blob: dd5a2c25b37be8bd698253f75731de8dd8d34bb9 [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010013#include <ctype.h>
Mark Lakes56cc1252018-03-27 09:48:06 +020014#include <limits.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020015#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010016
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010017#include <lauxlib.h>
18#include <lua.h>
19#include <lualib.h>
20
Thierry FOURNIER463119c2015-03-10 00:35:36 +010021#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
22#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010023#endif
24
Thierry FOURNIER380d0932015-01-23 14:27:52 +010025#include <ebpttree.h>
26
27#include <common/cfgparse.h>
Willy Tarreaub059b892018-10-16 17:57:36 +020028#include <common/compiler.h>
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +020029#include <common/hathreads.h>
Willy Tarreau0108d902018-11-25 19:14:37 +010030#include <common/initcall.h>
31#include <common/xref.h>
Christopher Faulet724a12c2018-12-13 22:12:15 +010032#include <common/h1.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010033
William Lallemand9ed62032016-11-21 17:49:11 +010034#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010035#include <types/hlua.h>
36#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010037#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010038
Thierry FOURNIER55da1652015-01-23 11:36:30 +010039#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020040#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010041#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010042#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010043#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010044#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010045#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010046#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010047#include <proto/hlua_fcn.h>
Willy Tarreau79e57332018-10-02 16:01:16 +020048#include <proto/http_fetch.h>
Christopher Faulet724a12c2018-12-13 22:12:15 +010049#include <proto/http_htx.h>
Willy Tarreau61c112a2018-10-02 16:43:32 +020050#include <proto/http_rules.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020051#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010052#include <proto/obj_type.h>
Patrick Hemmer268a7072018-05-11 12:52:31 -040053#include <proto/queue.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010054#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010055#include <proto/payload.h>
56#include <proto/proto_http.h>
57#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010058#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020059#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020060#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010061#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010062#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010063#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020064#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010065
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010066/* Lua uses longjmp to perform yield or throwing errors. This
67 * macro is used only for identifying the function that can
68 * not return because a longjmp is executed.
69 * __LJMP marks a prototype of hlua file that can use longjmp.
70 * WILL_LJMP() marks an lua function that will use longjmp.
71 * MAY_LJMP() marks an lua function that may use longjmp.
72 */
73#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020074#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010075#define MAY_LJMP(func) func
76
Thierry FOURNIERbabae282015-09-17 11:36:37 +020077/* This couple of function executes securely some Lua calls outside of
78 * the lua runtime environment. Each Lua call can return a longjmp
79 * if it encounter a memory error.
80 *
81 * Lua documentation extract:
82 *
83 * If an error happens outside any protected environment, Lua calls
84 * a panic function (see lua_atpanic) and then calls abort, thus
85 * exiting the host application. Your panic function can avoid this
86 * exit by never returning (e.g., doing a long jump to your own
87 * recovery point outside Lua).
88 *
89 * The panic function runs as if it were a message handler (see
90 * §2.3); in particular, the error message is at the top of the
91 * stack. However, there is no guarantee about stack space. To push
92 * anything on the stack, the panic function must first check the
93 * available space (see §4.2).
94 *
95 * We must check all the Lua entry point. This includes:
96 * - The include/proto/hlua.h exported functions
97 * - the task wrapper function
98 * - The action wrapper function
99 * - The converters wrapper function
100 * - The sample-fetch wrapper functions
101 *
102 * It is tolerated that the initilisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800103 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200104 *
105 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
106 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
107 * because they must be exists in the program stack when the longjmp
108 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200109 *
110 * Note that the Lua processing is not really thread safe. It provides
111 * heavy system which consists to add our own lock function in the Lua
112 * code and recompile the library. This system will probably not accepted
113 * by maintainers of various distribs.
114 *
115 * Our main excution point of the Lua is the function lua_resume(). A
116 * quick looking on the Lua sources displays a lua_lock() a the start
117 * of function and a lua_unlock() at the end of the function. So I
118 * conclude that the Lua thread safe mode just perform a mutex around
119 * all execution. So I prefer to do this in the HAProxy code, it will be
120 * easier for distro maintainers.
121 *
122 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
123 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
124 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200125 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100126__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200127THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200128static int hlua_panic_safe(lua_State *L) { return 0; }
129static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
130
131#define SET_SAFE_LJMP(__L) \
132 ({ \
133 int ret; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100134 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200135 if (setjmp(safe_ljmp_env) != 0) { \
136 lua_atpanic(__L, hlua_panic_safe); \
137 ret = 0; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100138 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200139 } else { \
140 lua_atpanic(__L, hlua_panic_ljmp); \
141 ret = 1; \
142 } \
143 ret; \
144 })
145
146/* If we are the last function catching Lua errors, we
147 * must reset the panic function.
148 */
149#define RESET_SAFE_LJMP(__L) \
150 do { \
151 lua_atpanic(__L, hlua_panic_safe); \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100152 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200153 } while(0)
154
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200155/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200156#define APPLET_DONE 0x01 /* applet processing is done. */
157#define APPLET_100C 0x02 /* 100 continue expected. */
158#define APPLET_HDR_SENT 0x04 /* Response header sent. */
159#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
160#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100161#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200162
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100163/* The main Lua execution context. */
164struct hlua gL;
165
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100166/* This is the memory pool containing struct lua for applets
167 * (including cli).
168 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100169DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100170
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100171/* Used for Socket connection. */
172static struct proxy socket_proxy;
173static struct server socket_tcp;
174#ifdef USE_OPENSSL
175static struct server socket_ssl;
176#endif
177
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100178/* List head of the function called at the initialisation time. */
179struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
180
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100181/* The following variables contains the reference of the different
182 * Lua classes. These references are useful for identify metadata
183 * associated with an object.
184 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100185static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100186static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100187static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100188static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100189static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100190static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200191static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200192static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200193static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100194
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100195/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200196 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100197 * short timeout. Lua linked with tasks doesn't have a timeout
198 * because a task may remain alive during all the haproxy execution.
199 */
200static unsigned int hlua_timeout_session = 4000; /* session timeout. */
201static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200202static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100203
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100204/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
205 * it is used for preventing infinite loops.
206 *
207 * I test the scheer with an infinite loop containing one incrementation
208 * and one test. I run this loop between 10 seconds, I raise a ceil of
209 * 710M loops from one interrupt each 9000 instructions, so I fix the value
210 * to one interrupt each 10 000 instructions.
211 *
212 * configured | Number of
213 * instructions | loops executed
214 * between two | in milions
215 * forced yields |
216 * ---------------+---------------
217 * 10 | 160
218 * 500 | 670
219 * 1000 | 680
220 * 5000 | 700
221 * 7000 | 700
222 * 8000 | 700
223 * 9000 | 710 <- ceil
224 * 10000 | 710
225 * 100000 | 710
226 * 1000000 | 710
227 *
228 */
229static unsigned int hlua_nb_instruction = 10000;
230
Willy Tarreau32f61e22015-03-18 17:54:59 +0100231/* Descriptor for the memory allocation state. If limit is not null, it will
232 * be enforced on any memory allocation.
233 */
234struct hlua_mem_allocator {
235 size_t allocated;
236 size_t limit;
237};
238
239static struct hlua_mem_allocator hlua_global_allocator;
240
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200241static const char error_500[] =
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200242 "HTTP/1.0 500 Internal Server Error\r\n"
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200243 "Cache-Control: no-cache\r\n"
244 "Connection: close\r\n"
245 "Content-Type: text/html\r\n"
246 "\r\n"
Joseph Herlant7fe15772018-11-15 10:07:32 -0800247 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occurred.\n</body></html>\n";
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200248
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100249/* These functions converts types between HAProxy internal args or
250 * sample and LUA types. Another function permits to check if the
251 * LUA stack contains arguments according with an required ARG_T
252 * format.
253 */
254static int hlua_arg2lua(lua_State *L, const struct arg *arg);
255static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100256__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100257 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100258static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100259static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100260static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
261
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200262__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
263
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200264#define SEND_ERR(__be, __fmt, __args...) \
265 do { \
266 send_log(__be, LOG_ERR, __fmt, ## __args); \
267 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100268 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200269 } while (0)
270
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100271/* Used to check an Lua function type in the stack. It creates and
272 * returns a reference of the function. This function throws an
273 * error if the rgument is not a "function".
274 */
275__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
276{
277 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100278 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100279 WILL_LJMP(luaL_argerror(L, argno, msg));
280 }
281 lua_pushvalue(L, argno);
282 return luaL_ref(L, LUA_REGISTRYINDEX);
283}
284
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200285/* Return the string that is of the top of the stack. */
286const char *hlua_get_top_error_string(lua_State *L)
287{
288 if (lua_gettop(L) < 1)
289 return "unknown error";
290 if (lua_type(L, -1) != LUA_TSTRING)
291 return "unknown error";
292 return lua_tostring(L, -1);
293}
294
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200295__LJMP static const char *hlua_traceback(lua_State *L)
296{
297 lua_Debug ar;
298 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200299 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200300 int filled = 0;
301
302 while (lua_getstack(L, level++, &ar)) {
303
304 /* Add separator */
305 if (filled)
306 chunk_appendf(msg, ", ");
307 filled = 1;
308
309 /* Fill fields:
310 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
311 * 'l': fills in the field currentline;
312 * 'n': fills in the field name and namewhat;
313 * 't': fills in the field istailcall;
314 */
315 lua_getinfo(L, "Slnt", &ar);
316
317 /* Append code localisation */
318 if (ar.currentline > 0)
319 chunk_appendf(msg, "%s:%d ", ar.short_src, ar.currentline);
320 else
321 chunk_appendf(msg, "%s ", ar.short_src);
322
323 /*
324 * Get function name
325 *
326 * if namewhat is no empty, name is defined.
327 * what contains "Lua" for Lua function, "C" for C function,
328 * or "main" for main code.
329 */
330 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
331 chunk_appendf(msg, "%s '%s'", ar.namewhat, ar.name); /* use it */
332
333 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
334 chunk_appendf(msg, "main chunk");
335
336 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
337 chunk_appendf(msg, "C function line %d", ar.linedefined);
338
339 else /* nothing left... */
340 chunk_appendf(msg, "?");
341
342
343 /* Display tailed call */
344 if (ar.istailcall)
345 chunk_appendf(msg, " ...");
346 }
347
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200348 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200349}
350
351
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100352/* This function check the number of arguments available in the
353 * stack. If the number of arguments available is not the same
354 * then <nb> an error is throwed.
355 */
356__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
357{
358 if (lua_gettop(L) == nb)
359 return;
360 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
361}
362
Mark Lakes22154b42018-01-29 14:38:40 -0800363/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100364 * and the line number where the error is encountered.
365 */
366static int hlua_pusherror(lua_State *L, const char *fmt, ...)
367{
368 va_list argp;
369 va_start(argp, fmt);
370 luaL_where(L, 1);
371 lua_pushvfstring(L, fmt, argp);
372 va_end(argp);
373 lua_concat(L, 2);
374 return 1;
375}
376
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100377/* This functions is used with sample fetch and converters. It
378 * converts the HAProxy configuration argument in a lua stack
379 * values.
380 *
381 * It takes an array of "arg", and each entry of the array is
382 * converted and pushed in the LUA stack.
383 */
384static int hlua_arg2lua(lua_State *L, const struct arg *arg)
385{
386 switch (arg->type) {
387 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100388 case ARGT_TIME:
389 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100390 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100391 break;
392
393 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200394 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100395 break;
396
397 case ARGT_IPV4:
398 case ARGT_IPV6:
399 case ARGT_MSK4:
400 case ARGT_MSK6:
401 case ARGT_FE:
402 case ARGT_BE:
403 case ARGT_TAB:
404 case ARGT_SRV:
405 case ARGT_USR:
406 case ARGT_MAP:
407 default:
408 lua_pushnil(L);
409 break;
410 }
411 return 1;
412}
413
414/* This function take one entrie in an LUA stack at the index "ud",
415 * and try to convert it in an HAProxy argument entry. This is useful
416 * with sample fetch wrappers. The input arguments are gived to the
417 * lua wrapper and converted as arg list by thi function.
418 */
419static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
420{
421 switch (lua_type(L, ud)) {
422
423 case LUA_TNUMBER:
424 case LUA_TBOOLEAN:
425 arg->type = ARGT_SINT;
426 arg->data.sint = lua_tointeger(L, ud);
427 break;
428
429 case LUA_TSTRING:
430 arg->type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200431 arg->data.str.area = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100432 break;
433
434 case LUA_TUSERDATA:
435 case LUA_TNIL:
436 case LUA_TTABLE:
437 case LUA_TFUNCTION:
438 case LUA_TTHREAD:
439 case LUA_TLIGHTUSERDATA:
440 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200441 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100442 break;
443 }
444 return 1;
445}
446
447/* the following functions are used to convert a struct sample
448 * in Lua type. This useful to convert the return of the
449 * fetchs or converters.
450 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100451static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100452{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200453 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100454 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100455 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200456 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100457 break;
458
459 case SMP_T_BIN:
460 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200461 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100462 break;
463
464 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200465 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100466 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
467 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
468 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
469 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
470 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
471 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
472 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
473 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
474 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200475 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100476 break;
477 default:
478 lua_pushnil(L);
479 break;
480 }
481 break;
482
483 case SMP_T_IPV4:
484 case SMP_T_IPV6:
485 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200486 if (sample_casts[smp->data.type][SMP_T_STR] &&
487 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200488 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100489 else
490 lua_pushnil(L);
491 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100492 default:
493 lua_pushnil(L);
494 break;
495 }
496 return 1;
497}
498
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100499/* the following functions are used to convert a struct sample
500 * in Lua strings. This is useful to convert the return of the
501 * fetchs or converters.
502 */
503static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
504{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200505 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100506
507 case SMP_T_BIN:
508 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200509 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100510 break;
511
512 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200513 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100514 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
515 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
516 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
517 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
518 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
519 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
520 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
521 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
522 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200523 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100524 break;
525 default:
526 lua_pushstring(L, "");
527 break;
528 }
529 break;
530
531 case SMP_T_SINT:
532 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100533 case SMP_T_IPV4:
534 case SMP_T_IPV6:
535 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200536 if (sample_casts[smp->data.type][SMP_T_STR] &&
537 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200538 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100539 else
540 lua_pushstring(L, "");
541 break;
542 default:
543 lua_pushstring(L, "");
544 break;
545 }
546 return 1;
547}
548
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100549/* the following functions are used to convert an Lua type in a
550 * struct sample. This is useful to provide data from a converter
551 * to the LUA code.
552 */
553static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
554{
555 switch (lua_type(L, ud)) {
556
557 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200558 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200559 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100560 break;
561
562
563 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200564 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200565 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100566 break;
567
568 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200569 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100570 smp->flags |= SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200571 smp->data.u.str.area = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100572 break;
573
574 case LUA_TUSERDATA:
575 case LUA_TNIL:
576 case LUA_TTABLE:
577 case LUA_TFUNCTION:
578 case LUA_TTHREAD:
579 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200580 case LUA_TNONE:
581 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200582 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200583 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100584 break;
585 }
586 return 1;
587}
588
589/* This function check the "argp" builded by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800590 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100591 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100592 *
593 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
594 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100595 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100596__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100597 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100598{
599 int min_arg;
600 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100601 struct proxy *px;
602 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100603
604 idx = 0;
605 min_arg = ARGM(mask);
606 mask >>= ARGM_BITS;
607
608 while (1) {
609
610 /* Check oversize. */
611 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100612 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100613 }
614
615 /* Check for mandatory arguments. */
616 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100617 if (idx < min_arg) {
618
619 /* If miss other argument than the first one, we return an error. */
620 if (idx > 0)
621 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
622
623 /* If first argument have a certain type, some default values
624 * may be used. See the function smp_resolve_args().
625 */
626 switch (mask & ARGT_MASK) {
627
628 case ARGT_FE:
629 if (!(p->cap & PR_CAP_FE))
630 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
631 argp[idx].data.prx = p;
632 argp[idx].type = ARGT_FE;
633 argp[idx+1].type = ARGT_STOP;
634 break;
635
636 case ARGT_BE:
637 if (!(p->cap & PR_CAP_BE))
638 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
639 argp[idx].data.prx = p;
640 argp[idx].type = ARGT_BE;
641 argp[idx+1].type = ARGT_STOP;
642 break;
643
644 case ARGT_TAB:
645 argp[idx].data.prx = p;
646 argp[idx].type = ARGT_TAB;
647 argp[idx+1].type = ARGT_STOP;
648 break;
649
650 default:
651 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
652 break;
653 }
654 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100655 return 0;
656 }
657
658 /* Check for exceed the number of requiered argument. */
659 if ((mask & ARGT_MASK) == ARGT_STOP &&
660 argp[idx].type != ARGT_STOP) {
661 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
662 }
663
664 if ((mask & ARGT_MASK) == ARGT_STOP &&
665 argp[idx].type == ARGT_STOP) {
666 return 0;
667 }
668
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100669 /* Convert some argument types. */
670 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100671 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100672 if (argp[idx].type != ARGT_SINT)
673 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
674 argp[idx].type = ARGT_SINT;
675 break;
676
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100677 case ARGT_TIME:
678 if (argp[idx].type != ARGT_SINT)
679 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200680 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100681 break;
682
683 case ARGT_SIZE:
684 if (argp[idx].type != ARGT_SINT)
685 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200686 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100687 break;
688
689 case ARGT_FE:
690 if (argp[idx].type != ARGT_STR)
691 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200692 memcpy(trash.area, argp[idx].data.str.area,
693 argp[idx].data.str.data);
694 trash.area[argp[idx].data.str.data] = 0;
695 argp[idx].data.prx = proxy_fe_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100696 if (!argp[idx].data.prx)
697 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
698 argp[idx].type = ARGT_FE;
699 break;
700
701 case ARGT_BE:
702 if (argp[idx].type != ARGT_STR)
703 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200704 memcpy(trash.area, argp[idx].data.str.area,
705 argp[idx].data.str.data);
706 trash.area[argp[idx].data.str.data] = 0;
707 argp[idx].data.prx = proxy_be_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100708 if (!argp[idx].data.prx)
709 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
710 argp[idx].type = ARGT_BE;
711 break;
712
713 case ARGT_TAB:
714 if (argp[idx].type != ARGT_STR)
715 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200716 memcpy(trash.area, argp[idx].data.str.area,
717 argp[idx].data.str.data);
718 trash.area[argp[idx].data.str.data] = 0;
719 argp[idx].data.prx = proxy_tbl_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100720 if (!argp[idx].data.prx)
721 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
722 argp[idx].type = ARGT_TAB;
723 break;
724
725 case ARGT_SRV:
726 if (argp[idx].type != ARGT_STR)
727 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200728 memcpy(trash.area, argp[idx].data.str.area,
729 argp[idx].data.str.data);
730 trash.area[argp[idx].data.str.data] = 0;
731 sname = strrchr(trash.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100732 if (sname) {
733 *sname++ = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200734 pname = trash.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200735 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100736 if (!px)
737 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
738 }
739 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200740 sname = trash.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100741 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100742 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100743 argp[idx].data.srv = findserver(px, sname);
744 if (!argp[idx].data.srv)
745 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
746 argp[idx].type = ARGT_SRV;
747 break;
748
749 case ARGT_IPV4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200750 memcpy(trash.area, argp[idx].data.str.area,
751 argp[idx].data.str.data);
752 trash.area[argp[idx].data.str.data] = 0;
753 if (inet_pton(AF_INET, trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100754 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
755 argp[idx].type = ARGT_IPV4;
756 break;
757
758 case ARGT_MSK4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200759 memcpy(trash.area, argp[idx].data.str.area,
760 argp[idx].data.str.data);
761 trash.area[argp[idx].data.str.data] = 0;
762 if (!str2mask(trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100763 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
764 argp[idx].type = ARGT_MSK4;
765 break;
766
767 case ARGT_IPV6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200768 memcpy(trash.area, argp[idx].data.str.area,
769 argp[idx].data.str.data);
770 trash.area[argp[idx].data.str.data] = 0;
771 if (inet_pton(AF_INET6, trash.area, &argp[idx].data.ipv6))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100772 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
773 argp[idx].type = ARGT_IPV6;
774 break;
775
776 case ARGT_MSK6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200777 memcpy(trash.area, argp[idx].data.str.area,
778 argp[idx].data.str.data);
779 trash.area[argp[idx].data.str.data] = 0;
780 if (!str2mask6(trash.area, &argp[idx].data.ipv6))
Tim Duesterhusb814da62018-01-25 16:24:50 +0100781 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 mask"));
782 argp[idx].type = ARGT_MSK6;
783 break;
784
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100785 case ARGT_MAP:
786 case ARGT_REG:
787 case ARGT_USR:
788 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100789 break;
790 }
791
792 /* Check for type of argument. */
793 if ((mask & ARGT_MASK) != argp[idx].type) {
794 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
795 arg_type_names[(mask & ARGT_MASK)],
796 arg_type_names[argp[idx].type & ARGT_MASK]);
797 WILL_LJMP(luaL_argerror(L, first + idx, msg));
798 }
799
800 /* Next argument. */
801 mask >>= ARGT_BITS;
802 idx++;
803 }
804}
805
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100806/*
807 * The following functions are used to make correspondance between the the
808 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100809 *
810 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100811 * - hlua_sethlua : create the association between hlua context and lua_state.
812 */
813static inline struct hlua *hlua_gethlua(lua_State *L)
814{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100815 struct hlua **hlua = lua_getextraspace(L);
816 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100817}
818static inline void hlua_sethlua(struct hlua *hlua)
819{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100820 struct hlua **hlua_store = lua_getextraspace(hlua->T);
821 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100822}
823
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100824/* This function is used to send logs. It try to send on screen (stderr)
825 * and on the default syslog server.
826 */
827static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
828{
829 struct tm tm;
830 char *p;
831
832 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200833 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100834 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200835 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200836 /* Break the message if exceed the buffer size. */
837 *(p-4) = ' ';
838 *(p-3) = '.';
839 *(p-2) = '.';
840 *(p-1) = '.';
841 break;
842 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100843 if (isprint(*msg))
844 *p = *msg;
845 else
846 *p = '.';
847 }
848 *p = '\0';
849
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200850 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100851 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200852 get_localtime(date.tv_sec, &tm);
853 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100854 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200855 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100856 fflush(stderr);
857 }
858}
859
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100860/* This function just ensure that the yield will be always
861 * returned with a timeout and permit to set some flags
862 */
863__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100864 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100865{
866 struct hlua *hlua = hlua_gethlua(L);
867
868 /* Set the wake timeout. If timeout is required, we set
869 * the expiration time.
870 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200871 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100872
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100873 hlua->flags |= flags;
874
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100875 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +0200876 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100877}
878
Willy Tarreau87b09662015-04-03 00:22:06 +0200879/* This function initialises the Lua environment stored in the stream.
880 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100881 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200882 *
883 * This function is particular. it initialises a new Lua thread. If the
884 * initialisation fails (example: out of memory error), the lua function
885 * throws an error (longjmp).
886 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100887 * In some case (at least one), this function can be called from safe
888 * environement, so we must not initialise it. While the support of
889 * threads appear, the safe environment set a lock to ensure only one
890 * Lua execution at a time. If we initialize safe environment in another
891 * safe environmenet, we have a dead lock.
892 *
893 * set "already_safe" true if the context is initialized form safe
894 * Lua fonction.
895 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800896 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200897 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800898 * MUST NOT manipulate the created thread stack state, because it is not
899 * proctected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100900 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100901int hlua_ctx_init(struct hlua *lua, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100902{
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100903 if (!already_safe) {
904 if (!SET_SAFE_LJMP(gL.T)) {
905 lua->Tref = LUA_REFNIL;
906 return 0;
907 }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200908 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100909 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100910 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100911 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100912 lua->T = lua_newthread(gL.T);
913 if (!lua->T) {
914 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100915 if (!already_safe)
916 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100917 return 0;
918 }
919 hlua_sethlua(lua);
920 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
921 lua->task = task;
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 1;
925}
926
Willy Tarreau87b09662015-04-03 00:22:06 +0200927/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100928 * is destroyed. The destroy also the memory context. The struct "lua"
929 * is not freed.
930 */
931void hlua_ctx_destroy(struct hlua *lua)
932{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100933 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100934 return;
935
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100936 if (!lua->T)
937 goto end;
938
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100939 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200940 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100941
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200942 if (!SET_SAFE_LJMP(lua->T))
943 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100944 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200945 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200946
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200947 if (!SET_SAFE_LJMP(gL.T))
948 return;
949 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
950 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200951 /* Forces a garbage collecting process. If the Lua program is finished
952 * without error, we run the GC on the thread pointer. Its freed all
953 * the unused memory.
954 * If the thread is finnish with an error or is currently yielded,
955 * it seems that the GC applied on the thread doesn't clean anything,
956 * so e run the GC on the main thread.
957 * NOTE: maybe this action locks all the Lua threads untiml the en of
958 * the garbage collection.
959 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200960 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200961 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200962 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200963 lua_gc(gL.T, LUA_GCCOLLECT, 0);
964 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200965 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200966
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200967 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100968
969end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100970 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100971}
972
973/* This function is used to restore the Lua context when a coroutine
974 * fails. This function copy the common memory between old coroutine
975 * and the new coroutine. The old coroutine is destroyed, and its
976 * replaced by the new coroutine.
977 * If the flag "keep_msg" is set, the last entry of the old is assumed
978 * as string error message and it is copied in the new stack.
979 */
980static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
981{
982 lua_State *T;
983 int new_ref;
984
985 /* Renew the main LUA stack doesn't have sense. */
986 if (lua == &gL)
987 return 0;
988
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100989 /* New Lua coroutine. */
990 T = lua_newthread(gL.T);
991 if (!T)
992 return 0;
993
994 /* Copy last error message. */
995 if (keep_msg)
996 lua_xmove(lua->T, T, 1);
997
998 /* Copy data between the coroutines. */
999 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1000 lua_xmove(lua->T, T, 1);
1001 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
1002
1003 /* Destroy old data. */
1004 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1005
1006 /* The thread is garbage collected by Lua. */
1007 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1008
1009 /* Fill the struct with the new coroutine values. */
1010 lua->Mref = new_ref;
1011 lua->T = T;
1012 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1013
1014 /* Set context. */
1015 hlua_sethlua(lua);
1016
1017 return 1;
1018}
1019
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001020void hlua_hook(lua_State *L, lua_Debug *ar)
1021{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001022 struct hlua *hlua = hlua_gethlua(L);
1023
1024 /* Lua cannot yield when its returning from a function,
1025 * so, we can fix the interrupt hook to 1 instruction,
1026 * expecting that the function is finnished.
1027 */
1028 if (lua_gethookmask(L) & LUA_MASKRET) {
1029 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1030 return;
1031 }
1032
1033 /* restore the interrupt condition. */
1034 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1035
1036 /* If we interrupt the Lua processing in yieldable state, we yield.
1037 * If the state is not yieldable, trying yield causes an error.
1038 */
1039 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001040 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001041
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001042 /* If we cannot yield, update the clock and check the timeout. */
1043 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001044 hlua->run_time += now_ms - hlua->start_time;
1045 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001046 lua_pushfstring(L, "execution timeout");
1047 WILL_LJMP(lua_error(L));
1048 }
1049
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001050 /* Update the start time. */
1051 hlua->start_time = now_ms;
1052
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001053 /* Try to interrupt the process at the end of the current
1054 * unyieldable function.
1055 */
1056 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001057}
1058
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001059/* This function start or resumes the Lua stack execution. If the flag
1060 * "yield_allowed" if no set and the LUA stack execution returns a yield
1061 * The function return an error.
1062 *
1063 * The function can returns 4 values:
1064 * - HLUA_E_OK : The execution is terminated without any errors.
1065 * - HLUA_E_AGAIN : The execution must continue at the next associated
1066 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001067 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001068 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001069 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001070 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001071 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001072 * LUA code.
1073 */
1074static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1075{
1076 int ret;
1077 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001078 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001079
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001080 /* Initialise run time counter. */
1081 if (!HLUA_IS_RUNNING(lua))
1082 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001083
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001084 /* Lock the whole Lua execution. This lock must be before the
1085 * label "resume_execution".
1086 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001087 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001088
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001089resume_execution:
1090
1091 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1092 * instructions. it is used for preventing infinite loops.
1093 */
1094 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1095
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001096 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001097 HLUA_SET_RUN(lua);
1098 HLUA_CLR_CTRLYIELD(lua);
1099 HLUA_CLR_WAKERESWR(lua);
1100 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001101
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001102 /* Update the start time. */
1103 lua->start_time = now_ms;
1104
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001105 /* Call the function. */
1106 ret = lua_resume(lua->T, gL.T, lua->nargs);
1107 switch (ret) {
1108
1109 case LUA_OK:
1110 ret = HLUA_E_OK;
1111 break;
1112
1113 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001114 /* Check if the execution timeout is expired. It it is the case, we
1115 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001116 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001117 tv_update_date(0, 1);
1118 lua->run_time += now_ms - lua->start_time;
1119 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001120 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001121 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001122 break;
1123 }
1124 /* Process the forced yield. if the general yield is not allowed or
1125 * if no task were associated this the current Lua execution
1126 * coroutine, we resume the execution. Else we want to return in the
1127 * scheduler and we want to be waked up again, to continue the
1128 * current Lua execution. So we schedule our own task.
1129 */
1130 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001131 if (!yield_allowed || !lua->task)
1132 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001133 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001134 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001135 if (!yield_allowed) {
1136 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001137 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001138 break;
1139 }
1140 ret = HLUA_E_AGAIN;
1141 break;
1142
1143 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001144
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001145 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001146 * because the errors ares the only one mean to return immediately
1147 * from and lua execution.
1148 */
1149 if (lua->flags & HLUA_EXIT) {
1150 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001151 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001152 break;
1153 }
1154
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001155 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001156 if (!lua_checkstack(lua->T, 1)) {
1157 ret = HLUA_E_ERR;
1158 break;
1159 }
1160 msg = lua_tostring(lua->T, -1);
1161 lua_settop(lua->T, 0); /* Empty the stack. */
1162 lua_pop(lua->T, 1);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001163 trace = hlua_traceback(lua->T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001164 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001165 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001166 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001167 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001168 ret = HLUA_E_ERRMSG;
1169 break;
1170
1171 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001172 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001173 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001174 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001175 break;
1176
1177 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001178 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001179 if (!lua_checkstack(lua->T, 1)) {
1180 ret = HLUA_E_ERR;
1181 break;
1182 }
1183 msg = lua_tostring(lua->T, -1);
1184 lua_settop(lua->T, 0); /* Empty the stack. */
1185 lua_pop(lua->T, 1);
1186 if (msg)
1187 lua_pushfstring(lua->T, "message handler error: %s", msg);
1188 else
1189 lua_pushfstring(lua->T, "message handler error");
1190 ret = HLUA_E_ERRMSG;
1191 break;
1192
1193 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001194 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001195 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001196 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001197 break;
1198 }
1199
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001200 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001201 if (lua->flags & HLUA_MUST_GC &&
1202 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001203 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1204
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001205 switch (ret) {
1206 case HLUA_E_AGAIN:
1207 break;
1208
1209 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001210 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001211 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001212 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001213 break;
1214
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001215 case HLUA_E_ETMOUT:
1216 case HLUA_E_NOMEM:
1217 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001218 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001219 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001220 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001221 hlua_ctx_renew(lua, 0);
1222 break;
1223
1224 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001225 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001226 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001227 break;
1228 }
1229
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001230 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001231 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001232
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001233 return ret;
1234}
1235
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001236/* This function exit the current code. */
1237__LJMP static int hlua_done(lua_State *L)
1238{
1239 struct hlua *hlua = hlua_gethlua(L);
1240
1241 hlua->flags |= HLUA_EXIT;
1242 WILL_LJMP(lua_error(L));
1243
1244 return 0;
1245}
1246
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001247/* This function is an LUA binding. It provides a function
1248 * for deleting ACL from a referenced ACL file.
1249 */
1250__LJMP static int hlua_del_acl(lua_State *L)
1251{
1252 const char *name;
1253 const char *key;
1254 struct pat_ref *ref;
1255
1256 MAY_LJMP(check_args(L, 2, "del_acl"));
1257
1258 name = MAY_LJMP(luaL_checkstring(L, 1));
1259 key = MAY_LJMP(luaL_checkstring(L, 2));
1260
1261 ref = pat_ref_lookup(name);
1262 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001263 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001264
1265 pat_ref_delete(ref, key);
1266 return 0;
1267}
1268
1269/* This function is an LUA binding. It provides a function
1270 * for deleting map entry from a referenced map file.
1271 */
1272static int hlua_del_map(lua_State *L)
1273{
1274 const char *name;
1275 const char *key;
1276 struct pat_ref *ref;
1277
1278 MAY_LJMP(check_args(L, 2, "del_map"));
1279
1280 name = MAY_LJMP(luaL_checkstring(L, 1));
1281 key = MAY_LJMP(luaL_checkstring(L, 2));
1282
1283 ref = pat_ref_lookup(name);
1284 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001285 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001286
1287 pat_ref_delete(ref, key);
1288 return 0;
1289}
1290
1291/* This function is an LUA binding. It provides a function
1292 * for adding ACL pattern from a referenced ACL file.
1293 */
1294static int hlua_add_acl(lua_State *L)
1295{
1296 const char *name;
1297 const char *key;
1298 struct pat_ref *ref;
1299
1300 MAY_LJMP(check_args(L, 2, "add_acl"));
1301
1302 name = MAY_LJMP(luaL_checkstring(L, 1));
1303 key = MAY_LJMP(luaL_checkstring(L, 2));
1304
1305 ref = pat_ref_lookup(name);
1306 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001307 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001308
1309 if (pat_ref_find_elt(ref, key) == NULL)
1310 pat_ref_add(ref, key, NULL, NULL);
1311 return 0;
1312}
1313
1314/* This function is an LUA binding. It provides a function
1315 * for setting map pattern and sample from a referenced map
1316 * file.
1317 */
1318static int hlua_set_map(lua_State *L)
1319{
1320 const char *name;
1321 const char *key;
1322 const char *value;
1323 struct pat_ref *ref;
1324
1325 MAY_LJMP(check_args(L, 3, "set_map"));
1326
1327 name = MAY_LJMP(luaL_checkstring(L, 1));
1328 key = MAY_LJMP(luaL_checkstring(L, 2));
1329 value = MAY_LJMP(luaL_checkstring(L, 3));
1330
1331 ref = pat_ref_lookup(name);
1332 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001333 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001334
1335 if (pat_ref_find_elt(ref, key) != NULL)
1336 pat_ref_set(ref, key, value, NULL);
1337 else
1338 pat_ref_add(ref, key, value, NULL);
1339 return 0;
1340}
1341
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001342/* A class is a lot of memory that contain data. This data can be a table,
1343 * an integer or user data. This data is associated with a metatable. This
1344 * metatable have an original version registred in the global context with
1345 * the name of the object (_G[<name>] = <metable> ).
1346 *
1347 * A metable is a table that modify the standard behavior of a standard
1348 * access to the associated data. The entries of this new metatable are
1349 * defined as is:
1350 *
1351 * http://lua-users.org/wiki/MetatableEvents
1352 *
1353 * __index
1354 *
1355 * we access an absent field in a table, the result is nil. This is
1356 * true, but it is not the whole truth. Actually, such access triggers
1357 * the interpreter to look for an __index metamethod: If there is no
1358 * such method, as usually happens, then the access results in nil;
1359 * otherwise, the metamethod will provide the result.
1360 *
1361 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1362 * the key does not appear in the table, but the metatable has an __index
1363 * property:
1364 *
1365 * - if the value is a function, the function is called, passing in the
1366 * table and the key; the return value of that function is returned as
1367 * the result.
1368 *
1369 * - if the value is another table, the value of the key in that table is
1370 * asked for and returned (and if it doesn't exist in that table, but that
1371 * table's metatable has an __index property, then it continues on up)
1372 *
1373 * - Use "rawget(myTable,key)" to skip this metamethod.
1374 *
1375 * http://www.lua.org/pil/13.4.1.html
1376 *
1377 * __newindex
1378 *
1379 * Like __index, but control property assignment.
1380 *
1381 * __mode - Control weak references. A string value with one or both
1382 * of the characters 'k' and 'v' which specifies that the the
1383 * keys and/or values in the table are weak references.
1384 *
1385 * __call - Treat a table like a function. When a table is followed by
1386 * parenthesis such as "myTable( 'foo' )" and the metatable has
1387 * a __call key pointing to a function, that function is invoked
1388 * (passing any specified arguments) and the return value is
1389 * returned.
1390 *
1391 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1392 * called, if the metatable for myTable has a __metatable
1393 * key, the value of that key is returned instead of the
1394 * actual metatable.
1395 *
1396 * __tostring - Control string representation. When the builtin
1397 * "tostring( myTable )" function is called, if the metatable
1398 * for myTable has a __tostring property set to a function,
1399 * that function is invoked (passing myTable to it) and the
1400 * return value is used as the string representation.
1401 *
1402 * __len - Control table length. When the table length is requested using
1403 * the length operator ( '#' ), if the metatable for myTable has
1404 * a __len key pointing to a function, that function is invoked
1405 * (passing myTable to it) and the return value used as the value
1406 * of "#myTable".
1407 *
1408 * __gc - Userdata finalizer code. When userdata is set to be garbage
1409 * collected, if the metatable has a __gc field pointing to a
1410 * function, that function is first invoked, passing the userdata
1411 * to it. The __gc metamethod is not called for tables.
1412 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1413 *
1414 * Special metamethods for redefining standard operators:
1415 * http://www.lua.org/pil/13.1.html
1416 *
1417 * __add "+"
1418 * __sub "-"
1419 * __mul "*"
1420 * __div "/"
1421 * __unm "!"
1422 * __pow "^"
1423 * __concat ".."
1424 *
1425 * Special methods for redfining standar relations
1426 * http://www.lua.org/pil/13.2.html
1427 *
1428 * __eq "=="
1429 * __lt "<"
1430 * __le "<="
1431 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001432
1433/*
1434 *
1435 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001436 * Class Map
1437 *
1438 *
1439 */
1440
1441/* Returns a struct hlua_map if the stack entry "ud" is
1442 * a class session, otherwise it throws an error.
1443 */
1444__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1445{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001446 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001447}
1448
1449/* This function is the map constructor. It don't need
1450 * the class Map object. It creates and return a new Map
1451 * object. It must be called only during "body" or "init"
1452 * context because it process some filesystem accesses.
1453 */
1454__LJMP static int hlua_map_new(struct lua_State *L)
1455{
1456 const char *fn;
1457 int match = PAT_MATCH_STR;
1458 struct sample_conv conv;
1459 const char *file = "";
1460 int line = 0;
1461 lua_Debug ar;
1462 char *err = NULL;
1463 struct arg args[2];
1464
1465 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1466 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1467
1468 fn = MAY_LJMP(luaL_checkstring(L, 1));
1469
1470 if (lua_gettop(L) >= 2) {
1471 match = MAY_LJMP(luaL_checkinteger(L, 2));
1472 if (match < 0 || match >= PAT_MATCH_NUM)
1473 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1474 }
1475
1476 /* Get Lua filename and line number. */
1477 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1478 lua_getinfo(L, "Sl", &ar); /* get info about it */
1479 if (ar.currentline > 0) { /* is there info? */
1480 file = ar.short_src;
1481 line = ar.currentline;
1482 }
1483 }
1484
1485 /* fill fake sample_conv struct. */
1486 conv.kw = ""; /* unused. */
1487 conv.process = NULL; /* unused. */
1488 conv.arg_mask = 0; /* unused. */
1489 conv.val_args = NULL; /* unused. */
1490 conv.out_type = SMP_T_STR;
1491 conv.private = (void *)(long)match;
1492 switch (match) {
1493 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1494 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1495 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1496 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1497 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1498 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1499 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001500 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001501 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1502 default:
1503 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1504 }
1505
1506 /* fill fake args. */
1507 args[0].type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001508 args[0].data.str.area = (char *)fn;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001509 args[1].type = ARGT_STOP;
1510
1511 /* load the map. */
1512 if (!sample_load_map(args, &conv, file, line, &err)) {
1513 /* error case: we cant use luaL_error because we must
1514 * free the err variable.
1515 */
1516 luaL_where(L, 1);
1517 lua_pushfstring(L, "'new': %s.", err);
1518 lua_concat(L, 2);
1519 free(err);
1520 WILL_LJMP(lua_error(L));
1521 }
1522
1523 /* create the lua object. */
1524 lua_newtable(L);
1525 lua_pushlightuserdata(L, args[0].data.map);
1526 lua_rawseti(L, -2, 0);
1527
1528 /* Pop a class Map metatable and affect it to the userdata. */
1529 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1530 lua_setmetatable(L, -2);
1531
1532
1533 return 1;
1534}
1535
1536__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1537{
1538 struct map_descriptor *desc;
1539 struct pattern *pat;
1540 struct sample smp;
1541
1542 MAY_LJMP(check_args(L, 2, "lookup"));
1543 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001544 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001545 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001546 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001547 }
1548 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001549 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001550 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001551 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 +02001552 }
1553
1554 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001555 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001556 if (str)
1557 lua_pushstring(L, "");
1558 else
1559 lua_pushnil(L);
1560 return 1;
1561 }
1562
1563 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001564 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001565 return 1;
1566}
1567
1568__LJMP static int hlua_map_lookup(struct lua_State *L)
1569{
1570 return _hlua_map_lookup(L, 0);
1571}
1572
1573__LJMP static int hlua_map_slookup(struct lua_State *L)
1574{
1575 return _hlua_map_lookup(L, 1);
1576}
1577
1578/*
1579 *
1580 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001581 * Class Socket
1582 *
1583 *
1584 */
1585
1586__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1587{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001588 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001589}
1590
1591/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001592 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001593 * received.
1594 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001595static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001596{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001597 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001598 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001599
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001600 if (appctx->ctx.hlua_cosocket.die) {
1601 si_shutw(si);
1602 si_shutr(si);
1603 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001604 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1605 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001606 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1607 }
1608
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001609 /* If the connection object is not available, close all the
1610 * streams and wakeup everything waiting for.
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001611 */
1612 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001613 si_shutw(si);
1614 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001615 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001616 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1617 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001618 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001619 }
1620
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001621 /* If we cant write, wakeup the pending write signals. */
1622 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001623 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001624
1625 /* If we cant read, wakeup the pending read signals. */
1626 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001627 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001628
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001629 /* if the connection is not estabkished, inform the stream that we want
1630 * to be notified whenever the connection completes.
1631 */
1632 if (!(c->flags & CO_FL_CONNECTED)) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001633 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001634 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001635 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001636 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001637 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001638
1639 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001640 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001641
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001642 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001643 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001644 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001645
1646 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001647 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001648 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001649
1650 /* Some data were injected in the buffer, notify the stream
1651 * interface.
1652 */
1653 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001654 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001655
1656 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001657 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001658 */
1659 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001660 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001661}
1662
Willy Tarreau87b09662015-04-03 00:22:06 +02001663/* This function is called when the "struct stream" is destroyed.
1664 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001665 * Wake all the pending signals.
1666 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001667static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001668{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001669 struct xref *peer;
1670
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001671 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001672 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1673 if (peer)
1674 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001675
1676 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001677 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1678 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001679}
1680
1681/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001682 * uses this object. If the stream does not exists, just quit.
1683 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001684 * pending signal can rest in the read and write lists. destroy
1685 * it.
1686 */
1687__LJMP static int hlua_socket_gc(lua_State *L)
1688{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001689 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001690 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001691 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001692
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001693 MAY_LJMP(check_args(L, 1, "__gc"));
1694
1695 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001696 peer = xref_get_peer_and_lock(&socket->xref);
1697 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001698 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001699 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001700
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001701 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001702 appctx->ctx.hlua_cosocket.die = 1;
1703 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001704
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001705 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001706 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001707 return 0;
1708}
1709
1710/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001711 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001712 */
sada05ed3302018-05-11 11:48:18 -07001713__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001714{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001715 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001716 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001717 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001718
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001719 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001720
1721 /* Check if we run on the same thread than the xreator thread.
1722 * We cannot access to the socket if the thread is different.
1723 */
1724 if (socket->tid != tid)
1725 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1726
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001727 peer = xref_get_peer_and_lock(&socket->xref);
1728 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001729 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001730 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001731
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001732 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001733 appctx->ctx.hlua_cosocket.die = 1;
1734 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001735
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001736 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001737 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001738 return 0;
1739}
1740
sada05ed3302018-05-11 11:48:18 -07001741/* The close function calls close_helper.
1742 */
1743__LJMP static int hlua_socket_close(lua_State *L)
1744{
1745 MAY_LJMP(check_args(L, 1, "close"));
1746 return hlua_socket_close_helper(L);
1747}
1748
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001749/* This Lua function assumes that the stack contain three parameters.
1750 * 1 - USERDATA containing a struct socket
1751 * 2 - INTEGER with values of the macro defined below
1752 * If the integer is -1, we must read at most one line.
1753 * If the integer is -2, we ust read all the data until the
1754 * end of the stream.
1755 * If the integer is positive value, we must read a number of
1756 * bytes corresponding to this value.
1757 */
1758#define HLSR_READ_LINE (-1)
1759#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001760__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001761{
1762 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1763 int wanted = lua_tointeger(L, 2);
1764 struct hlua *hlua = hlua_gethlua(L);
1765 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001766 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001767 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001768 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001769 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001770 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001771 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001772 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001773 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001774 struct stream_interface *si;
1775 struct stream *s;
1776 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001777 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001778
1779 /* Check if this lua stack is schedulable. */
1780 if (!hlua || !hlua->task)
1781 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1782 "'frontend', 'backend' or 'task'"));
1783
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001784 /* Check if we run on the same thread than the xreator thread.
1785 * We cannot access to the socket if the thread is different.
1786 */
1787 if (socket->tid != tid)
1788 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1789
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001790 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001791 peer = xref_get_peer_and_lock(&socket->xref);
1792 if (!peer)
1793 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001794 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1795 si = appctx->owner;
1796 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001797
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001798 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001799 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001800 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001801 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001802 if (nblk < 0) /* Connection close. */
1803 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001804 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001805 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001806
1807 /* remove final \r\n. */
1808 if (nblk == 1) {
1809 if (blk1[len1-1] == '\n') {
1810 len1--;
1811 skip_at_end++;
1812 if (blk1[len1-1] == '\r') {
1813 len1--;
1814 skip_at_end++;
1815 }
1816 }
1817 }
1818 else {
1819 if (blk2[len2-1] == '\n') {
1820 len2--;
1821 skip_at_end++;
1822 if (blk2[len2-1] == '\r') {
1823 len2--;
1824 skip_at_end++;
1825 }
1826 }
1827 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001828 }
1829
1830 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001831 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001832 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001833 if (nblk < 0) /* Connection close. */
1834 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001835 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001836 goto connection_empty;
1837 }
1838
1839 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001840 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001841 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001842 if (nblk < 0) /* Connection close. */
1843 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001844 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001845 goto connection_empty;
1846
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001847 missing_bytes = wanted - socket->b.n;
1848 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001849 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001850 len1 = missing_bytes;
1851 } if (nblk == 2 && len1 + len2 > missing_bytes)
1852 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001853 }
1854
1855 len = len1;
1856
1857 luaL_addlstring(&socket->b, blk1, len1);
1858 if (nblk == 2) {
1859 len += len2;
1860 luaL_addlstring(&socket->b, blk2, len2);
1861 }
1862
1863 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001864 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001865
1866 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001867 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001868
1869 /* If the pattern reclaim to read all the data
1870 * in the connection, got out.
1871 */
1872 if (wanted == HLSR_READ_ALL)
1873 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001874 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001875 goto connection_empty;
1876
1877 /* Return result. */
1878 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001879 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001880 return 1;
1881
1882connection_closed:
1883
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001884 xref_unlock(&socket->xref, peer);
1885
1886no_peer:
1887
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001888 /* If the buffer containds data. */
1889 if (socket->b.n > 0) {
1890 luaL_pushresult(&socket->b);
1891 return 1;
1892 }
1893 lua_pushnil(L);
1894 lua_pushstring(L, "connection closed.");
1895 return 2;
1896
1897connection_empty:
1898
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001899 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1900 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001901 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001902 }
1903 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02001904 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001905 return 0;
1906}
1907
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001908/* This Lua function gets two parameters. The first one can be string
1909 * or a number. If the string is "*l", the user requires one line. If
1910 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001911 * If the value is a number, the user require a number of bytes equal
1912 * to the value. The default value is "*l" (a line).
1913 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001914 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001915 * integer takes this values:
1916 * -1 : read a line
1917 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001918 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001919 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001920 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001921 * concatenated with the read data.
1922 */
1923__LJMP static int hlua_socket_receive(struct lua_State *L)
1924{
1925 int wanted = HLSR_READ_LINE;
1926 const char *pattern;
1927 int type;
1928 char *error;
1929 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001930 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001931
1932 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1933 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1934
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001935 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001936
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001937 /* Check if we run on the same thread than the xreator thread.
1938 * We cannot access to the socket if the thread is different.
1939 */
1940 if (socket->tid != tid)
1941 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1942
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001943 /* check for pattern. */
1944 if (lua_gettop(L) >= 2) {
1945 type = lua_type(L, 2);
1946 if (type == LUA_TSTRING) {
1947 pattern = lua_tostring(L, 2);
1948 if (strcmp(pattern, "*a") == 0)
1949 wanted = HLSR_READ_ALL;
1950 else if (strcmp(pattern, "*l") == 0)
1951 wanted = HLSR_READ_LINE;
1952 else {
1953 wanted = strtoll(pattern, &error, 10);
1954 if (*error != '\0')
1955 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1956 }
1957 }
1958 else if (type == LUA_TNUMBER) {
1959 wanted = lua_tointeger(L, 2);
1960 if (wanted < 0)
1961 WILL_LJMP(luaL_error(L, "Unsupported size."));
1962 }
1963 }
1964
1965 /* Set pattern. */
1966 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001967
1968 /* Check if we would replace the top by itself. */
1969 if (lua_gettop(L) != 2)
1970 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001971
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001972 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001973 luaL_buffinit(L, &socket->b);
1974
1975 /* Check prefix. */
1976 if (lua_gettop(L) >= 3) {
1977 if (lua_type(L, 3) != LUA_TSTRING)
1978 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1979 pattern = lua_tolstring(L, 3, &len);
1980 luaL_addlstring(&socket->b, pattern, len);
1981 }
1982
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001983 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001984}
1985
1986/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001987 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001988 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001989static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001990{
1991 struct hlua_socket *socket;
1992 struct hlua *hlua = hlua_gethlua(L);
1993 struct appctx *appctx;
1994 size_t buf_len;
1995 const char *buf;
1996 int len;
1997 int send_len;
1998 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001999 struct xref *peer;
2000 struct stream_interface *si;
2001 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002002
2003 /* Check if this lua stack is schedulable. */
2004 if (!hlua || !hlua->task)
2005 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2006 "'frontend', 'backend' or 'task'"));
2007
2008 /* Get object */
2009 socket = MAY_LJMP(hlua_checksocket(L, 1));
2010 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002011 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002012
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002013 /* Check if we run on the same thread than the xreator thread.
2014 * We cannot access to the socket if the thread is different.
2015 */
2016 if (socket->tid != tid)
2017 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2018
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002019 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002020 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002021 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002022 lua_pushinteger(L, -1);
2023 return 1;
2024 }
2025 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2026 si = appctx->owner;
2027 s = si_strm(si);
2028
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002029 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002030 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002031 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002032 lua_pushinteger(L, -1);
2033 return 1;
2034 }
2035
2036 /* Update the input buffer data. */
2037 buf += sent;
2038 send_len = buf_len - sent;
2039
2040 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002041 if (sent >= buf_len) {
2042 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002043 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002044 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002045
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002046 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002047 * the request buffer if its not required.
2048 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002049 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002050 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002051 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002052 }
2053
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002054 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002055 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002056 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002057 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002058 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002059
2060 /* send data */
2061 if (len < send_len)
2062 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002063 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002064
2065 /* "Not enough space" (-1), "Buffer too little to contain
2066 * the data" (-2) are not expected because the available length
2067 * is tested.
2068 * Other unknown error are also not expected.
2069 */
2070 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002071 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002072 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002073
sada05ed3302018-05-11 11:48:18 -07002074 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002075 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002076 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002077 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002078 return 1;
2079 }
2080
2081 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002082 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002083
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002084 s->req.rex = TICK_ETERNITY;
2085 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086
2087 /* Update length sent. */
2088 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002089 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002090
2091 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002092 if (sent + len >= buf_len) {
2093 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002094 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002095 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002096
2097hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002098 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2099 xref_unlock(&socket->xref, peer);
2100 WILL_LJMP(luaL_error(L, "out of memory"));
2101 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002102 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002103 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002104 return 0;
2105}
2106
2107/* This function initiate the send of data. It just check the input
2108 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002109 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002110 * "hlua_socket_write_yield" that can yield.
2111 *
2112 * The Lua function gets between 3 and 4 parameters. The first one is
2113 * the associated object. The second is a string buffer. The third is
2114 * a facultative integer that represents where is the buffer position
2115 * of the start of the data that can send. The first byte is the
2116 * position "1". The default value is "1". The fourth argument is a
2117 * facultative integer that represents where is the buffer position
2118 * of the end of the data that can send. The default is the last byte.
2119 */
2120static int hlua_socket_send(struct lua_State *L)
2121{
2122 int i;
2123 int j;
2124 const char *buf;
2125 size_t buf_len;
2126
2127 /* Check number of arguments. */
2128 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2129 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2130
2131 /* Get the string. */
2132 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2133
2134 /* Get and check j. */
2135 if (lua_gettop(L) == 4) {
2136 j = MAY_LJMP(luaL_checkinteger(L, 4));
2137 if (j < 0)
2138 j = buf_len + j + 1;
2139 if (j > buf_len)
2140 j = buf_len + 1;
2141 lua_pop(L, 1);
2142 }
2143 else
2144 j = buf_len;
2145
2146 /* Get and check i. */
2147 if (lua_gettop(L) == 3) {
2148 i = MAY_LJMP(luaL_checkinteger(L, 3));
2149 if (i < 0)
2150 i = buf_len + i + 1;
2151 if (i > buf_len)
2152 i = buf_len + 1;
2153 lua_pop(L, 1);
2154 } else
2155 i = 1;
2156
2157 /* Check bth i and j. */
2158 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002159 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002160 return 1;
2161 }
2162 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002163 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164 return 1;
2165 }
2166 if (i == 0)
2167 i = 1;
2168 if (j == 0)
2169 j = 1;
2170
2171 /* Pop the string. */
2172 lua_pop(L, 1);
2173
2174 /* Update the buffer length. */
2175 buf += i - 1;
2176 buf_len = j - i + 1;
2177 lua_pushlstring(L, buf, buf_len);
2178
2179 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002180 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002181
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002182 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002183}
2184
Willy Tarreau22b0a682015-06-17 19:43:49 +02002185#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2187{
2188 static char buffer[SOCKET_INFO_MAX_LEN];
2189 int ret;
2190 int len;
2191 char *p;
2192
2193 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2194 if (ret <= 0) {
2195 lua_pushnil(L);
2196 return 1;
2197 }
2198
2199 if (ret == AF_UNIX) {
2200 lua_pushstring(L, buffer+1);
2201 return 1;
2202 }
2203 else if (ret == AF_INET6) {
2204 buffer[0] = '[';
2205 len = strlen(buffer);
2206 buffer[len] = ']';
2207 len++;
2208 buffer[len] = ':';
2209 len++;
2210 p = buffer;
2211 }
2212 else if (ret == AF_INET) {
2213 p = buffer + 1;
2214 len = strlen(p);
2215 p[len] = ':';
2216 len++;
2217 }
2218 else {
2219 lua_pushnil(L);
2220 return 1;
2221 }
2222
2223 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2224 lua_pushnil(L);
2225 return 1;
2226 }
2227
2228 lua_pushstring(L, p);
2229 return 1;
2230}
2231
2232/* Returns information about the peer of the connection. */
2233__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2234{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002235 struct hlua_socket *socket;
2236 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002237 struct xref *peer;
2238 struct appctx *appctx;
2239 struct stream_interface *si;
2240 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002241 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002242
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002243 MAY_LJMP(check_args(L, 1, "getpeername"));
2244
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002245 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002246
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002247 /* Check if we run on the same thread than the xreator thread.
2248 * We cannot access to the socket if the thread is different.
2249 */
2250 if (socket->tid != tid)
2251 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2252
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002253 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002254 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002255 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002256 lua_pushnil(L);
2257 return 1;
2258 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002259 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2260 si = appctx->owner;
2261 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002262
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002263 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002264 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002265 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002266 lua_pushnil(L);
2267 return 1;
2268 }
2269
Willy Tarreaua71f6422016-11-16 17:00:14 +01002270 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002272 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002273 lua_pushnil(L);
2274 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002275 }
2276
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002277 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2278 xref_unlock(&socket->xref, peer);
2279 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002280}
2281
2282/* Returns information about my connection side. */
2283static int hlua_socket_getsockname(struct lua_State *L)
2284{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002285 struct hlua_socket *socket;
2286 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002287 struct appctx *appctx;
2288 struct xref *peer;
2289 struct stream_interface *si;
2290 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002291 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002292
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293 MAY_LJMP(check_args(L, 1, "getsockname"));
2294
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002295 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002296
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002297 /* Check if we run on the same thread than the xreator thread.
2298 * We cannot access to the socket if the thread is different.
2299 */
2300 if (socket->tid != tid)
2301 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2302
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002303 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002304 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002305 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 lua_pushnil(L);
2307 return 1;
2308 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002309 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2310 si = appctx->owner;
2311 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002312
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002313 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002314 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002315 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316 lua_pushnil(L);
2317 return 1;
2318 }
2319
Willy Tarreaua71f6422016-11-16 17:00:14 +01002320 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002321 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002322 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002323 lua_pushnil(L);
2324 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002325 }
2326
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002327 ret = hlua_socket_info(L, &conn->addr.from);
2328 xref_unlock(&socket->xref, peer);
2329 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002330}
2331
2332/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002333static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002334 .obj_type = OBJ_TYPE_APPLET,
2335 .name = "<LUA_TCP>",
2336 .fct = hlua_socket_handler,
2337 .release = hlua_socket_release,
2338};
2339
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002340__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002341{
2342 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2343 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002344 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002346 struct stream_interface *si;
2347 struct stream *s;
2348
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002349 /* Check if we run on the same thread than the xreator thread.
2350 * We cannot access to the socket if the thread is different.
2351 */
2352 if (socket->tid != tid)
2353 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2354
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002355 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002356 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002357 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002358 lua_pushnil(L);
2359 lua_pushstring(L, "Can't connect");
2360 return 2;
2361 }
2362 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2363 si = appctx->owner;
2364 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002366 /* Check if we run on the same thread than the xreator thread.
2367 * We cannot access to the socket if the thread is different.
2368 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002369 if (socket->tid != tid) {
2370 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002371 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002372 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002373
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002374 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002375 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002376 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002377 lua_pushnil(L);
2378 lua_pushstring(L, "Can't connect");
2379 return 2;
2380 }
2381
Willy Tarreaue09101e2018-10-16 17:37:12 +02002382 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002383
2384 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002385 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002386 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002387 lua_pushinteger(L, 1);
2388 return 1;
2389 }
2390
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002391 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2392 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002393 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002394 }
2395 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002396 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002397 return 0;
2398}
2399
2400/* This function fail or initite the connection. */
2401__LJMP static int hlua_socket_connect(struct lua_State *L)
2402{
2403 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002404 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002405 const char *ip;
2406 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002407 struct hlua *hlua;
2408 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002409 int low, high;
2410 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002411 struct xref *peer;
2412 struct stream_interface *si;
2413 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002414
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002415 if (lua_gettop(L) < 2)
2416 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002417
2418 /* Get args. */
2419 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002420
2421 /* Check if we run on the same thread than the xreator thread.
2422 * We cannot access to the socket if the thread is different.
2423 */
2424 if (socket->tid != tid)
2425 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2426
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002427 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002428 if (lua_gettop(L) >= 3) {
2429 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002430 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002431
Tim Duesterhus6edab862018-01-06 19:04:45 +01002432 /* Force the ip to end with a colon, to support IPv6 addresses
2433 * that are not enclosed within square brackets.
2434 */
2435 if (port > 0) {
2436 luaL_buffinit(L, &b);
2437 luaL_addstring(&b, ip);
2438 luaL_addchar(&b, ':');
2439 luaL_pushresult(&b);
2440 ip = lua_tolstring(L, lua_gettop(L), NULL);
2441 }
2442 }
2443
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002444 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002445 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002446 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002447 lua_pushnil(L);
2448 return 1;
2449 }
2450 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2451 si = appctx->owner;
2452 s = si_strm(si);
2453
2454 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002455 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002456 if (!conn) {
2457 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002458 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002459 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002460
Willy Tarreau3adac082015-09-26 17:51:09 +02002461 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002462 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002463
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002464 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002465 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002466 if (!addr) {
2467 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002468 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002469 }
2470 if (low != high) {
2471 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002472 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002473 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002474 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002475
2476 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002477 if (low == 0) {
2478 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002479 if (port == -1) {
2480 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002481 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002482 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002483 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2484 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002485 if (port == -1) {
2486 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002487 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002488 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002489 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2490 }
2491 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002492
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002493 hlua = hlua_gethlua(L);
Willy Tarreaue09101e2018-10-16 17:37:12 +02002494 appctx = __objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002495
2496 /* inform the stream that we want to be notified whenever the
2497 * connection completes.
2498 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002499 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002500 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002501 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002502
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002503 hlua->flags |= HLUA_MUST_GC;
2504
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002505 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2506 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002507 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002508 }
2509 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002510
2511 task_wakeup(s->task, TASK_WOKEN_INIT);
2512 /* Return yield waiting for connection. */
2513
Willy Tarreau9635e032018-10-16 17:52:55 +02002514 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002515
2516 return 0;
2517}
2518
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002519#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002520__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2521{
2522 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002523 struct xref *peer;
2524 struct appctx *appctx;
2525 struct stream_interface *si;
2526 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002527
2528 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2529 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002530
2531 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002532 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002533 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002534 lua_pushnil(L);
2535 return 1;
2536 }
2537 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2538 si = appctx->owner;
2539 s = si_strm(si);
2540
2541 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002542 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002543 return MAY_LJMP(hlua_socket_connect(L));
2544}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002545#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002546
2547__LJMP static int hlua_socket_setoption(struct lua_State *L)
2548{
2549 return 0;
2550}
2551
2552__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2553{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002554 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002555 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002556 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002557 struct xref *peer;
2558 struct appctx *appctx;
2559 struct stream_interface *si;
2560 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002561
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002562 MAY_LJMP(check_args(L, 2, "settimeout"));
2563
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002564 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002565
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002566 /* convert the timeout to millis */
2567 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002568
Thierry Fournier17a921b2018-03-08 09:59:02 +01002569 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002570 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002571 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2572
Mark Lakes56cc1252018-03-27 09:48:06 +02002573 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002574 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002575
2576 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002577 if (tmout == 0)
2578 tmout++; /* very small timeouts are adjusted to a minium of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002579
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002580 /* Check if we run on the same thread than the xreator thread.
2581 * We cannot access to the socket if the thread is different.
2582 */
2583 if (socket->tid != tid)
2584 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2585
Mark Lakes56cc1252018-03-27 09:48:06 +02002586 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002587 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002588 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002589 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2590 WILL_LJMP(lua_error(L));
2591 return 0;
2592 }
2593 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2594 si = appctx->owner;
2595 s = si_strm(si);
2596
Cyril Bonté7bb63452018-08-17 23:51:02 +02002597 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002598 s->req.rto = tmout;
2599 s->req.wto = tmout;
2600 s->res.rto = tmout;
2601 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002602 s->req.rex = tick_add_ifset(now_ms, tmout);
2603 s->req.wex = tick_add_ifset(now_ms, tmout);
2604 s->res.rex = tick_add_ifset(now_ms, tmout);
2605 s->res.wex = tick_add_ifset(now_ms, tmout);
2606
2607 s->task->expire = tick_add_ifset(now_ms, tmout);
2608 task_queue(s->task);
2609
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002610 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002611
Thierry Fourniere9636f12018-03-08 09:54:32 +01002612 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002613 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002614}
2615
2616__LJMP static int hlua_socket_new(lua_State *L)
2617{
2618 struct hlua_socket *socket;
2619 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002620 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002621 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002622
2623 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002624 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002625 hlua_pusherror(L, "socket: full stack");
2626 goto out_fail_conf;
2627 }
2628
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002629 /* Create the object: obj[0] = userdata. */
2630 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002631 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002632 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002633 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002634 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002635
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002636 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002637 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002638 hlua_pusherror(L, "socket: uninitialized pools.");
2639 goto out_fail_conf;
2640 }
2641
Willy Tarreau87b09662015-04-03 00:22:06 +02002642 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002643 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2644 lua_setmetatable(L, -2);
2645
Willy Tarreaud420a972015-04-06 00:39:18 +02002646 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002647 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002648 if (!appctx) {
2649 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002650 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002651 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002652
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002653 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002654 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002655 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2656 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002657
Willy Tarreaud420a972015-04-06 00:39:18 +02002658 /* Now create a session, task and stream for this applet */
2659 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2660 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002661 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002662 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002663 }
2664
Willy Tarreau87787ac2017-08-28 16:22:54 +02002665 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002666 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002667 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002668 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002669 }
2670
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002671 /* Initialise cross reference between stream and Lua socket object. */
2672 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002673
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002674 /* Configure "right" stream interface. this "si" is used to connect
2675 * and retrieve data from the server. The connection is initialized
2676 * with the "struct server".
2677 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002678 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002679
2680 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002681 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2682 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002683
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002684 return 1;
2685
Willy Tarreaud420a972015-04-06 00:39:18 +02002686 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002687 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002688 out_fail_sess:
2689 appctx_free(appctx);
2690 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002691 WILL_LJMP(lua_error(L));
2692 return 0;
2693}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002694
2695/*
2696 *
2697 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002698 * Class Channel
2699 *
2700 *
2701 */
2702
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002703/* This function is called before the Lua execution. It stores
2704 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002705 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002706static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002707{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002708 c->mode = stream->be->mode;
2709 switch (c->mode) {
2710 case PR_MODE_HTTP:
2711 c->data.http.dir = opt & SMP_OPT_DIR;
2712 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2713 c->data.http.state = stream->txn->req.msg_state;
2714 else
2715 c->data.http.state = stream->txn->rsp.msg_state;
2716 break;
2717 default:
2718 break;
2719 }
2720}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002721
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002722/* This function is called after the Lua execution. it
2723 * returns true if the parser state is consistent, otherwise,
2724 * it return false.
2725 *
2726 * In HTTP mode, the parser state must be in the same state
2727 * or greater when we exit the function. Even if we do a
2728 * control yield. This prevent to break the HTTP message
2729 * from the Lua code.
2730 */
2731static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2732{
2733 if (c->mode != stream->be->mode)
2734 return 0;
2735
2736 switch (c->mode) {
2737 case PR_MODE_HTTP:
2738 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002739 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002740 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2741 return stream->txn->req.msg_state >= c->data.http.state;
2742 else
2743 return stream->txn->rsp.msg_state >= c->data.http.state;
2744 default:
2745 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002746 }
2747 return 1;
2748}
2749
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002750/* Returns the struct hlua_channel join to the class channel in the
2751 * stack entry "ud" or throws an argument error.
2752 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002753__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002754{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002755 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002756}
2757
Willy Tarreau47860ed2015-03-10 14:07:50 +01002758/* Pushes the channel onto the top of the stack. If the stask does not have a
2759 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002760 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002761static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002762{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002763 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002764 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002765 return 0;
2766
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002767 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002768 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002769 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002770
2771 /* Pop a class sesison metatable and affect it to the userdata. */
2772 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2773 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002774 return 1;
2775}
2776
2777/* Duplicate all the data present in the input channel and put it
2778 * in a string LUA variables. Returns -1 and push a nil value in
2779 * the stack if the channel is closed and all the data are consumed,
2780 * returns 0 if no data are available, otherwise it returns the length
2781 * of the builded string.
2782 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002783static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002784{
2785 char *blk1;
2786 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002787 size_t len1;
2788 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002789 int ret;
2790 luaL_Buffer b;
2791
Willy Tarreau06d80a92017-10-19 14:32:15 +02002792 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002793 if (unlikely(ret == 0))
2794 return 0;
2795
2796 if (unlikely(ret < 0)) {
2797 lua_pushnil(L);
2798 return -1;
2799 }
2800
2801 luaL_buffinit(L, &b);
2802 luaL_addlstring(&b, blk1, len1);
2803 if (unlikely(ret == 2))
2804 luaL_addlstring(&b, blk2, len2);
2805 luaL_pushresult(&b);
2806
2807 if (unlikely(ret == 2))
2808 return len1 + len2;
2809 return len1;
2810}
2811
2812/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2813 * a yield. This function keep the data in the buffer.
2814 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002815__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002816{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002817 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002818
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002819 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2820
Christopher Faulet3f829a42018-12-13 21:56:45 +01002821 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2822 WILL_LJMP(lua_error(L));
2823
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002824 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002825 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002826 return 1;
2827}
2828
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002829/* Check arguments for the function "hlua_channel_dup_yield". */
2830__LJMP static int hlua_channel_dup(lua_State *L)
2831{
2832 MAY_LJMP(check_args(L, 1, "dup"));
2833 MAY_LJMP(hlua_checkchannel(L, 1));
2834 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2835}
2836
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002837/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2838 * a yield. This function consumes the data in the buffer. It returns
2839 * a string containing the data or a nil pointer if no data are available
2840 * and the channel is closed.
2841 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002842__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002843{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002844 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002845 int ret;
2846
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002847 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002848
Christopher Faulet3f829a42018-12-13 21:56:45 +01002849 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2850 WILL_LJMP(lua_error(L));
2851
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002852 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002853 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02002854 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002855
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002856 if (unlikely(ret == -1))
2857 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002858
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002859 b_sub(&chn->buf, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002860 return 1;
2861}
2862
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002863/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002864__LJMP static int hlua_channel_get(lua_State *L)
2865{
2866 MAY_LJMP(check_args(L, 1, "get"));
2867 MAY_LJMP(hlua_checkchannel(L, 1));
2868 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2869}
2870
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002871/* This functions consumes and returns one line. If the channel is closed,
2872 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002873 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002874 * value.
2875 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002876__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002877{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002878 char *blk1;
2879 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002880 size_t len1;
2881 size_t len2;
2882 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002883 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002884 int ret;
2885 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002886
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002887 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2888
Christopher Faulet3f829a42018-12-13 21:56:45 +01002889 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2890 WILL_LJMP(lua_error(L));
2891
Willy Tarreau06d80a92017-10-19 14:32:15 +02002892 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002893 if (ret == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002894 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002895
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002896 if (ret == -1) {
2897 lua_pushnil(L);
2898 return 1;
2899 }
2900
2901 luaL_buffinit(L, &b);
2902 luaL_addlstring(&b, blk1, len1);
2903 len = len1;
2904 if (unlikely(ret == 2)) {
2905 luaL_addlstring(&b, blk2, len2);
2906 len += len2;
2907 }
2908 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002909 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002910 return 1;
2911}
2912
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002913/* Check arguments for the function "hlua_channel_getline_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002914__LJMP static int hlua_channel_getline(lua_State *L)
2915{
2916 MAY_LJMP(check_args(L, 1, "getline"));
2917 MAY_LJMP(hlua_checkchannel(L, 1));
2918 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2919}
2920
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002921/* This function takes a string as input, and append it at the
2922 * input side of channel. If the data is too big, but a space
2923 * is probably available after sending some data, the function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002924 * yields. If the data is bigger than the buffer, or if the
2925 * channel is closed, it returns -1. Otherwise, it returns the
2926 * amount of data written.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002927 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002928__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002929{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002930 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002931 size_t len;
2932 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2933 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2934 int ret;
2935 int max;
2936
Christopher Faulet3f829a42018-12-13 21:56:45 +01002937 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2938 WILL_LJMP(lua_error(L));
2939
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002940 /* Check if the buffer is available because HAProxy doesn't allocate
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002941 * the request buffer if its not required.
2942 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002943 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002944 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002945 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002946 }
2947
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002948 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002949 if (max > len - l)
2950 max = len - l;
2951
Willy Tarreau06d80a92017-10-19 14:32:15 +02002952 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002953 if (ret == -2 || ret == -3) {
2954 lua_pushinteger(L, -1);
2955 return 1;
2956 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002957 if (ret == -1) {
2958 chn->flags |= CF_WAKE_WRITE;
Willy Tarreau9635e032018-10-16 17:52:55 +02002959 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002960 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002961 l += ret;
2962 lua_pop(L, 1);
2963 lua_pushinteger(L, l);
2964
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002965 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02002966 if (max == 0 && co_data(chn) == 0) {
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002967 /* There are no space available, and the output buffer is empty.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002968 * in this case, we cannot add more data, so we cannot yield,
2969 * we return the amount of copyied data.
2970 */
2971 return 1;
2972 }
2973 if (l < len)
Willy Tarreau9635e032018-10-16 17:52:55 +02002974 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002975 return 1;
2976}
2977
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002978/* Just a wrapper of "hlua_channel_append_yield". It returns the length
2979 * of the written string, or -1 if the channel is closed or if the
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002980 * buffer size is too little for the data.
2981 */
2982__LJMP static int hlua_channel_append(lua_State *L)
2983{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002984 size_t len;
2985
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002986 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002987 MAY_LJMP(hlua_checkchannel(L, 1));
2988 MAY_LJMP(luaL_checklstring(L, 2, &len));
2989 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002990 lua_pushinteger(L, 0);
2991
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002992 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002993}
2994
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002995/* Just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002996 * his process by cleaning the buffer. The result is a replacement
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002997 * of the current data. It returns the length of the written string,
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002998 * or -1 if the channel is closed or if the buffer size is too
2999 * little for the data.
3000 */
3001__LJMP static int hlua_channel_set(lua_State *L)
3002{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003003 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003004
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003005 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003006 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003007 lua_pushinteger(L, 0);
3008
Christopher Faulet3f829a42018-12-13 21:56:45 +01003009 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3010 WILL_LJMP(lua_error(L));
3011
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003012 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003013
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003014 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003015}
3016
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003017/* Append data in the output side of the buffer. This data is immediately
3018 * sent. The function returns the amount of data written. If the buffer
3019 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003020 * if the channel is closed.
3021 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003022__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003023{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003024 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003025 size_t len;
3026 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3027 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3028 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003029 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003030
Christopher Faulet3f829a42018-12-13 21:56:45 +01003031 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3032 WILL_LJMP(lua_error(L));
3033
Willy Tarreau47860ed2015-03-10 14:07:50 +01003034 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003035 lua_pushinteger(L, -1);
3036 return 1;
3037 }
3038
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003039 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003040 * the request buffer if its not required.
3041 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003042 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01003043 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02003044 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003045 }
3046
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003047 /* The written data will be immediately sent, so we can check
3048 * the available space without taking in account the reserve.
3049 * The reserve is guaranteed for the processing of incoming
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003050 * data, because the buffer will be flushed.
3051 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003052 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003053
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003054 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003055 * in this case, we cannot add more data, so we cannot yield,
3056 * we return the amount of copyied data.
3057 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003058 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003059 return 1;
3060
3061 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003062 if (max > len - l)
3063 max = len - l;
3064
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003065 /* The buffer available size may be not contiguous. This test
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003066 * detects a non contiguous buffer and realign it.
3067 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003068 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003069 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003070
3071 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003072 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003073
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003074 /* buffer replace considers that the input part is filled.
3075 * so, I must forward these new data in the output part.
3076 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003077 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003078
3079 l += max;
3080 lua_pop(L, 1);
3081 lua_pushinteger(L, l);
3082
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003083 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003084 * in this case, we cannot add more data, so we cannot yield,
3085 * we return the amount of copyied data.
3086 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003087 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003088 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003089 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003090
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003091 if (l < len) {
3092 /* If we are waiting for space in the response buffer, we
3093 * must set the flag WAKERESWR. This flag required the task
3094 * wake up if any activity is detected on the response buffer.
3095 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003096 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003097 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003098 else
3099 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003100 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003101 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003102
3103 return 1;
3104}
3105
3106/* Just a wraper of "_hlua_channel_send". This wrapper permits
3107 * yield the LUA process, and resume it without checking the
3108 * input arguments.
3109 */
3110__LJMP static int hlua_channel_send(lua_State *L)
3111{
3112 MAY_LJMP(check_args(L, 2, "send"));
3113 lua_pushinteger(L, 0);
3114
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003115 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003116}
3117
3118/* This function forward and amount of butes. The data pass from
3119 * the input side of the buffer to the output side, and can be
3120 * forwarded. This function never fails.
3121 *
3122 * The Lua function takes an amount of bytes to be forwarded in
3123 * imput. It returns the number of bytes forwarded.
3124 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003125__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003126{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003127 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003128 int len;
3129 int l;
3130 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003131 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003132
3133 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003134
3135 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3136 WILL_LJMP(lua_error(L));
3137
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003138 len = MAY_LJMP(luaL_checkinteger(L, 2));
3139 l = MAY_LJMP(luaL_checkinteger(L, -1));
3140
3141 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003142 if (max > ci_data(chn))
3143 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003144 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003145 l += max;
3146
3147 lua_pop(L, 1);
3148 lua_pushinteger(L, l);
3149
3150 /* Check if it miss bytes to forward. */
3151 if (l < len) {
3152 /* The the input channel or the output channel are closed, we
3153 * must return the amount of data forwarded.
3154 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003155 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003156 return 1;
3157
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003158 /* If we are waiting for space data in the response buffer, we
3159 * must set the flag WAKERESWR. This flag required the task
3160 * wake up if any activity is detected on the response buffer.
3161 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003162 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003163 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003164 else
3165 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003166
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003167 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003168 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003169 }
3170
3171 return 1;
3172}
3173
3174/* Just check the input and prepare the stack for the previous
3175 * function "hlua_channel_forward_yield"
3176 */
3177__LJMP static int hlua_channel_forward(lua_State *L)
3178{
3179 MAY_LJMP(check_args(L, 2, "forward"));
3180 MAY_LJMP(hlua_checkchannel(L, 1));
3181 MAY_LJMP(luaL_checkinteger(L, 2));
3182
3183 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003184 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003185}
3186
3187/* Just returns the number of bytes available in the input
3188 * side of the buffer. This function never fails.
3189 */
3190__LJMP static int hlua_channel_get_in_len(lua_State *L)
3191{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003192 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003193
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003194 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003195 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003196 if (IS_HTX_STRM(chn_strm(chn))) {
3197 struct htx *htx = htxbuf(&chn->buf);
3198 lua_pushinteger(L, htx->data - co_data(chn));
3199 }
3200 else
3201 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003202 return 1;
3203}
3204
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003205/* Returns true if the channel is full. */
3206__LJMP static int hlua_channel_is_full(lua_State *L)
3207{
3208 struct channel *chn;
3209 int rem;
3210
3211 MAY_LJMP(check_args(L, 1, "is_full"));
3212 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3213
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003214 if (IS_HTX_STRM(chn_strm(chn))) {
3215 struct htx *htx = htxbuf(&chn->buf);
3216
3217 rem = htx_free_data_space(htx);
3218 }
3219 else
3220 rem = b_room(&chn->buf);
3221
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003222 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3223
3224 lua_pushboolean(L, rem <= 0);
3225 return 1;
3226}
3227
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003228/* Just returns the number of bytes available in the output
3229 * side of the buffer. This function never fails.
3230 */
3231__LJMP static int hlua_channel_get_out_len(lua_State *L)
3232{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003233 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003234
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003235 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003236 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003237 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003238 return 1;
3239}
3240
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003241/*
3242 *
3243 *
3244 * Class Fetches
3245 *
3246 *
3247 */
3248
3249/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003250 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003251 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003252__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003253{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003254 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003255}
3256
3257/* This function creates and push in the stack a fetch object according
3258 * with a current TXN.
3259 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003260static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003261{
Willy Tarreau7073c472015-04-06 11:15:40 +02003262 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003263
3264 /* Check stack size. */
3265 if (!lua_checkstack(L, 3))
3266 return 0;
3267
3268 /* Create the object: obj[0] = userdata.
3269 * Note that the base of the Fetches object is the
3270 * transaction object.
3271 */
3272 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003273 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003274 lua_rawseti(L, -2, 0);
3275
Willy Tarreau7073c472015-04-06 11:15:40 +02003276 hsmp->s = txn->s;
3277 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003278 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003279 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003280
3281 /* Pop a class sesison metatable and affect it to the userdata. */
3282 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3283 lua_setmetatable(L, -2);
3284
3285 return 1;
3286}
3287
3288/* This function is an LUA binding. It is called with each sample-fetch.
3289 * It uses closure argument to store the associated sample-fetch. It
3290 * returns only one argument or throws an error. An error is thrown
3291 * only if an error is encountered during the argument parsing. If
3292 * the "sample-fetch" function fails, nil is returned.
3293 */
3294__LJMP static int hlua_run_sample_fetch(lua_State *L)
3295{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003296 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003297 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003298 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003299 int i;
3300 struct sample smp;
3301
3302 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003303 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003304
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003305 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003306 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003307
Thierry FOURNIERca988662015-12-20 18:43:03 +01003308 /* Check execution authorization. */
3309 if (f->use & SMP_USE_HTTP_ANY &&
3310 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3311 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3312 "is not available in Lua services", f->kw);
3313 WILL_LJMP(lua_error(L));
3314 }
3315
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003316 /* Get extra arguments. */
3317 for (i = 0; i < lua_gettop(L) - 1; i++) {
3318 if (i >= ARGM_NBARGS)
3319 break;
3320 hlua_lua2arg(L, i + 2, &args[i]);
3321 }
3322 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003323 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003324
3325 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003326 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003327
3328 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003329 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003330 lua_pushfstring(L, "error in arguments");
3331 WILL_LJMP(lua_error(L));
3332 }
3333
3334 /* Initialise the sample. */
3335 memset(&smp, 0, sizeof(smp));
3336
3337 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003338 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003339 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003340 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003341 lua_pushstring(L, "");
3342 else
3343 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003344 return 1;
3345 }
3346
3347 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003348 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003349 hlua_smp2lua_str(L, &smp);
3350 else
3351 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003352 return 1;
3353}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003354
3355/*
3356 *
3357 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003358 * Class Converters
3359 *
3360 *
3361 */
3362
3363/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003364 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003365 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003366__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003367{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003368 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003369}
3370
3371/* This function creates and push in the stack a Converters object
3372 * according with a current TXN.
3373 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003374static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003375{
Willy Tarreau7073c472015-04-06 11:15:40 +02003376 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003377
3378 /* Check stack size. */
3379 if (!lua_checkstack(L, 3))
3380 return 0;
3381
3382 /* Create the object: obj[0] = userdata.
3383 * Note that the base of the Converters object is the
3384 * same than the TXN object.
3385 */
3386 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003387 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003388 lua_rawseti(L, -2, 0);
3389
Willy Tarreau7073c472015-04-06 11:15:40 +02003390 hsmp->s = txn->s;
3391 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003392 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003393 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003394
Willy Tarreau87b09662015-04-03 00:22:06 +02003395 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003396 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3397 lua_setmetatable(L, -2);
3398
3399 return 1;
3400}
3401
3402/* This function is an LUA binding. It is called with each converter.
3403 * It uses closure argument to store the associated converter. It
3404 * returns only one argument or throws an error. An error is thrown
3405 * only if an error is encountered during the argument parsing. If
3406 * the converter function function fails, nil is returned.
3407 */
3408__LJMP static int hlua_run_sample_conv(lua_State *L)
3409{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003410 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003411 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003412 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003413 int i;
3414 struct sample smp;
3415
3416 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003417 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003418
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003419 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003420 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003421
3422 /* Get extra arguments. */
3423 for (i = 0; i < lua_gettop(L) - 2; i++) {
3424 if (i >= ARGM_NBARGS)
3425 break;
3426 hlua_lua2arg(L, i + 3, &args[i]);
3427 }
3428 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003429 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003430
3431 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003432 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003433
3434 /* Run the special args checker. */
3435 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3436 hlua_pusherror(L, "error in arguments");
3437 WILL_LJMP(lua_error(L));
3438 }
3439
3440 /* Initialise the sample. */
3441 if (!hlua_lua2smp(L, 2, &smp)) {
3442 hlua_pusherror(L, "error in the input argument");
3443 WILL_LJMP(lua_error(L));
3444 }
3445
Willy Tarreau1777ea62016-03-10 16:15:46 +01003446 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3447
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003448 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003449 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003450 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003451 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003452 WILL_LJMP(lua_error(L));
3453 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003454 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3455 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003456 hlua_pusherror(L, "error during the input argument casting");
3457 WILL_LJMP(lua_error(L));
3458 }
3459
3460 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003461 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003462 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003463 lua_pushstring(L, "");
3464 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003465 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003466 return 1;
3467 }
3468
3469 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003470 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003471 hlua_smp2lua_str(L, &smp);
3472 else
3473 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003474 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003475}
3476
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003477/*
3478 *
3479 *
3480 * Class AppletTCP
3481 *
3482 *
3483 */
3484
3485/* Returns a struct hlua_txn if the stack entry "ud" is
3486 * a class stream, otherwise it throws an error.
3487 */
3488__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3489{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003490 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003491}
3492
3493/* This function creates and push in the stack an Applet object
3494 * according with a current TXN.
3495 */
3496static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3497{
3498 struct hlua_appctx *appctx;
3499 struct stream_interface *si = ctx->owner;
3500 struct stream *s = si_strm(si);
3501 struct proxy *p = s->be;
3502
3503 /* Check stack size. */
3504 if (!lua_checkstack(L, 3))
3505 return 0;
3506
3507 /* Create the object: obj[0] = userdata.
3508 * Note that the base of the Converters object is the
3509 * same than the TXN object.
3510 */
3511 lua_newtable(L);
3512 appctx = lua_newuserdata(L, sizeof(*appctx));
3513 lua_rawseti(L, -2, 0);
3514 appctx->appctx = ctx;
3515 appctx->htxn.s = s;
3516 appctx->htxn.p = p;
3517
3518 /* Create the "f" field that contains a list of fetches. */
3519 lua_pushstring(L, "f");
3520 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3521 return 0;
3522 lua_settable(L, -3);
3523
3524 /* Create the "sf" field that contains a list of stringsafe fetches. */
3525 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003526 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003527 return 0;
3528 lua_settable(L, -3);
3529
3530 /* Create the "c" field that contains a list of converters. */
3531 lua_pushstring(L, "c");
3532 if (!hlua_converters_new(L, &appctx->htxn, 0))
3533 return 0;
3534 lua_settable(L, -3);
3535
3536 /* Create the "sc" field that contains a list of stringsafe converters. */
3537 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003538 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003539 return 0;
3540 lua_settable(L, -3);
3541
3542 /* Pop a class stream metatable and affect it to the table. */
3543 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3544 lua_setmetatable(L, -2);
3545
3546 return 1;
3547}
3548
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003549__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3550{
3551 struct hlua_appctx *appctx;
3552 struct stream *s;
3553 const char *name;
3554 size_t len;
3555 struct sample smp;
3556
3557 MAY_LJMP(check_args(L, 3, "set_var"));
3558
3559 /* It is useles to retrieve the stream, but this function
3560 * runs only in a stream context.
3561 */
3562 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3563 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3564 s = appctx->htxn.s;
3565
3566 /* Converts the third argument in a sample. */
3567 hlua_lua2smp(L, 3, &smp);
3568
3569 /* Store the sample in a variable. */
3570 smp_set_owner(&smp, s->be, s->sess, s, 0);
3571 vars_set_by_name(name, len, &smp);
3572 return 0;
3573}
3574
3575__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3576{
3577 struct hlua_appctx *appctx;
3578 struct stream *s;
3579 const char *name;
3580 size_t len;
3581 struct sample smp;
3582
3583 MAY_LJMP(check_args(L, 2, "unset_var"));
3584
3585 /* It is useles to retrieve the stream, but this function
3586 * runs only in a stream context.
3587 */
3588 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3589 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3590 s = appctx->htxn.s;
3591
3592 /* Unset the variable. */
3593 smp_set_owner(&smp, s->be, s->sess, s, 0);
3594 vars_unset_by_name(name, len, &smp);
3595 return 0;
3596}
3597
3598__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3599{
3600 struct hlua_appctx *appctx;
3601 struct stream *s;
3602 const char *name;
3603 size_t len;
3604 struct sample smp;
3605
3606 MAY_LJMP(check_args(L, 2, "get_var"));
3607
3608 /* It is useles to retrieve the stream, but this function
3609 * runs only in a stream context.
3610 */
3611 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3612 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3613 s = appctx->htxn.s;
3614
3615 smp_set_owner(&smp, s->be, s->sess, s, 0);
3616 if (!vars_get_by_name(name, len, &smp)) {
3617 lua_pushnil(L);
3618 return 1;
3619 }
3620
3621 return hlua_smp2lua(L, &smp);
3622}
3623
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003624__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3625{
3626 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3627 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003628 struct hlua *hlua;
3629
3630 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003631 if (!s->hlua)
3632 return 0;
3633 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003634
3635 MAY_LJMP(check_args(L, 2, "set_priv"));
3636
3637 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003638 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003639
3640 /* Get and store new value. */
3641 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3642 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3643
3644 return 0;
3645}
3646
3647__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3648{
3649 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3650 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003651 struct hlua *hlua;
3652
3653 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003654 if (!s->hlua) {
3655 lua_pushnil(L);
3656 return 1;
3657 }
3658 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003659
3660 /* Push configuration index in the stack. */
3661 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3662
3663 return 1;
3664}
3665
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003666/* If expected data not yet available, it returns a yield. This function
3667 * consumes the data in the buffer. It returns a string containing the
3668 * data. This string can be empty.
3669 */
3670__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3671{
3672 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3673 struct stream_interface *si = appctx->appctx->owner;
3674 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003675 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003676 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003677 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003678 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003679
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003680 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003681 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003682
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003683 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003684 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003685 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003686 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003687 }
3688
3689 /* End of data: commit the total strings and return. */
3690 if (ret < 0) {
3691 luaL_pushresult(&appctx->b);
3692 return 1;
3693 }
3694
3695 /* Ensure that the block 2 length is usable. */
3696 if (ret == 1)
3697 len2 = 0;
3698
3699 /* dont check the max length read and dont check. */
3700 luaL_addlstring(&appctx->b, blk1, len1);
3701 luaL_addlstring(&appctx->b, blk2, len2);
3702
3703 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003704 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003705 luaL_pushresult(&appctx->b);
3706 return 1;
3707}
3708
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003709/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003710__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3711{
3712 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3713
3714 /* Initialise the string catenation. */
3715 luaL_buffinit(L, &appctx->b);
3716
3717 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3718}
3719
3720/* If expected data not yet available, it returns a yield. This function
3721 * consumes the data in the buffer. It returns a string containing the
3722 * data. This string can be empty.
3723 */
3724__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3725{
3726 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3727 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003728 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003729 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003730 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003731 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003732 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003733 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003734
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003735 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003736 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003737
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003738 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003739 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003740 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003741 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003742 }
3743
3744 /* End of data: commit the total strings and return. */
3745 if (ret < 0) {
3746 luaL_pushresult(&appctx->b);
3747 return 1;
3748 }
3749
3750 /* Ensure that the block 2 length is usable. */
3751 if (ret == 1)
3752 len2 = 0;
3753
3754 if (len == -1) {
3755
3756 /* If len == -1, catenate all the data avalaile and
3757 * yield because we want to get all the data until
3758 * the end of data stream.
3759 */
3760 luaL_addlstring(&appctx->b, blk1, len1);
3761 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003762 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003763 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003764 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003765
3766 } else {
3767
3768 /* Copy the fisrt block caping to the length required. */
3769 if (len1 > len)
3770 len1 = len;
3771 luaL_addlstring(&appctx->b, blk1, len1);
3772 len -= len1;
3773
3774 /* Copy the second block. */
3775 if (len2 > len)
3776 len2 = len;
3777 luaL_addlstring(&appctx->b, blk2, len2);
3778 len -= len2;
3779
3780 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003781 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003782
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003783 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003784 if (len > 0) {
3785 lua_pushinteger(L, len);
3786 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003787 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003788 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003789 }
3790
3791 /* return the result. */
3792 luaL_pushresult(&appctx->b);
3793 return 1;
3794 }
3795
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003796 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003797 hlua_pusherror(L, "Lua: internal error");
3798 WILL_LJMP(lua_error(L));
3799 return 0;
3800}
3801
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003802/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003803__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3804{
3805 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3806 int len = -1;
3807
3808 if (lua_gettop(L) > 2)
3809 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3810 if (lua_gettop(L) >= 2) {
3811 len = MAY_LJMP(luaL_checkinteger(L, 2));
3812 lua_pop(L, 1);
3813 }
3814
3815 /* Confirm or set the required length */
3816 lua_pushinteger(L, len);
3817
3818 /* Initialise the string catenation. */
3819 luaL_buffinit(L, &appctx->b);
3820
3821 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3822}
3823
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003824/* Append data in the output side of the buffer. This data is immediately
3825 * sent. The function returns the amount of data written. If the buffer
3826 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003827 * if the channel is closed.
3828 */
3829__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3830{
3831 size_t len;
3832 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3833 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3834 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3835 struct stream_interface *si = appctx->appctx->owner;
3836 struct channel *chn = si_ic(si);
3837 int max;
3838
3839 /* Get the max amount of data which can write as input in the channel. */
3840 max = channel_recv_max(chn);
3841 if (max > (len - l))
3842 max = len - l;
3843
3844 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003845 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003846
3847 /* update counters. */
3848 l += max;
3849 lua_pop(L, 1);
3850 lua_pushinteger(L, l);
3851
3852 /* If some data is not send, declares the situation to the
3853 * applet, and returns a yield.
3854 */
3855 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01003856 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003857 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003858 }
3859
3860 return 1;
3861}
3862
3863/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3864 * yield the LUA process, and resume it without checking the
3865 * input arguments.
3866 */
3867__LJMP static int hlua_applet_tcp_send(lua_State *L)
3868{
3869 MAY_LJMP(check_args(L, 2, "send"));
3870 lua_pushinteger(L, 0);
3871
3872 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3873}
3874
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003875/*
3876 *
3877 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003878 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003879 *
3880 *
3881 */
3882
3883/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003884 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003885 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003886__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003887{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003888 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003889}
3890
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003891/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003892 * according with a current TXN.
3893 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003894static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003895{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003896 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003897 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003898 struct stream_interface *si = ctx->owner;
3899 struct stream *s = si_strm(si);
3900 struct proxy *px = s->be;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003901
3902 /* Check stack size. */
3903 if (!lua_checkstack(L, 3))
3904 return 0;
3905
3906 /* Create the object: obj[0] = userdata.
3907 * Note that the base of the Converters object is the
3908 * same than the TXN object.
3909 */
3910 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003911 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003912 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003913 appctx->appctx = ctx;
3914 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003915 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003916 appctx->htxn.s = s;
3917 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003918
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003919 /* Create the "f" field that contains a list of fetches. */
3920 lua_pushstring(L, "f");
3921 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3922 return 0;
3923 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003924
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003925 /* Create the "sf" field that contains a list of stringsafe fetches. */
3926 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003927 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003928 return 0;
3929 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003930
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003931 /* Create the "c" field that contains a list of converters. */
3932 lua_pushstring(L, "c");
3933 if (!hlua_converters_new(L, &appctx->htxn, 0))
3934 return 0;
3935 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003936
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003937 /* Create the "sc" field that contains a list of stringsafe converters. */
3938 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003939 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003940 return 0;
3941 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003942
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003943 if (IS_HTX_STRM(s)) {
3944 /* HTX version */
3945 struct htx *htx = htxbuf(&s->req.buf);
3946 struct htx_sl *sl = http_find_stline(htx);
3947 struct ist path;
3948 unsigned long long len = 0;
3949 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003950
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003951 /* Stores the request method. */
3952 lua_pushstring(L, "method");
3953 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
3954 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003955
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003956 /* Stores the http version. */
3957 lua_pushstring(L, "version");
3958 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
3959 lua_settable(L, -3);
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003960
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003961 /* creates an array of headers. hlua_http_get_headers() crates and push
3962 * the array on the top of the stack.
3963 */
3964 lua_pushstring(L, "headers");
3965 htxn.s = s;
3966 htxn.p = px;
3967 htxn.dir = SMP_OPT_DIR_REQ;
3968 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3969 return 0;
3970 lua_settable(L, -3);
3971
3972 path = http_get_path(htx_sl_req_uri(sl));
3973 if (path.ptr) {
3974 char *p, *q, *end;
3975
3976 p = path.ptr;
3977 end = path.ptr + path.len;
3978 q = p;
3979 while (q < end && *q != '?')
3980 q++;
3981
3982 /* Stores the request path. */
3983 lua_pushstring(L, "path");
3984 lua_pushlstring(L, p, q - p);
3985 lua_settable(L, -3);
3986
3987 /* Stores the query string. */
3988 lua_pushstring(L, "qs");
3989 if (*q == '?')
3990 q++;
3991 lua_pushlstring(L, q, end - q);
3992 lua_settable(L, -3);
3993 }
3994
3995 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3996 struct htx_blk *blk = htx_get_blk(htx, pos);
3997 enum htx_blk_type type = htx_get_blk_type(blk);
3998
3999 if (type == HTX_BLK_EOM || type == HTX_BLK_EOD)
4000 break;
4001 if (type == HTX_BLK_DATA)
4002 len += htx_get_blksz(blk);
4003 }
4004 if (htx->extra != ULLONG_MAX)
4005 len += htx->extra;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004006
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004007 /* Stores the request path. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004008 lua_pushstring(L, "length");
4009 lua_pushinteger(L, len);
4010 lua_settable(L, -3);
4011 }
4012 else {
4013 /* Legacy HTTP version */
4014 struct http_txn *txn = s->txn;
4015 const char *path;
4016 const char *end;
4017 const char *p;
4018
4019 /* Stores the request method. */
4020 lua_pushstring(L, "method");
4021 lua_pushlstring(L, ci_head(txn->req.chn), txn->req.sl.rq.m_l);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004022 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004023
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004024 /* Stores the http version. */
4025 lua_pushstring(L, "version");
4026 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 +01004027 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004028
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004029 /* creates an array of headers. hlua_http_get_headers() crates and push
4030 * the array on the top of the stack.
4031 */
4032 lua_pushstring(L, "headers");
4033 htxn.s = s;
4034 htxn.p = px;
4035 htxn.dir = SMP_OPT_DIR_REQ;
4036 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
4037 return 0;
4038 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004039
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004040 /* Get path and qs */
4041 path = http_txn_get_path(txn);
4042 if (path) {
4043 end = ci_head(txn->req.chn) + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
4044 p = path;
4045 while (p < end && *p != '?')
4046 p++;
4047
4048 /* Stores the request path. */
4049 lua_pushstring(L, "path");
4050 lua_pushlstring(L, path, p - path);
4051 lua_settable(L, -3);
4052
4053 /* Stores the query string. */
4054 lua_pushstring(L, "qs");
4055 if (*p == '?')
4056 p++;
4057 lua_pushlstring(L, p, end - p);
4058 lua_settable(L, -3);
4059 }
4060
4061 /* Stores the request path. */
4062 lua_pushstring(L, "length");
4063 lua_pushinteger(L, txn->req.body_len);
4064 lua_settable(L, -3);
4065 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004066
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004067 /* Create an empty array of HTTP request headers. */
4068 lua_pushstring(L, "response");
4069 lua_newtable(L);
4070 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004071
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004072 /* Pop a class stream metatable and affect it to the table. */
4073 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4074 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004075
4076 return 1;
4077}
4078
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004079__LJMP static int hlua_applet_http_set_var(lua_State *L)
4080{
4081 struct hlua_appctx *appctx;
4082 struct stream *s;
4083 const char *name;
4084 size_t len;
4085 struct sample smp;
4086
4087 MAY_LJMP(check_args(L, 3, "set_var"));
4088
4089 /* It is useles to retrieve the stream, but this function
4090 * runs only in a stream context.
4091 */
4092 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4093 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4094 s = appctx->htxn.s;
4095
4096 /* Converts the third argument in a sample. */
4097 hlua_lua2smp(L, 3, &smp);
4098
4099 /* Store the sample in a variable. */
4100 smp_set_owner(&smp, s->be, s->sess, s, 0);
4101 vars_set_by_name(name, len, &smp);
4102 return 0;
4103}
4104
4105__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4106{
4107 struct hlua_appctx *appctx;
4108 struct stream *s;
4109 const char *name;
4110 size_t len;
4111 struct sample smp;
4112
4113 MAY_LJMP(check_args(L, 2, "unset_var"));
4114
4115 /* It is useles to retrieve the stream, but this function
4116 * runs only in a stream context.
4117 */
4118 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4119 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4120 s = appctx->htxn.s;
4121
4122 /* Unset the variable. */
4123 smp_set_owner(&smp, s->be, s->sess, s, 0);
4124 vars_unset_by_name(name, len, &smp);
4125 return 0;
4126}
4127
4128__LJMP static int hlua_applet_http_get_var(lua_State *L)
4129{
4130 struct hlua_appctx *appctx;
4131 struct stream *s;
4132 const char *name;
4133 size_t len;
4134 struct sample smp;
4135
4136 MAY_LJMP(check_args(L, 2, "get_var"));
4137
4138 /* It is useles to retrieve the stream, but this function
4139 * runs only in a stream context.
4140 */
4141 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4142 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4143 s = appctx->htxn.s;
4144
4145 smp_set_owner(&smp, s->be, s->sess, s, 0);
4146 if (!vars_get_by_name(name, len, &smp)) {
4147 lua_pushnil(L);
4148 return 1;
4149 }
4150
4151 return hlua_smp2lua(L, &smp);
4152}
4153
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004154__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4155{
4156 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4157 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004158 struct hlua *hlua;
4159
4160 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004161 if (!s->hlua)
4162 return 0;
4163 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004164
4165 MAY_LJMP(check_args(L, 2, "set_priv"));
4166
4167 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004168 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004169
4170 /* Get and store new value. */
4171 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4172 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4173
4174 return 0;
4175}
4176
4177__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4178{
4179 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4180 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004181 struct hlua *hlua;
4182
4183 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004184 if (!s->hlua) {
4185 lua_pushnil(L);
4186 return 1;
4187 }
4188 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004189
4190 /* Push configuration index in the stack. */
4191 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4192
4193 return 1;
4194}
4195
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004196__LJMP static void hlua_applet_htx_reply_100_continue(lua_State *L)
4197{
4198 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4199 struct stream_interface *si = appctx->appctx->owner;
4200 struct channel *res = si_ic(si);
4201 struct htx *htx = htx_from_buf(&res->buf);
4202 struct htx_sl *sl;
4203 unsigned int flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11|
4204 HTX_SL_F_XFER_LEN|HTX_SL_F_BODYLESS);
4205 size_t data;
4206
4207 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags,
4208 ist("HTTP/1.1"), ist("100"), ist("Continue"));
4209 if (!sl)
4210 goto fail;
4211 sl->info.res.status = 100;
4212 if (!htx_add_endof(htx, HTX_BLK_EOH) || !htx_add_endof(htx, HTX_BLK_EOM))
4213 goto fail;
4214
4215 data = htx->data - co_data(res);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004216 channel_add_input(res, data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004217 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4218 return;
4219
4220 fail:
4221 hlua_pusherror(L, "Lua applet http '%s': Failed to create 100-Continue response.\n",
4222 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4223 WILL_LJMP(lua_error(L));
4224}
4225
4226
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004227/* If expected data not yet available, it returns a yield. This function
4228 * consumes the data in the buffer. It returns a string containing the
4229 * data. This string can be empty.
4230 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004231__LJMP static int hlua_applet_htx_getline_yield(lua_State *L, int status, lua_KContext ctx)
4232{
4233 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4234 struct stream_interface *si = appctx->appctx->owner;
4235 struct channel *req = si_oc(si);
4236 struct htx *htx;
4237 struct htx_blk *blk;
4238 size_t count;
4239 int stop = 0;
4240
4241 /* Maybe we cant send a 100-continue ? */
4242 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C)
4243 MAY_LJMP(hlua_applet_htx_reply_100_continue(L));
4244
4245 htx = htx_from_buf(&req->buf);
4246 count = co_data(req);
4247 blk = htx_get_head_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004248
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004249 while (count && !stop && blk) {
4250 enum htx_blk_type type = htx_get_blk_type(blk);
4251 uint32_t sz = htx_get_blksz(blk);
4252 struct ist v;
4253 uint32_t vlen;
4254 char *nl;
4255
Christopher Faulete461e342018-12-18 16:43:35 +01004256 if (type == HTX_BLK_EOM) {
4257 stop = 1;
4258 break;
4259 }
4260
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004261 vlen = sz;
4262 if (vlen > count) {
4263 if (type != HTX_BLK_DATA)
4264 break;
4265 vlen = count;
4266 }
4267
4268 switch (type) {
4269 case HTX_BLK_UNUSED:
4270 break;
4271
4272 case HTX_BLK_DATA:
4273 v = htx_get_blk_value(htx, blk);
4274 v.len = vlen;
4275 nl = istchr(v, '\n');
4276 if (nl != NULL) {
4277 stop = 1;
4278 vlen = nl - v.ptr + 1;
4279 }
4280 luaL_addlstring(&appctx->b, v.ptr, vlen);
4281 break;
4282
4283 case HTX_BLK_EOD:
4284 case HTX_BLK_TLR:
4285 case HTX_BLK_EOM:
4286 stop = 1;
4287 break;
4288
4289 default:
4290 break;
4291 }
4292
4293 co_set_data(req, co_data(req) - vlen);
4294 count -= vlen;
4295 if (sz == vlen)
4296 blk = htx_remove_blk(htx, blk);
4297 else {
4298 htx_cut_data_blk(htx, blk, vlen);
4299 break;
4300 }
4301 }
4302
4303 if (!stop) {
4304 si_cant_get(si);
4305 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_getline_yield, TICK_ETERNITY, 0));
4306 }
4307
4308 /* return the result. */
4309 luaL_pushresult(&appctx->b);
4310 return 1;
4311}
4312
4313
4314/* If expected data not yet available, it returns a yield. This function
4315 * consumes the data in the buffer. It returns a string containing the
4316 * data. This string can be empty.
4317 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004318__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004319{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004320 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4321 struct stream_interface *si = appctx->appctx->owner;
4322 struct channel *chn = si_ic(si);
4323 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004324 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004325 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004326 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004327 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004328
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004329 /* Maybe we cant send a 100-continue ? */
4330 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02004331 ret = ci_putblk(chn, HTTP_100.ptr, HTTP_100.len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004332 /* if ret == -2 or -3 the channel closed or the message si too
4333 * big for the buffers. We cant send anything. So, we ignoring
4334 * the error, considers that the 100-continue is sent, and try
4335 * to receive.
4336 * If ret is -1, we dont have room in the buffer, so we yield.
4337 */
4338 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004339 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004340 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004341 }
4342 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4343 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004344
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004345 /* Check for the end of the data. */
4346 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4347 luaL_pushresult(&appctx->b);
4348 return 1;
4349 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004350
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004351 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004352 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004353
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004354 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004355 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004356 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004357 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004358 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004359
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004360 /* End of data: commit the total strings and return. */
4361 if (ret < 0) {
4362 luaL_pushresult(&appctx->b);
4363 return 1;
4364 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004365
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004366 /* Ensure that the block 2 length is usable. */
4367 if (ret == 1)
4368 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004369
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004370 /* Copy the fisrt block caping to the length required. */
4371 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4372 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4373 luaL_addlstring(&appctx->b, blk1, len1);
4374 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004375
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004376 /* Copy the second block. */
4377 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4378 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4379 luaL_addlstring(&appctx->b, blk2, len2);
4380 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004381
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004382 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004383 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004384 luaL_pushresult(&appctx->b);
4385 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004386}
4387
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004388/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004389__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004390{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004391 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004392
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004393 /* Initialise the string catenation. */
4394 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004395
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004396 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
4397 return MAY_LJMP(hlua_applet_htx_getline_yield(L, 0, 0));
4398 else
4399 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004400}
4401
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004402/* If expected data not yet available, it returns a yield. This function
4403 * consumes the data in the buffer. It returns a string containing the
4404 * data. This string can be empty.
4405 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004406__LJMP static int hlua_applet_htx_recv_yield(lua_State *L, int status, lua_KContext ctx)
4407{
4408 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4409 struct stream_interface *si = appctx->appctx->owner;
4410 struct channel *req = si_oc(si);
4411 struct htx *htx;
4412 struct htx_blk *blk;
4413 size_t count;
4414 int len;
4415
4416 /* Maybe we cant send a 100-continue ? */
4417 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C)
4418 MAY_LJMP(hlua_applet_htx_reply_100_continue(L));
4419
4420 htx = htx_from_buf(&req->buf);
4421 len = MAY_LJMP(luaL_checkinteger(L, 2));
4422 count = co_data(req);
4423 blk = htx_get_head_blk(htx);
4424 while (count && len && blk) {
4425 enum htx_blk_type type = htx_get_blk_type(blk);
4426 uint32_t sz = htx_get_blksz(blk);
4427 struct ist v;
4428 uint32_t vlen;
4429
Christopher Faulete461e342018-12-18 16:43:35 +01004430 if (type == HTX_BLK_EOM) {
4431 len = 0;
4432 break;
4433 }
4434
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004435 vlen = sz;
4436 if (len > 0 && vlen > len)
4437 vlen = len;
4438 if (vlen > count) {
4439 if (type != HTX_BLK_DATA)
4440 break;
4441 vlen = count;
4442 }
4443
4444 switch (type) {
4445 case HTX_BLK_UNUSED:
4446 break;
4447
4448 case HTX_BLK_DATA:
4449 v = htx_get_blk_value(htx, blk);
4450 luaL_addlstring(&appctx->b, v.ptr, vlen);
4451 break;
4452
4453 case HTX_BLK_EOD:
4454 case HTX_BLK_TLR:
4455 case HTX_BLK_EOM:
4456 len = 0;
4457 break;
4458
4459 default:
4460 break;
4461 }
4462
4463 co_set_data(req, co_data(req) - vlen);
4464 count -= vlen;
4465 if (len > 0)
4466 len -= vlen;
4467 if (sz == vlen)
4468 blk = htx_remove_blk(htx, blk);
4469 else {
4470 htx_cut_data_blk(htx, blk, vlen);
4471 break;
4472 }
4473 }
4474
4475 /* If we are no other data available, yield waiting for new data. */
4476 if (len) {
4477 if (len > 0) {
4478 lua_pushinteger(L, len);
4479 lua_replace(L, 2);
4480 }
4481 si_cant_get(si);
4482 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_recv_yield, TICK_ETERNITY, 0));
4483 }
4484
4485 /* return the result. */
4486 luaL_pushresult(&appctx->b);
4487 return 1;
4488}
4489
4490/* If expected data not yet available, it returns a yield. This function
4491 * consumes the data in the buffer. It returns a string containing the
4492 * data. This string can be empty.
4493 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004494__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004495{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004496 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4497 struct stream_interface *si = appctx->appctx->owner;
4498 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4499 struct channel *chn = si_ic(si);
4500 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004501 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004502 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004503 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004504 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004505
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004506 /* Maybe we cant send a 100-continue ? */
4507 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02004508 ret = ci_putblk(chn, HTTP_100.ptr, HTTP_100.len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004509 /* if ret == -2 or -3 the channel closed or the message si too
4510 * big for the buffers. We cant send anything. So, we ignoring
4511 * the error, considers that the 100-continue is sent, and try
4512 * to receive.
4513 * If ret is -1, we dont have room in the buffer, so we yield.
4514 */
4515 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004516 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004517 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004518 }
4519 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4520 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004521
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004522 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004523 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004524
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004525 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004526 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004527 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004528 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004529 }
4530
4531 /* End of data: commit the total strings and return. */
4532 if (ret < 0) {
4533 luaL_pushresult(&appctx->b);
4534 return 1;
4535 }
4536
4537 /* Ensure that the block 2 length is usable. */
4538 if (ret == 1)
4539 len2 = 0;
4540
4541 /* Copy the fisrt block caping to the length required. */
4542 if (len1 > len)
4543 len1 = len;
4544 luaL_addlstring(&appctx->b, blk1, len1);
4545 len -= len1;
4546
4547 /* Copy the second block. */
4548 if (len2 > len)
4549 len2 = len;
4550 luaL_addlstring(&appctx->b, blk2, len2);
4551 len -= len2;
4552
4553 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004554 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004555 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4556 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4557
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004558 /* If we are no other data available, yield waiting for new data. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004559 if (len > 0) {
4560 lua_pushinteger(L, len);
4561 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004562 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004563 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004564 }
4565
4566 /* return the result. */
4567 luaL_pushresult(&appctx->b);
4568 return 1;
4569}
4570
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004571/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004572__LJMP static int hlua_applet_http_recv(lua_State *L)
4573{
4574 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4575 int len = -1;
4576
4577 /* Check arguments. */
4578 if (lua_gettop(L) > 2)
4579 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4580 if (lua_gettop(L) >= 2) {
4581 len = MAY_LJMP(luaL_checkinteger(L, 2));
4582 lua_pop(L, 1);
4583 }
4584
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004585 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4586 /* HTX version */
4587 lua_pushinteger(L, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004588
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004589 /* Initialise the string catenation. */
4590 luaL_buffinit(L, &appctx->b);
4591
4592 return MAY_LJMP(hlua_applet_htx_recv_yield(L, 0, 0));
4593 }
4594 else {
4595 /* Legacy HTTP version */
4596 /* Check the required length */
4597 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4598 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4599 lua_pushinteger(L, len);
4600
4601 /* Initialise the string catenation. */
4602 luaL_buffinit(L, &appctx->b);
4603
4604 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4605 }
4606}
4607
4608/* Append data in the output side of the buffer. This data is immediately
4609 * sent. The function returns the amount of data written. If the buffer
4610 * cannot contain the data, the function yields. The function returns -1
4611 * if the channel is closed.
4612 */
4613__LJMP static int hlua_applet_htx_send_yield(lua_State *L, int status, lua_KContext ctx)
4614{
4615 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4616 struct stream_interface *si = appctx->appctx->owner;
4617 struct channel *res = si_ic(si);
4618 struct htx *htx = htx_from_buf(&res->buf);
4619 const char *data;
4620 size_t len;
4621 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4622 int max;
4623
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004624 max = channel_htx_recv_max(res, htx);
4625 if (!max)
4626 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004627
4628 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4629
4630 /* Get the max amount of data which can write as input in the channel. */
4631 if (max > (len - l))
4632 max = len - l;
4633
4634 /* Copy data. */
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004635 if (!htx_add_data(htx, ist2(data + l, max)))
4636 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004637 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004638 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004639
4640 /* update counters. */
4641 l += max;
4642 lua_pop(L, 1);
4643 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004644
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004645 /* If some data is not send, declares the situation to the
4646 * applet, and returns a yield.
4647 */
4648 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004649 snd_yield:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004650 si_rx_room_blk(si);
4651 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_send_yield, TICK_ETERNITY, 0));
4652 }
4653
4654 return 1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004655}
4656
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004657/* Append data in the output side of the buffer. This data is immediately
4658 * sent. The function returns the amount of data written. If the buffer
4659 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004660 * if the channel is closed.
4661 */
4662__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4663{
4664 size_t len;
4665 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4666 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4667 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4668 struct stream_interface *si = appctx->appctx->owner;
4669 struct channel *chn = si_ic(si);
4670 int max;
4671
4672 /* Get the max amount of data which can write as input in the channel. */
4673 max = channel_recv_max(chn);
4674 if (max > (len - l))
4675 max = len - l;
4676
4677 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004678 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004679
4680 /* update counters. */
4681 l += max;
4682 lua_pop(L, 1);
4683 lua_pushinteger(L, l);
4684
4685 /* If some data is not send, declares the situation to the
4686 * applet, and returns a yield.
4687 */
4688 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004689 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004690 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004691 }
4692
4693 return 1;
4694}
4695
4696/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4697 * yield the LUA process, and resume it without checking the
4698 * input arguments.
4699 */
4700__LJMP static int hlua_applet_http_send(lua_State *L)
4701{
4702 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004703
4704 /* We want to send some data. Headers must be sent. */
4705 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4706 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4707 WILL_LJMP(lua_error(L));
4708 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004709
4710 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4711 /* HTX version */
4712 /* This interger is used for followinf the amount of data sent. */
4713 lua_pushinteger(L, 0);
4714
4715 return MAY_LJMP(hlua_applet_htx_send_yield(L, 0, 0));
4716 }
4717 else {
4718 /* Legacy HTTP version */
4719 size_t len;
4720 char hex[10];
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004721
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004722 MAY_LJMP(luaL_checklstring(L, 2, &len));
4723
4724 /* If transfer encoding chunked is selected, we surround the data
4725 * by chunk data.
4726 */
4727 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4728 snprintf(hex, 9, "%x", (unsigned int)len);
4729 lua_pushfstring(L, "%s\r\n", hex);
4730 lua_insert(L, 2); /* swap the last 2 entries. */
4731 lua_pushstring(L, "\r\n");
4732 lua_concat(L, 3);
4733 }
4734
4735 /* This interger is used for followinf the amount of data sent. */
4736 lua_pushinteger(L, 0);
4737
4738 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4739 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004740}
4741
4742__LJMP static int hlua_applet_http_addheader(lua_State *L)
4743{
4744 const char *name;
4745 int ret;
4746
4747 MAY_LJMP(hlua_checkapplet_http(L, 1));
4748 name = MAY_LJMP(luaL_checkstring(L, 2));
4749 MAY_LJMP(luaL_checkstring(L, 3));
4750
4751 /* Push in the stack the "response" entry. */
4752 ret = lua_getfield(L, 1, "response");
4753 if (ret != LUA_TTABLE) {
4754 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4755 "is expected as an array. %s found", lua_typename(L, ret));
4756 WILL_LJMP(lua_error(L));
4757 }
4758
4759 /* check if the header is already registered if it is not
4760 * the case, register it.
4761 */
4762 ret = lua_getfield(L, -1, name);
4763 if (ret == LUA_TNIL) {
4764
4765 /* Entry not found. */
4766 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4767
4768 /* Insert the new header name in the array in the top of the stack.
4769 * It left the new array in the top of the stack.
4770 */
4771 lua_newtable(L);
4772 lua_pushvalue(L, 2);
4773 lua_pushvalue(L, -2);
4774 lua_settable(L, -4);
4775
4776 } else if (ret != LUA_TTABLE) {
4777
4778 /* corruption error. */
4779 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4780 "is expected as an array. %s found", name, lua_typename(L, ret));
4781 WILL_LJMP(lua_error(L));
4782 }
4783
4784 /* Now the top od thestack is an array of values. We push
4785 * the header value as new entry.
4786 */
4787 lua_pushvalue(L, 3);
4788 ret = lua_rawlen(L, -2);
4789 lua_rawseti(L, -2, ret + 1);
4790 lua_pushboolean(L, 1);
4791 return 1;
4792}
4793
4794__LJMP static int hlua_applet_http_status(lua_State *L)
4795{
4796 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4797 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004798 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004799
4800 if (status < 100 || status > 599) {
4801 lua_pushboolean(L, 0);
4802 return 1;
4803 }
4804
4805 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004806 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004807 lua_pushboolean(L, 1);
4808 return 1;
4809}
4810
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004811
4812__LJMP static int hlua_applet_htx_send_response(lua_State *L)
4813{
4814 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4815 struct stream_interface *si = appctx->appctx->owner;
4816 struct channel *res = si_ic(si);
4817 struct htx *htx;
4818 struct htx_sl *sl;
4819 struct h1m h1m;
4820 const char *status, *reason;
4821 const char *name, *value;
4822 size_t nlen, vlen;
4823 unsigned int flags;
4824
4825 /* Send the message at once. */
4826 htx = htx_from_buf(&res->buf);
4827 h1m_init_res(&h1m);
4828
4829 /* Use the same http version than the request. */
4830 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4831 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4832 if (reason == NULL)
4833 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4834 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4835 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4836 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4837 }
4838 else {
4839 flags = HTX_SL_F_IS_RESP;
4840 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4841 }
4842 if (!sl) {
4843 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
4844 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4845 WILL_LJMP(lua_error(L));
4846 }
4847 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4848
4849 /* Get the array associated to the field "response" in the object AppletHTTP. */
4850 lua_pushvalue(L, 0);
4851 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4852 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4853 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4854 WILL_LJMP(lua_error(L));
4855 }
4856
4857 /* Browse the list of headers. */
4858 lua_pushnil(L);
4859 while(lua_next(L, -2) != 0) {
4860 /* We expect a string as -2. */
4861 if (lua_type(L, -2) != LUA_TSTRING) {
4862 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4863 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4864 lua_typename(L, lua_type(L, -2)));
4865 WILL_LJMP(lua_error(L));
4866 }
4867 name = lua_tolstring(L, -2, &nlen);
4868
4869 /* We expect an array as -1. */
4870 if (lua_type(L, -1) != LUA_TTABLE) {
4871 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4872 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4873 name,
4874 lua_typename(L, lua_type(L, -1)));
4875 WILL_LJMP(lua_error(L));
4876 }
4877
4878 /* Browse the table who is on the top of the stack. */
4879 lua_pushnil(L);
4880 while(lua_next(L, -2) != 0) {
4881 int id;
4882
4883 /* We expect a number as -2. */
4884 if (lua_type(L, -2) != LUA_TNUMBER) {
4885 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4886 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4887 name,
4888 lua_typename(L, lua_type(L, -2)));
4889 WILL_LJMP(lua_error(L));
4890 }
4891 id = lua_tointeger(L, -2);
4892
4893 /* We expect a string as -2. */
4894 if (lua_type(L, -1) != LUA_TSTRING) {
4895 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4896 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4897 name, id,
4898 lua_typename(L, lua_type(L, -1)));
4899 WILL_LJMP(lua_error(L));
4900 }
4901 value = lua_tolstring(L, -1, &vlen);
4902
4903 /* Simple Protocol checks. */
4904 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
4905 h1_parse_xfer_enc_header(&h1m, ist2(name, nlen));
4906 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4907 struct ist v = ist2(value, vlen);
4908 int ret;
4909
4910 ret = h1_parse_cont_len_header(&h1m, &v);
4911 if (ret < 0) {
4912 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
4913 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4914 name);
4915 WILL_LJMP(lua_error(L));
4916 }
4917 else if (ret == 0)
4918 goto next; /* Skip it */
4919 }
4920
4921 /* Add a new header */
4922 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4923 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
4924 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4925 name);
4926 WILL_LJMP(lua_error(L));
4927 }
4928 next:
4929 /* Remove the array from the stack, and get next element with a remaining string. */
4930 lua_pop(L, 1);
4931 }
4932
4933 /* Remove the array from the stack, and get next element with a remaining string. */
4934 lua_pop(L, 1);
4935 }
4936
4937 if (h1m.flags & H1_MF_CHNK)
4938 h1m.flags &= ~H1_MF_CLEN;
4939 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4940 h1m.flags |= H1_MF_XFER_LEN;
4941
4942 /* Uset HTX start-line flags */
4943 if (h1m.flags & H1_MF_XFER_ENC)
4944 flags |= HTX_SL_F_XFER_ENC;
4945 if (h1m.flags & H1_MF_XFER_LEN) {
4946 flags |= HTX_SL_F_XFER_LEN;
4947 if (h1m.flags & H1_MF_CHNK)
4948 flags |= HTX_SL_F_CHNK;
4949 else if (h1m.flags & H1_MF_CLEN)
4950 flags |= HTX_SL_F_CLEN;
4951 if (h1m.body_len == 0)
4952 flags |= HTX_SL_F_BODYLESS;
4953 }
4954 sl->flags |= flags;
4955
4956 /* If we dont have a content-length set, and the HTTP version is 1.1
4957 * and the status code implies the presence of a message body, we must
4958 * announce a transfer encoding chunked. This is required by haproxy
4959 * for the keepalive compliance. If the applet annouces a transfer-encoding
4960 * chunked itslef, don't do anything.
4961 */
4962 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4963 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4964 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4965 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4966 /* Add a new header */
4967 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4968 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4969 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
4970 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4971 WILL_LJMP(lua_error(L));
4972 }
4973 }
4974
4975 /* Finalize headers. */
4976 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4977 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
4978 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4979 WILL_LJMP(lua_error(L));
4980 }
4981
4982 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4983 b_reset(&res->buf);
4984 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4985 WILL_LJMP(lua_error(L));
4986 }
4987
4988 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004989 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004990
4991 /* Headers sent, set the flag. */
4992 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4993 return 0;
4994
4995}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004996/* We will build the status line and the headers of the HTTP response.
4997 * We will try send at once if its not possible, we give back the hand
4998 * waiting for more room.
4999 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005000__LJMP static int hlua_applet_htx_start_response_yield(lua_State *L, int status, lua_KContext ctx)
5001{
5002 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5003 struct stream_interface *si = appctx->appctx->owner;
5004 struct channel *res = si_ic(si);
5005
5006 if (co_data(res)) {
5007 si_rx_room_blk(si);
5008 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_start_response_yield, TICK_ETERNITY, 0));
5009 }
5010 return MAY_LJMP(hlua_applet_htx_send_response(L));
5011}
5012
5013
5014__LJMP static int hlua_applet_htx_start_response(lua_State *L)
5015{
5016 return MAY_LJMP(hlua_applet_htx_start_response_yield(L, 0, 0));
5017}
5018
5019/* We will build the status line and the headers of the HTTP response.
5020 * We will try send at once if its not possible, we give back the hand
5021 * waiting for more room.
5022 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005023__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
5024{
5025 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5026 struct stream_interface *si = appctx->appctx->owner;
5027 struct channel *chn = si_ic(si);
5028 int ret;
5029 size_t len;
5030 const char *msg;
5031
5032 /* Get the message as the first argument on the stack. */
5033 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
5034
5035 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02005036 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005037
5038 /* if ret == -2 or -3 the channel closed or the message si too
5039 * big for the buffers.
5040 */
5041 if (ret == -2 || ret == -3) {
5042 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5043 WILL_LJMP(lua_error(L));
5044 }
5045
5046 /* If ret is -1, we dont have room in the buffer, so we yield. */
5047 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01005048 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005049 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005050 }
5051
5052 /* Headers sent, set the flag. */
5053 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
5054 return 0;
5055}
5056
5057__LJMP static int hlua_applet_http_start_response(lua_State *L)
5058{
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005059 struct buffer *tmp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005060 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005061 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02005062 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005063 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02005064 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005065 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005066 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005067 int hdr_chunked = 0;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005068 const char *reason;
5069
5070 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
5071 return MAY_LJMP(hlua_applet_htx_start_response(L));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005072
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005073 reason = appctx->appctx->ctx.hlua_apphttp.reason;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005074 if (reason == NULL)
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02005075 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005076
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005077 tmp = get_trash_chunk();
5078
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005079 /* Use the same http version than the request. */
5080 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005081 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005082 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005083 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005084
5085 /* Get the array associated to the field "response" in the object AppletHTTP. */
5086 lua_pushvalue(L, 0);
5087 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5088 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
5089 appctx->appctx->rule->arg.hlua_rule->fcn.name);
5090 WILL_LJMP(lua_error(L));
5091 }
5092
5093 /* Browse the list of headers. */
5094 lua_pushnil(L);
5095 while(lua_next(L, -2) != 0) {
5096
5097 /* We expect a string as -2. */
5098 if (lua_type(L, -2) != LUA_TSTRING) {
5099 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
5100 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5101 lua_typename(L, lua_type(L, -2)));
5102 WILL_LJMP(lua_error(L));
5103 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005104 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005105
5106 /* We expect an array as -1. */
5107 if (lua_type(L, -1) != LUA_TTABLE) {
5108 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
5109 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5110 name,
5111 lua_typename(L, lua_type(L, -1)));
5112 WILL_LJMP(lua_error(L));
5113 }
5114
5115 /* Browse the table who is on the top of the stack. */
5116 lua_pushnil(L);
5117 while(lua_next(L, -2) != 0) {
5118
5119 /* We expect a number as -2. */
5120 if (lua_type(L, -2) != LUA_TNUMBER) {
5121 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
5122 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5123 name,
5124 lua_typename(L, lua_type(L, -2)));
5125 WILL_LJMP(lua_error(L));
5126 }
5127 id = lua_tointeger(L, -2);
5128
5129 /* We expect a string as -2. */
5130 if (lua_type(L, -1) != LUA_TSTRING) {
5131 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
5132 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5133 name, id,
5134 lua_typename(L, lua_type(L, -1)));
5135 WILL_LJMP(lua_error(L));
5136 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005137 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005138
5139 /* Catenate a new header. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005140 if (tmp->data + name_len + 2 + value_len + 2 < tmp->size) {
5141 memcpy(tmp->area + tmp->data, name, name_len);
5142 tmp->data += name_len;
5143 tmp->area[tmp->data++] = ':';
5144 tmp->area[tmp->data++] = ' ';
Willy Tarreaua3294632017-08-23 11:24:47 +02005145
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005146 memcpy(tmp->area + tmp->data, value,
5147 value_len);
5148 tmp->data += value_len;
5149 tmp->area[tmp->data++] = '\r';
5150 tmp->area[tmp->data++] = '\n';
Willy Tarreaua3294632017-08-23 11:24:47 +02005151 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005152
5153 /* Protocol checks. */
5154
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005155 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005156 * is done without control. If it contains a bad value,
5157 * the content-length remains negative so that we can
5158 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005159 */
Willy Tarreaua3294632017-08-23 11:24:47 +02005160 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005161 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005162
5163 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02005164 if (name_len == 17 && value_len == 7 &&
5165 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005166 strcasecmp("chunked", value) == 0)
5167 hdr_chunked = 1;
5168
5169 /* Remove the array from the stack, and get next element with a remaining string. */
5170 lua_pop(L, 1);
5171 }
5172
5173 /* Remove the array from the stack, and get next element with a remaining string. */
5174 lua_pop(L, 1);
5175 }
5176
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005177 /* If we dont have a content-length set, and the HTTP version is 1.1
5178 * and the status code implies the presence of a message body, we must
5179 * announce a transfer encoding chunked. This is required by haproxy
5180 * for the keepalive compliance. If the applet annouces a transfer-encoding
5181 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005182 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005183 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005184 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
5185 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
5186 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
5187 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005188 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
5189 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
5190 }
5191
5192 /* Finalize headers. */
5193 chunk_appendf(tmp, "\r\n");
5194
5195 /* Remove the last entry and the array of headers */
5196 lua_pop(L, 2);
5197
5198 /* Push the headers block. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005199 lua_pushlstring(L, tmp->area, tmp->data);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005200
5201 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
5202}
5203
5204/*
5205 *
5206 *
5207 * Class HTTP
5208 *
5209 *
5210 */
5211
5212/* Returns a struct hlua_txn if the stack entry "ud" is
5213 * a class stream, otherwise it throws an error.
5214 */
5215__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
5216{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005217 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005218}
5219
5220/* This function creates and push in the stack a HTTP object
5221 * according with a current TXN.
5222 */
5223static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5224{
5225 struct hlua_txn *htxn;
5226
5227 /* Check stack size. */
5228 if (!lua_checkstack(L, 3))
5229 return 0;
5230
5231 /* Create the object: obj[0] = userdata.
5232 * Note that the base of the Converters object is the
5233 * same than the TXN object.
5234 */
5235 lua_newtable(L);
5236 htxn = lua_newuserdata(L, sizeof(*htxn));
5237 lua_rawseti(L, -2, 0);
5238
5239 htxn->s = txn->s;
5240 htxn->p = txn->p;
5241
5242 /* Pop a class stream metatable and affect it to the table. */
5243 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5244 lua_setmetatable(L, -2);
5245
5246 return 1;
5247}
5248
5249/* This function creates ans returns an array of HTTP headers.
5250 * This function does not fails. It is used as wrapper with the
5251 * 2 following functions.
5252 */
5253__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5254{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005255 /* Create the table. */
5256 lua_newtable(L);
5257
5258 if (!htxn->s->txn)
5259 return 1;
5260
Christopher Faulet724a12c2018-12-13 22:12:15 +01005261 if (IS_HTX_STRM(htxn->s)) {
5262 /* HTX version */
5263 struct htx *htx = htxbuf(&msg->chn->buf);
5264 int32_t pos;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005265
Christopher Faulet724a12c2018-12-13 22:12:15 +01005266 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5267 struct htx_blk *blk = htx_get_blk(htx, pos);
5268 enum htx_blk_type type = htx_get_blk_type(blk);
5269 struct ist n, v;
5270 int len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005271
Christopher Faulet724a12c2018-12-13 22:12:15 +01005272 if (type == HTX_BLK_HDR) {
5273 n = htx_get_blk_name(htx,blk);
5274 v = htx_get_blk_value(htx, blk);
5275 }
5276 else if (type == HTX_BLK_EOH)
5277 break;
5278 else
5279 continue;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005280
Christopher Faulet724a12c2018-12-13 22:12:15 +01005281 /* Check for existing entry:
5282 * assume that the table is on the top of the stack, and
5283 * push the key in the stack, the function lua_gettable()
5284 * perform the lookup.
5285 */
5286 lua_pushlstring(L, n.ptr, n.len);
5287 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005288
Christopher Faulet724a12c2018-12-13 22:12:15 +01005289 switch (lua_type(L, -1)) {
5290 case LUA_TNIL:
5291 /* Table not found, create it. */
5292 lua_pop(L, 1); /* remove the nil value. */
5293 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5294 lua_newtable(L); /* create and push empty table. */
5295 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5296 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5297 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5298 break;
5299
5300 case LUA_TTABLE:
5301 /* Entry found: push the value in the table. */
5302 len = lua_rawlen(L, -1);
5303 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5304 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5305 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5306 break;
5307
5308 default:
5309 /* Other cases are errors. */
5310 hlua_pusherror(L, "internal error during the parsing of headers.");
5311 WILL_LJMP(lua_error(L));
5312 }
5313 }
5314 }
5315 else {
5316 /* Legacy HTTP version */
5317 const char *cur_ptr, *cur_next, *p;
5318 int old_idx, cur_idx;
5319 struct hdr_idx_elem *cur_hdr;
5320 const char *hn, *hv;
5321 int hnl, hvl;
5322 const char *in;
5323 char *out;
5324 int len;
5325
5326 /* Build array of headers. */
5327 old_idx = 0;
5328 cur_next = ci_head(msg->chn) + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
5329
5330 while (1) {
5331 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
5332 if (!cur_idx)
5333 break;
5334 old_idx = cur_idx;
5335
5336 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
5337 cur_ptr = cur_next;
5338 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
5339
5340 /* Now we have one full header at cur_ptr of len cur_hdr->len,
5341 * and the next header starts at cur_next. We'll check
5342 * this header in the list as well as against the default
5343 * rule.
5344 */
5345
5346 /* look for ': *'. */
5347 hn = cur_ptr;
5348 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
5349 if (p >= cur_ptr+cur_hdr->len)
5350 continue;
5351 hnl = p - hn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005352 p++;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005353 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
5354 p++;
5355 if (p >= cur_ptr+cur_hdr->len)
5356 continue;
5357 hv = p;
5358 hvl = cur_ptr+cur_hdr->len-p;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005359
Christopher Faulet724a12c2018-12-13 22:12:15 +01005360 /* Lowercase the key. Don't check the size of trash, it have
5361 * the size of one buffer and the input data contains in one
5362 * buffer.
5363 */
5364 out = trash.area;
5365 for (in=hn; in<hn+hnl; in++, out++)
5366 *out = tolower(*in);
5367 *out = '\0';
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005368
Christopher Faulet724a12c2018-12-13 22:12:15 +01005369 /* Check for existing entry:
5370 * assume that the table is on the top of the stack, and
5371 * push the key in the stack, the function lua_gettable()
5372 * perform the lookup.
5373 */
5374 lua_pushlstring(L, trash.area, hnl);
5375 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005376
Christopher Faulet724a12c2018-12-13 22:12:15 +01005377 switch (lua_type(L, -1)) {
5378 case LUA_TNIL:
5379 /* Table not found, create it. */
5380 lua_pop(L, 1); /* remove the nil value. */
5381 lua_pushlstring(L, trash.area, hnl); /* push the header name as key. */
5382 lua_newtable(L); /* create and push empty table. */
5383 lua_pushlstring(L, hv, hvl); /* push header value. */
5384 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5385 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5386 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005387
Christopher Faulet724a12c2018-12-13 22:12:15 +01005388 case LUA_TTABLE:
5389 /* Entry found: push the value in the table. */
5390 len = lua_rawlen(L, -1);
5391 lua_pushlstring(L, hv, hvl); /* push header value. */
5392 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5393 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5394 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005395
Christopher Faulet724a12c2018-12-13 22:12:15 +01005396 default:
5397 /* Other cases are errors. */
5398 hlua_pusherror(L, "internal error during the parsing of headers.");
5399 WILL_LJMP(lua_error(L));
5400 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005401 }
5402 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005403 return 1;
5404}
5405
5406__LJMP static int hlua_http_req_get_headers(lua_State *L)
5407{
5408 struct hlua_txn *htxn;
5409
5410 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5411 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5412
5413 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
5414}
5415
5416__LJMP static int hlua_http_res_get_headers(lua_State *L)
5417{
5418 struct hlua_txn *htxn;
5419
5420 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5421 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5422
5423 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
5424}
5425
5426/* This function replace full header, or just a value in
5427 * the request or in the response. It is a wrapper fir the
5428 * 4 following functions.
5429 */
5430__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
5431 struct http_msg *msg, int action)
5432{
5433 size_t name_len;
5434 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5435 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5436 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
5437 struct my_regex re;
5438
5439 if (!regex_comp(reg, &re, 1, 1, NULL))
5440 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5441
5442 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
5443 regex_free(&re);
5444 return 0;
5445}
5446
5447__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5448{
5449 struct hlua_txn *htxn;
5450
5451 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5452 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5453
5454 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
5455}
5456
5457__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5458{
5459 struct hlua_txn *htxn;
5460
5461 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5462 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5463
5464 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
5465}
5466
5467__LJMP static int hlua_http_req_rep_val(lua_State *L)
5468{
5469 struct hlua_txn *htxn;
5470
5471 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5472 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5473
5474 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
5475}
5476
5477__LJMP static int hlua_http_res_rep_val(lua_State *L)
5478{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005479 struct hlua_txn *htxn;
5480
5481 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5482 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5483
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02005484 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005485}
5486
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005487/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005488 * It is a wrapper for the 2 following functions.
5489 */
5490__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5491{
5492 size_t len;
5493 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005494
Christopher Faulet724a12c2018-12-13 22:12:15 +01005495 if (IS_HTX_STRM(htxn->s)) {
5496 /* HTX version */
5497 struct htx *htx = htxbuf(&msg->chn->buf);
5498 struct http_hdr_ctx ctx;
5499
5500 ctx.blk = NULL;
5501 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5502 http_remove_header(htx, &ctx);
5503 }
5504 else {
5505 /* Legacy HTTP version */
5506 struct hdr_ctx ctx;
5507 struct http_txn *txn = htxn->s->txn;
5508
5509 ctx.idx = 0;
5510 while (http_find_header2(name, len, ci_head(msg->chn), &txn->hdr_idx, &ctx))
5511 http_remove_header2(msg, &txn->hdr_idx, &ctx);
5512 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005513 return 0;
5514}
5515
5516__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5517{
5518 struct hlua_txn *htxn;
5519
5520 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5521 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5522
Willy Tarreaueee5b512015-04-03 23:46:31 +02005523 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005524}
5525
5526__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5527{
5528 struct hlua_txn *htxn;
5529
5530 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5531 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5532
Willy Tarreaueee5b512015-04-03 23:46:31 +02005533 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005534}
5535
5536/* This function adds an header. It is a wrapper used by
5537 * the 2 following functions.
5538 */
5539__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5540{
5541 size_t name_len;
5542 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5543 size_t value_len;
5544 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
5545 char *p;
5546
Christopher Faulet724a12c2018-12-13 22:12:15 +01005547 if (IS_HTX_STRM(htxn->s)) {
5548 /* HTX version */
5549 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005550
Christopher Faulet724a12c2018-12-13 22:12:15 +01005551 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5552 ist2(value, value_len)));
5553 }
5554 else {
5555 /* Legacy HTTP version */
5556 /* Check length. */
5557 trash.data = value_len + name_len + 2;
5558 if (trash.data > trash.size)
5559 return 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005560
Christopher Faulet724a12c2018-12-13 22:12:15 +01005561 /* Creates the header string. */
5562 p = trash.area;
5563 memcpy(p, name, name_len);
5564 p += name_len;
5565 *p = ':';
5566 p++;
5567 *p = ' ';
5568 p++;
5569 memcpy(p, value, value_len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005570
Christopher Faulet724a12c2018-12-13 22:12:15 +01005571 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
5572 trash.area, trash.data) != 0);
5573 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005574 return 0;
5575}
5576
5577__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5578{
5579 struct hlua_txn *htxn;
5580
5581 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5582 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5583
Willy Tarreaueee5b512015-04-03 23:46:31 +02005584 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005585}
5586
5587__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5588{
5589 struct hlua_txn *htxn;
5590
5591 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5592 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5593
Willy Tarreaueee5b512015-04-03 23:46:31 +02005594 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005595}
5596
5597static int hlua_http_req_set_hdr(lua_State *L)
5598{
5599 struct hlua_txn *htxn;
5600
5601 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5602 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5603
Willy Tarreaueee5b512015-04-03 23:46:31 +02005604 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
5605 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005606}
5607
5608static int hlua_http_res_set_hdr(lua_State *L)
5609{
5610 struct hlua_txn *htxn;
5611
5612 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5613 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5614
Willy Tarreaueee5b512015-04-03 23:46:31 +02005615 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
5616 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005617}
5618
5619/* This function set the method. */
5620static int hlua_http_req_set_meth(lua_State *L)
5621{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005622 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005623 size_t name_len;
5624 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005625
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005626 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005627 return 1;
5628}
5629
5630/* This function set the method. */
5631static int hlua_http_req_set_path(lua_State *L)
5632{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005633 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005634 size_t name_len;
5635 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005636
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005637 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005638 return 1;
5639}
5640
5641/* This function set the query-string. */
5642static int hlua_http_req_set_query(lua_State *L)
5643{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005644 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005645 size_t name_len;
5646 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005647
5648 /* Check length. */
5649 if (name_len > trash.size - 1) {
5650 lua_pushboolean(L, 0);
5651 return 1;
5652 }
5653
5654 /* Add the mark question as prefix. */
5655 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005656 trash.area[trash.data++] = '?';
5657 memcpy(trash.area + trash.data, name, name_len);
5658 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005659
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005660 lua_pushboolean(L,
5661 http_replace_req_line(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005662 return 1;
5663}
5664
5665/* This function set the uri. */
5666static int hlua_http_req_set_uri(lua_State *L)
5667{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005668 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005669 size_t name_len;
5670 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005671
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005672 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005673 return 1;
5674}
5675
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005676/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005677static int hlua_http_res_set_status(lua_State *L)
5678{
5679 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5680 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005681 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005682
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005683 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005684 return 0;
5685}
5686
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005687/*
5688 *
5689 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005690 * Class TXN
5691 *
5692 *
5693 */
5694
5695/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005696 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005697 */
5698__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5699{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005700 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005701}
5702
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005703__LJMP static int hlua_set_var(lua_State *L)
5704{
5705 struct hlua_txn *htxn;
5706 const char *name;
5707 size_t len;
5708 struct sample smp;
5709
5710 MAY_LJMP(check_args(L, 3, "set_var"));
5711
5712 /* It is useles to retrieve the stream, but this function
5713 * runs only in a stream context.
5714 */
5715 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5716 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5717
5718 /* Converts the third argument in a sample. */
5719 hlua_lua2smp(L, 3, &smp);
5720
5721 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005722 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005723 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005724 return 0;
5725}
5726
Christopher Faulet85d79c92016-11-09 16:54:56 +01005727__LJMP static int hlua_unset_var(lua_State *L)
5728{
5729 struct hlua_txn *htxn;
5730 const char *name;
5731 size_t len;
5732 struct sample smp;
5733
5734 MAY_LJMP(check_args(L, 2, "unset_var"));
5735
5736 /* It is useles to retrieve the stream, but this function
5737 * runs only in a stream context.
5738 */
5739 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5740 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5741
5742 /* Unset the variable. */
5743 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5744 vars_unset_by_name(name, len, &smp);
5745 return 0;
5746}
5747
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005748__LJMP static int hlua_get_var(lua_State *L)
5749{
5750 struct hlua_txn *htxn;
5751 const char *name;
5752 size_t len;
5753 struct sample smp;
5754
5755 MAY_LJMP(check_args(L, 2, "get_var"));
5756
5757 /* It is useles to retrieve the stream, but this function
5758 * runs only in a stream context.
5759 */
5760 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5761 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5762
Willy Tarreau7560dd42016-03-10 16:28:58 +01005763 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005764 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005765 lua_pushnil(L);
5766 return 1;
5767 }
5768
5769 return hlua_smp2lua(L, &smp);
5770}
5771
Willy Tarreau59551662015-03-10 14:23:13 +01005772__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005773{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005774 struct hlua *hlua;
5775
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005776 MAY_LJMP(check_args(L, 2, "set_priv"));
5777
Willy Tarreau87b09662015-04-03 00:22:06 +02005778 /* It is useles to retrieve the stream, but this function
5779 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005780 */
5781 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005782 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005783
5784 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005785 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005786
5787 /* Get and store new value. */
5788 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5789 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5790
5791 return 0;
5792}
5793
Willy Tarreau59551662015-03-10 14:23:13 +01005794__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005795{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005796 struct hlua *hlua;
5797
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005798 MAY_LJMP(check_args(L, 1, "get_priv"));
5799
Willy Tarreau87b09662015-04-03 00:22:06 +02005800 /* It is useles to retrieve the stream, but this function
5801 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005802 */
5803 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005804 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005805
5806 /* Push configuration index in the stack. */
5807 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5808
5809 return 1;
5810}
5811
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005812/* Create stack entry containing a class TXN. This function
5813 * return 0 if the stack does not contains free slots,
5814 * otherwise it returns 1.
5815 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005816static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005817{
Willy Tarreaude491382015-04-06 11:04:28 +02005818 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005819
5820 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005821 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005822 return 0;
5823
5824 /* NOTE: The allocation never fails. The failure
5825 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005826 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005827 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005828 /* Create the object: obj[0] = userdata. */
5829 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005830 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005831 lua_rawseti(L, -2, 0);
5832
Willy Tarreaude491382015-04-06 11:04:28 +02005833 htxn->s = s;
5834 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005835 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005836 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005837
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005838 /* Create the "f" field that contains a list of fetches. */
5839 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005840 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005841 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005842 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005843
5844 /* Create the "sf" field that contains a list of stringsafe fetches. */
5845 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005846 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005847 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005848 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005849
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005850 /* Create the "c" field that contains a list of converters. */
5851 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005852 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005853 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005854 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005855
5856 /* Create the "sc" field that contains a list of stringsafe converters. */
5857 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005858 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005859 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005860 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005861
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005862 /* Create the "req" field that contains the request channel object. */
5863 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005864 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005865 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005866 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005867
5868 /* Create the "res" field that contains the response channel object. */
5869 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005870 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005871 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005872 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005873
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005874 /* Creates the HTTP object is the current proxy allows http. */
5875 lua_pushstring(L, "http");
5876 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005877 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005878 return 0;
5879 }
5880 else
5881 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005882 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005883
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005884 /* Pop a class sesison metatable and affect it to the userdata. */
5885 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5886 lua_setmetatable(L, -2);
5887
5888 return 1;
5889}
5890
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005891__LJMP static int hlua_txn_deflog(lua_State *L)
5892{
5893 const char *msg;
5894 struct hlua_txn *htxn;
5895
5896 MAY_LJMP(check_args(L, 2, "deflog"));
5897 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5898 msg = MAY_LJMP(luaL_checkstring(L, 2));
5899
5900 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5901 return 0;
5902}
5903
5904__LJMP static int hlua_txn_log(lua_State *L)
5905{
5906 int level;
5907 const char *msg;
5908 struct hlua_txn *htxn;
5909
5910 MAY_LJMP(check_args(L, 3, "log"));
5911 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5912 level = MAY_LJMP(luaL_checkinteger(L, 2));
5913 msg = MAY_LJMP(luaL_checkstring(L, 3));
5914
5915 if (level < 0 || level >= NB_LOG_LEVELS)
5916 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5917
5918 hlua_sendlog(htxn->s->be, level, msg);
5919 return 0;
5920}
5921
5922__LJMP static int hlua_txn_log_debug(lua_State *L)
5923{
5924 const char *msg;
5925 struct hlua_txn *htxn;
5926
5927 MAY_LJMP(check_args(L, 2, "Debug"));
5928 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5929 msg = MAY_LJMP(luaL_checkstring(L, 2));
5930 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5931 return 0;
5932}
5933
5934__LJMP static int hlua_txn_log_info(lua_State *L)
5935{
5936 const char *msg;
5937 struct hlua_txn *htxn;
5938
5939 MAY_LJMP(check_args(L, 2, "Info"));
5940 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5941 msg = MAY_LJMP(luaL_checkstring(L, 2));
5942 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5943 return 0;
5944}
5945
5946__LJMP static int hlua_txn_log_warning(lua_State *L)
5947{
5948 const char *msg;
5949 struct hlua_txn *htxn;
5950
5951 MAY_LJMP(check_args(L, 2, "Warning"));
5952 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5953 msg = MAY_LJMP(luaL_checkstring(L, 2));
5954 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5955 return 0;
5956}
5957
5958__LJMP static int hlua_txn_log_alert(lua_State *L)
5959{
5960 const char *msg;
5961 struct hlua_txn *htxn;
5962
5963 MAY_LJMP(check_args(L, 2, "Alert"));
5964 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5965 msg = MAY_LJMP(luaL_checkstring(L, 2));
5966 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5967 return 0;
5968}
5969
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005970__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5971{
5972 struct hlua_txn *htxn;
5973 int ll;
5974
5975 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5976 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5977 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5978
5979 if (ll < 0 || ll > 7)
5980 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5981
5982 htxn->s->logs.level = ll;
5983 return 0;
5984}
5985
5986__LJMP static int hlua_txn_set_tos(lua_State *L)
5987{
5988 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005989 int tos;
5990
5991 MAY_LJMP(check_args(L, 2, "set_tos"));
5992 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5993 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5994
Willy Tarreau1a18b542018-12-11 16:37:42 +01005995 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005996 return 0;
5997}
5998
5999__LJMP static int hlua_txn_set_mark(lua_State *L)
6000{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006001 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006002 int mark;
6003
6004 MAY_LJMP(check_args(L, 2, "set_mark"));
6005 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6006 mark = MAY_LJMP(luaL_checkinteger(L, 2));
6007
Willy Tarreau1a18b542018-12-11 16:37:42 +01006008 conn_set_tos(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006009 return 0;
6010}
6011
Patrick Hemmer268a7072018-05-11 12:52:31 -04006012__LJMP static int hlua_txn_set_priority_class(lua_State *L)
6013{
6014 struct hlua_txn *htxn;
6015
6016 MAY_LJMP(check_args(L, 2, "set_priority_class"));
6017 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6018 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
6019 return 0;
6020}
6021
6022__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
6023{
6024 struct hlua_txn *htxn;
6025
6026 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
6027 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6028 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
6029 return 0;
6030}
6031
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006032/* This function is an Lua binding that send pending data
6033 * to the client, and close the stream interface.
6034 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006035__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006036{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006037 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006038 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01006039 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006040
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006041 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006042 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006043 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006044
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006045 /* If the flags NOTERM is set, we cannot terminate the http
6046 * session, so we just end the execution of the current
6047 * lua code.
6048 */
6049 if (htxn->flags & HLUA_TXN_NOTERM) {
6050 WILL_LJMP(hlua_done(L));
6051 return 0;
6052 }
6053
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006054 ic = &htxn->s->req;
6055 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01006056
Willy Tarreau630ef452015-08-28 10:06:15 +02006057 if (htxn->s->txn) {
6058 /* HTTP mode, let's stay in sync with the stream */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02006059 b_del(&ic->buf, htxn->s->txn->req.sov);
Willy Tarreau630ef452015-08-28 10:06:15 +02006060 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
6061 htxn->s->txn->req.sov = 0;
6062 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
6063 oc->analysers = AN_RES_HTTP_XFER_BODY;
6064 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
6065 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
6066
Willy Tarreau630ef452015-08-28 10:06:15 +02006067 /* Note that if we want to support keep-alive, we need
6068 * to bypass the close/shutr_now calls below, but that
6069 * may only be done if the HTTP request was already
6070 * processed and the connection header is known (ie
6071 * not during TCP rules).
6072 */
6073 }
6074
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006075 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01006076 channel_abort(ic);
6077 channel_auto_close(ic);
6078 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006079
6080 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01006081 channel_auto_read(oc);
6082 channel_auto_close(oc);
6083 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006084
Willy Tarreau0458b082015-08-28 09:40:04 +02006085 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006086
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006087 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006088 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006089 return 0;
6090}
6091
6092__LJMP static int hlua_log(lua_State *L)
6093{
6094 int level;
6095 const char *msg;
6096
6097 MAY_LJMP(check_args(L, 2, "log"));
6098 level = MAY_LJMP(luaL_checkinteger(L, 1));
6099 msg = MAY_LJMP(luaL_checkstring(L, 2));
6100
6101 if (level < 0 || level >= NB_LOG_LEVELS)
6102 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
6103
6104 hlua_sendlog(NULL, level, msg);
6105 return 0;
6106}
6107
6108__LJMP static int hlua_log_debug(lua_State *L)
6109{
6110 const char *msg;
6111
6112 MAY_LJMP(check_args(L, 1, "debug"));
6113 msg = MAY_LJMP(luaL_checkstring(L, 1));
6114 hlua_sendlog(NULL, LOG_DEBUG, msg);
6115 return 0;
6116}
6117
6118__LJMP static int hlua_log_info(lua_State *L)
6119{
6120 const char *msg;
6121
6122 MAY_LJMP(check_args(L, 1, "info"));
6123 msg = MAY_LJMP(luaL_checkstring(L, 1));
6124 hlua_sendlog(NULL, LOG_INFO, msg);
6125 return 0;
6126}
6127
6128__LJMP static int hlua_log_warning(lua_State *L)
6129{
6130 const char *msg;
6131
6132 MAY_LJMP(check_args(L, 1, "warning"));
6133 msg = MAY_LJMP(luaL_checkstring(L, 1));
6134 hlua_sendlog(NULL, LOG_WARNING, msg);
6135 return 0;
6136}
6137
6138__LJMP static int hlua_log_alert(lua_State *L)
6139{
6140 const char *msg;
6141
6142 MAY_LJMP(check_args(L, 1, "alert"));
6143 msg = MAY_LJMP(luaL_checkstring(L, 1));
6144 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006145 return 0;
6146}
6147
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006148__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006149{
6150 int wakeup_ms = lua_tointeger(L, -1);
6151 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02006152 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006153 return 0;
6154}
6155
6156__LJMP static int hlua_sleep(lua_State *L)
6157{
6158 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006159 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006160
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006161 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006162
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006163 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006164 wakeup_ms = tick_add(now_ms, delay);
6165 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006166
Willy Tarreau9635e032018-10-16 17:52:55 +02006167 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006168 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006169}
6170
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006171__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006172{
6173 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006174 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006175
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006176 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006177
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006178 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006179 wakeup_ms = tick_add(now_ms, delay);
6180 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006181
Willy Tarreau9635e032018-10-16 17:52:55 +02006182 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006183 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006184}
6185
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006186/* This functionis an LUA binding. it permits to give back
6187 * the hand at the HAProxy scheduler. It is used when the
6188 * LUA processing consumes a lot of time.
6189 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006190__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006191{
6192 return 0;
6193}
6194
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006195__LJMP static int hlua_yield(lua_State *L)
6196{
Willy Tarreau9635e032018-10-16 17:52:55 +02006197 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006198 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006199}
6200
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006201/* This function change the nice of the currently executed
6202 * task. It is used set low or high priority at the current
6203 * task.
6204 */
Willy Tarreau59551662015-03-10 14:23:13 +01006205__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006206{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006207 struct hlua *hlua;
6208 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006209
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006210 MAY_LJMP(check_args(L, 1, "set_nice"));
6211 hlua = hlua_gethlua(L);
6212 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006213
6214 /* If he task is not set, I'm in a start mode. */
6215 if (!hlua || !hlua->task)
6216 return 0;
6217
6218 if (nice < -1024)
6219 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006220 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006221 nice = 1024;
6222
6223 hlua->task->nice = nice;
6224 return 0;
6225}
6226
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006227/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006228 * HAProxy task subsystem when the task is awaked. The LUA runtime can
6229 * return an E_AGAIN signal, the emmiter of this signal must set a
6230 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006231 *
6232 * Task wrapper are longjmp safe because the only one Lua code
6233 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006234 */
Olivier Houchard9f6af332018-05-25 14:04:04 +02006235static struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006236{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006237 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006238 enum hlua_exec status;
6239
Christopher Faulet5bc99722018-04-25 10:34:45 +02006240 if (task->thread_mask == MAX_THREADS_MASK)
6241 task_set_affinity(task, tid_bit);
6242
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006243 /* If it is the first call to the task, we must initialize the
6244 * execution timeouts.
6245 */
6246 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006247 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006248
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006249 /* Execute the Lua code. */
6250 status = hlua_ctx_resume(hlua, 1);
6251
6252 switch (status) {
6253 /* finished or yield */
6254 case HLUA_E_OK:
6255 hlua_ctx_destroy(hlua);
6256 task_delete(task);
6257 task_free(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006258 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006259 break;
6260
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006261 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006262 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006263 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006264 break;
6265
6266 /* finished with error. */
6267 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006268 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006269 hlua_ctx_destroy(hlua);
6270 task_delete(task);
6271 task_free(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);
6279 task_delete(task);
6280 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006281 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006282 break;
6283 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006284 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006285}
6286
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006287/* This function is an LUA binding that register LUA function to be
6288 * executed after the HAProxy configuration parsing and before the
6289 * HAProxy scheduler starts. This function expect only one LUA
6290 * argument that is a function. This function returns nothing, but
6291 * throws if an error is encountered.
6292 */
6293__LJMP static int hlua_register_init(lua_State *L)
6294{
6295 struct hlua_init_function *init;
6296 int ref;
6297
6298 MAY_LJMP(check_args(L, 1, "register_init"));
6299
6300 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6301
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006302 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006303 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006304 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006305
6306 init->function_ref = ref;
6307 LIST_ADDQ(&hlua_init_functions, &init->l);
6308 return 0;
6309}
6310
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006311/* This functio is an LUA binding. It permits to register a task
6312 * executed in parallel of the main HAroxy activity. The task is
6313 * created and it is set in the HAProxy scheduler. It can be called
6314 * from the "init" section, "post init" or during the runtime.
6315 *
6316 * Lua prototype:
6317 *
6318 * <none> core.register_task(<function>)
6319 */
6320static int hlua_register_task(lua_State *L)
6321{
6322 struct hlua *hlua;
6323 struct task *task;
6324 int ref;
6325
6326 MAY_LJMP(check_args(L, 1, "register_task"));
6327
6328 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6329
Willy Tarreaubafbe012017-11-24 17:34:44 +01006330 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006331 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006332 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006333
Emeric Brunc60def82017-09-27 14:59:38 +02006334 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006335 if (!task)
6336 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6337
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006338 task->context = hlua;
6339 task->process = hlua_process_task;
6340
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006341 if (!hlua_ctx_init(hlua, task, 1))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006342 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006343
6344 /* Restore the function in the stack. */
6345 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6346 hlua->nargs = 0;
6347
6348 /* Schedule task. */
6349 task_schedule(task, now_ms);
6350
6351 return 0;
6352}
6353
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006354/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6355 * doesn't allow "yield" functions because the HAProxy engine cannot
6356 * resume converters.
6357 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006358static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006359{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006360 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006361 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006362 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006363
Willy Tarreaube508f12016-03-10 11:47:01 +01006364 if (!stream)
6365 return 0;
6366
Willy Tarreau87b09662015-04-03 00:22:06 +02006367 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006368 * Lua context can be not initialized. This behavior
6369 * permits to save performances because a systematic
6370 * Lua initialization cause 5% performances loss.
6371 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006372 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006373 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006374 if (!stream->hlua) {
6375 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6376 return 0;
6377 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006378 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006379 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6380 return 0;
6381 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006382 }
6383
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006384 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006385 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006386
6387 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006388 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6389 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6390 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006391 else
6392 error = "critical error";
6393 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006394 return 0;
6395 }
6396
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006397 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006398 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006399 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006400 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006401 return 0;
6402 }
6403
6404 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006405 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006406
6407 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006408 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006409 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006410 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006411 return 0;
6412 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006413 hlua_smp2lua(stream->hlua->T, smp);
6414 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006415
6416 /* push keywords in the stack. */
6417 if (arg_p) {
6418 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006419 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006420 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006421 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006422 return 0;
6423 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006424 hlua_arg2lua(stream->hlua->T, arg_p);
6425 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006426 }
6427 }
6428
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006429 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006430 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006431
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006432 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006433 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006434 }
6435
6436 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006437 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006438 /* finished. */
6439 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006440 /* If the stack is empty, the function fails. */
6441 if (lua_gettop(stream->hlua->T) <= 0)
6442 return 0;
6443
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006444 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006445 hlua_lua2smp(stream->hlua->T, -1, smp);
6446 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006447 return 1;
6448
6449 /* yield. */
6450 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006451 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006452 return 0;
6453
6454 /* finished with error. */
6455 case HLUA_E_ERRMSG:
6456 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006457 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006458 fcn->name, lua_tostring(stream->hlua->T, -1));
6459 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006460 return 0;
6461
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006462 case HLUA_E_ETMOUT:
6463 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6464 return 0;
6465
6466 case HLUA_E_NOMEM:
6467 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6468 return 0;
6469
6470 case HLUA_E_YIELD:
6471 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6472 return 0;
6473
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006474 case HLUA_E_ERR:
6475 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006476 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006477
6478 default:
6479 return 0;
6480 }
6481}
6482
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006483/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6484 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006485 * resume sample-fetches. This function will be called by the sample
6486 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006487 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006488static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6489 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006490{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006491 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006492 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006493 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006494 const struct buffer msg = { };
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
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006518 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006519 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006520
6521 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006522 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6523 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6524 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006525 else
6526 error = "critical error";
6527 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006528 return 0;
6529 }
6530
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006531 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006532 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006533 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006534 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006535 return 0;
6536 }
6537
6538 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006539 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006540
6541 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006542 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006543 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006544 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006545 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006546 return 0;
6547 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006548 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006549
6550 /* push keywords in the stack. */
6551 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6552 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006553 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006554 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006555 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006556 return 0;
6557 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006558 hlua_arg2lua(stream->hlua->T, arg_p);
6559 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006560 }
6561
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006562 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006563 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006564
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006565 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006566 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006567 }
6568
6569 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006570 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006571 /* finished. */
6572 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006573 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006574 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006575 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006576 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006577 /* If the stack is empty, the function fails. */
6578 if (lua_gettop(stream->hlua->T) <= 0)
6579 return 0;
6580
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006581 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006582 hlua_lua2smp(stream->hlua->T, -1, smp);
6583 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006584
6585 /* Set the end of execution flag. */
6586 smp->flags &= ~SMP_F_MAY_CHANGE;
6587 return 1;
6588
6589 /* yield. */
6590 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006591 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006592 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006593 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006594 return 0;
6595
6596 /* finished with error. */
6597 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006598 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006599 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006600 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006601 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006602 fcn->name, lua_tostring(stream->hlua->T, -1));
6603 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006604 return 0;
6605
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006606 case HLUA_E_ETMOUT:
6607 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006608 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006609 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6610 return 0;
6611
6612 case HLUA_E_NOMEM:
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': out of memory error.\n", fcn->name);
6616 return 0;
6617
6618 case HLUA_E_YIELD:
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': yield not allowed.\n", fcn->name);
6622 return 0;
6623
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006624 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006625 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006626 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006627 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006628 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006629
6630 default:
6631 return 0;
6632 }
6633}
6634
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006635/* This function is an LUA binding used for registering
6636 * "sample-conv" functions. It expects a converter name used
6637 * in the haproxy configuration file, and an LUA function.
6638 */
6639__LJMP static int hlua_register_converters(lua_State *L)
6640{
6641 struct sample_conv_kw_list *sck;
6642 const char *name;
6643 int ref;
6644 int len;
6645 struct hlua_function *fcn;
6646
6647 MAY_LJMP(check_args(L, 2, "register_converters"));
6648
6649 /* First argument : converter name. */
6650 name = MAY_LJMP(luaL_checkstring(L, 1));
6651
6652 /* Second argument : lua function. */
6653 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6654
6655 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006656 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006657 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006658 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006659 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006660 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006661 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006662
6663 /* Fill fcn. */
6664 fcn->name = strdup(name);
6665 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006666 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006667 fcn->function_ref = ref;
6668
6669 /* List head */
6670 sck->list.n = sck->list.p = NULL;
6671
6672 /* converter keyword. */
6673 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006674 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006675 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006676 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006677
6678 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6679 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006680 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 +01006681 sck->kw[0].val_args = NULL;
6682 sck->kw[0].in_type = SMP_T_STR;
6683 sck->kw[0].out_type = SMP_T_STR;
6684 sck->kw[0].private = fcn;
6685
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006686 /* Register this new converter */
6687 sample_register_convs(sck);
6688
6689 return 0;
6690}
6691
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006692/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006693 * "sample-fetch" functions. It expects a converter name used
6694 * in the haproxy configuration file, and an LUA function.
6695 */
6696__LJMP static int hlua_register_fetches(lua_State *L)
6697{
6698 const char *name;
6699 int ref;
6700 int len;
6701 struct sample_fetch_kw_list *sfk;
6702 struct hlua_function *fcn;
6703
6704 MAY_LJMP(check_args(L, 2, "register_fetches"));
6705
6706 /* First argument : sample-fetch name. */
6707 name = MAY_LJMP(luaL_checkstring(L, 1));
6708
6709 /* Second argument : lua function. */
6710 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6711
6712 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006713 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006714 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006715 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006716 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006717 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006718 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006719
6720 /* Fill fcn. */
6721 fcn->name = strdup(name);
6722 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006723 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006724 fcn->function_ref = ref;
6725
6726 /* List head */
6727 sfk->list.n = sfk->list.p = NULL;
6728
6729 /* sample-fetch keyword. */
6730 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006731 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006732 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006733 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006734
6735 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6736 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006737 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 +01006738 sfk->kw[0].val_args = NULL;
6739 sfk->kw[0].out_type = SMP_T_STR;
6740 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6741 sfk->kw[0].val = 0;
6742 sfk->kw[0].private = fcn;
6743
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006744 /* Register this new fetch. */
6745 sample_register_fetches(sfk);
6746
6747 return 0;
6748}
6749
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006750/* This function is a wrapper to execute each LUA function declared
6751 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006752 * return ACT_RET_CONT if the processing is finished (with or without
6753 * error) and return ACT_RET_YIELD if the function must be called again
6754 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006755 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006756static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006757 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006758{
6759 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006760 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006761 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006762 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006763 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006764
6765 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006766 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6767 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6768 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6769 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006770 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006771 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006772 return ACT_RET_CONT;
6773 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006774
Willy Tarreau87b09662015-04-03 00:22:06 +02006775 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006776 * Lua context can be not initialized. This behavior
6777 * permits to save performances because a systematic
6778 * Lua initialization cause 5% performances loss.
6779 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006780 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006781 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006782 if (!s->hlua) {
6783 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6784 rule->arg.hlua_rule->fcn.name);
6785 return ACT_RET_CONT;
6786 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006787 if (!hlua_ctx_init(s->hlua, s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006788 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6789 rule->arg.hlua_rule->fcn.name);
6790 return ACT_RET_CONT;
6791 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006792 }
6793
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006794 consistency_set(s, dir, &s->hlua->cons);
6795
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006796 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006797 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006798
6799 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006800 if (!SET_SAFE_LJMP(s->hlua->T)) {
6801 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6802 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006803 else
6804 error = "critical error";
6805 SEND_ERR(px, "Lua function '%s': %s.\n",
6806 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006807 return ACT_RET_CONT;
6808 }
6809
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006810 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006811 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006812 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006813 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006814 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006815 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006816 }
6817
6818 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006819 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006820
Willy Tarreau87b09662015-04-03 00:22:06 +02006821 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006822 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006823 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006824 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006825 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006826 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006827 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006828 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006829
6830 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006831 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006832 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006833 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006834 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006835 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006836 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006837 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006838 lua_pushstring(s->hlua->T, *arg);
6839 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006840 }
6841
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006842 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006843 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006844
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006845 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006846 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006847 }
6848
6849 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006850 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006851 /* finished. */
6852 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006853 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006854 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006855 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006856 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006857 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006858 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006859 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006860
6861 /* yield. */
6862 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006863 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006864 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006865 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006866 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006867 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006868 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006869 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006870 /* Some actions can be wake up when a "write" event
6871 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006872 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006873 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006874 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006875 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006876 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006877 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006878 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006879 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006880 s->req.flags |= CF_WAKE_WRITE;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006881 /* We can quit the function without consistency check
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006882 * because HAProxy is not able to manipulate data, it
6883 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006884 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006885
6886 /* finished with error. */
6887 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006888 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006889 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006890 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006891 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006892 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006893 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006894 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6895 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006896 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006897
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006898 case HLUA_E_ETMOUT:
6899 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006900 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006901 return ACT_RET_ERR;
6902 }
6903 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6904 return 0;
6905
6906 case HLUA_E_NOMEM:
6907 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006908 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006909 return ACT_RET_ERR;
6910 }
6911 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6912 return 0;
6913
6914 case HLUA_E_YIELD:
6915 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006916 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006917 return ACT_RET_ERR;
6918 }
6919 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6920 rule->arg.hlua_rule->fcn.name);
6921 return 0;
6922
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006923 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006924 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006925 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006926 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006927 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006928 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006929 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006930 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006931
6932 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006933 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006934 }
6935}
6936
Olivier Houchard9f6af332018-05-25 14:04:04 +02006937struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006938{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006939 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006940
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006941 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006942 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006943 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006944}
6945
6946static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6947{
6948 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006949 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006950 struct task *task;
6951 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006952 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006953
Willy Tarreaubafbe012017-11-24 17:34:44 +01006954 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006955 if (!hlua) {
6956 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6957 ctx->rule->arg.hlua_rule->fcn.name);
6958 return 0;
6959 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006960 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006961 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006962 ctx->ctx.hlua_apptcp.flags = 0;
6963
6964 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006965 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006966 if (!task) {
6967 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6968 ctx->rule->arg.hlua_rule->fcn.name);
6969 return 0;
6970 }
6971 task->nice = 0;
6972 task->context = ctx;
6973 task->process = hlua_applet_wakeup;
6974 ctx->ctx.hlua_apptcp.task = task;
6975
6976 /* In the execution wrappers linked with a stream, the
6977 * Lua context can be not initialized. This behavior
6978 * permits to save performances because a systematic
6979 * Lua initialization cause 5% performances loss.
6980 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006981 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006982 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6983 ctx->rule->arg.hlua_rule->fcn.name);
6984 return 0;
6985 }
6986
6987 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006988 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006989
6990 /* The following Lua calls can fail. */
6991 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006992 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6993 error = lua_tostring(hlua->T, -1);
6994 else
6995 error = "critical error";
6996 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6997 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006998 return 0;
6999 }
7000
7001 /* Check stack available size. */
7002 if (!lua_checkstack(hlua->T, 1)) {
7003 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7004 ctx->rule->arg.hlua_rule->fcn.name);
7005 RESET_SAFE_LJMP(hlua->T);
7006 return 0;
7007 }
7008
7009 /* Restore the function in the stack. */
7010 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7011
7012 /* Create and and push object stream in the stack. */
7013 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
7014 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7015 ctx->rule->arg.hlua_rule->fcn.name);
7016 RESET_SAFE_LJMP(hlua->T);
7017 return 0;
7018 }
7019 hlua->nargs = 1;
7020
7021 /* push keywords in the stack. */
7022 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7023 if (!lua_checkstack(hlua->T, 1)) {
7024 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7025 ctx->rule->arg.hlua_rule->fcn.name);
7026 RESET_SAFE_LJMP(hlua->T);
7027 return 0;
7028 }
7029 lua_pushstring(hlua->T, *arg);
7030 hlua->nargs++;
7031 }
7032
7033 RESET_SAFE_LJMP(hlua->T);
7034
7035 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007036 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01007037 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007038
7039 return 1;
7040}
7041
7042static void hlua_applet_tcp_fct(struct appctx *ctx)
7043{
7044 struct stream_interface *si = ctx->owner;
7045 struct stream *strm = si_strm(si);
7046 struct channel *res = si_ic(si);
7047 struct act_rule *rule = ctx->rule;
7048 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007049 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007050
7051 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02007052 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
7053 /* eat the whole request */
7054 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007055 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02007056 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007057
7058 /* If the stream is disconnect or closed, ldo nothing. */
7059 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7060 return;
7061
7062 /* Execute the function. */
7063 switch (hlua_ctx_resume(hlua, 1)) {
7064 /* finished. */
7065 case HLUA_E_OK:
7066 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7067
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007068 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007069 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007070 res->flags |= CF_READ_NULL;
7071 si_shutr(si);
7072 return;
7073
7074 /* yield. */
7075 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007076 if (hlua->wake_time != TICK_ETERNITY)
7077 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007078 return;
7079
7080 /* finished with error. */
7081 case HLUA_E_ERRMSG:
7082 /* Display log. */
7083 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7084 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7085 lua_pop(hlua->T, 1);
7086 goto error;
7087
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007088 case HLUA_E_ETMOUT:
7089 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
7090 rule->arg.hlua_rule->fcn.name);
7091 goto error;
7092
7093 case HLUA_E_NOMEM:
7094 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
7095 rule->arg.hlua_rule->fcn.name);
7096 goto error;
7097
7098 case HLUA_E_YIELD: /* unexpected */
7099 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
7100 rule->arg.hlua_rule->fcn.name);
7101 goto error;
7102
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007103 case HLUA_E_ERR:
7104 /* Display log. */
7105 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
7106 rule->arg.hlua_rule->fcn.name);
7107 goto error;
7108
7109 default:
7110 goto error;
7111 }
7112
7113error:
7114
7115 /* For all other cases, just close the stream. */
7116 si_shutw(si);
7117 si_shutr(si);
7118 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7119}
7120
7121static void hlua_applet_tcp_release(struct appctx *ctx)
7122{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02007123 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007124 task_free(ctx->ctx.hlua_apptcp.task);
7125 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007126 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007127 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007128}
7129
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007130/* The function returns 1 if the initialisation is complete, 0 if
7131 * an errors occurs and -1 if more data are required for initializing
7132 * the applet.
7133 */
7134static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7135{
7136 struct stream_interface *si = ctx->owner;
7137 struct channel *req = si_oc(si);
7138 struct http_msg *msg;
7139 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;
7146 msg = &txn->req;
7147
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007148 /* We want two things in HTTP mode :
7149 * - enforce server-close mode if we were in keep-alive, so that the
7150 * applet is released after each response ;
7151 * - enable request body transfer to the applet in order to resync
7152 * with the response body.
7153 */
7154 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
7155 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007156
Willy Tarreaubafbe012017-11-24 17:34:44 +01007157 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007158 if (!hlua) {
7159 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7160 ctx->rule->arg.hlua_rule->fcn.name);
7161 return 0;
7162 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007163 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007164 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007165 ctx->ctx.hlua_apphttp.left_bytes = -1;
7166 ctx->ctx.hlua_apphttp.flags = 0;
7167
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01007168 if (txn->req.flags & HTTP_MSGF_VER_11)
7169 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
7170
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007171 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007172 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007173 if (!task) {
7174 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7175 ctx->rule->arg.hlua_rule->fcn.name);
7176 return 0;
7177 }
7178 task->nice = 0;
7179 task->context = ctx;
7180 task->process = hlua_applet_wakeup;
7181 ctx->ctx.hlua_apphttp.task = task;
7182
7183 /* In the execution wrappers linked with a stream, the
7184 * Lua context can be not initialized. This behavior
7185 * permits to save performances because a systematic
7186 * Lua initialization cause 5% performances loss.
7187 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007188 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007189 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
7190 ctx->rule->arg.hlua_rule->fcn.name);
7191 return 0;
7192 }
7193
7194 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007195 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007196
7197 /* The following Lua calls can fail. */
7198 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007199 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7200 error = lua_tostring(hlua->T, -1);
7201 else
7202 error = "critical error";
7203 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7204 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007205 return 0;
7206 }
7207
7208 /* Check stack available size. */
7209 if (!lua_checkstack(hlua->T, 1)) {
7210 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7211 ctx->rule->arg.hlua_rule->fcn.name);
7212 RESET_SAFE_LJMP(hlua->T);
7213 return 0;
7214 }
7215
7216 /* Restore the function in the stack. */
7217 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7218
7219 /* Create and and push object stream in the stack. */
7220 if (!hlua_applet_http_new(hlua->T, ctx)) {
7221 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7222 ctx->rule->arg.hlua_rule->fcn.name);
7223 RESET_SAFE_LJMP(hlua->T);
7224 return 0;
7225 }
7226 hlua->nargs = 1;
7227
7228 /* Look for a 100-continue expected. */
7229 if (msg->flags & HTTP_MSGF_VER_11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007230 if (IS_HTX_STRM(si_strm(si))) {
7231 /* HTX version */
7232 struct htx *htx = htxbuf(&req->buf);
7233 struct ist hdr = { .ptr = "Expect", .len = 6 };
7234 struct http_hdr_ctx hdr_ctx;
7235
7236 hdr_ctx.blk = NULL;
7237 /* Expect is allowed in 1.1, look for it */
7238 if (http_find_header(htx, hdr, &hdr_ctx, 0) &&
7239 unlikely(isteqi(hdr_ctx.value, ist2("100-continue", 12))))
7240 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
7241 }
7242 else {
7243 /* Legacy HTTP version */
7244 struct hdr_ctx hdr;
7245
7246 hdr.idx = 0;
7247 if (http_find_header2("Expect", 6, ci_head(req), &txn->hdr_idx, &hdr) &&
7248 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
7249 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
7250 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007251 }
7252
7253 /* push keywords in the stack. */
7254 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7255 if (!lua_checkstack(hlua->T, 1)) {
7256 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7257 ctx->rule->arg.hlua_rule->fcn.name);
7258 RESET_SAFE_LJMP(hlua->T);
7259 return 0;
7260 }
7261 lua_pushstring(hlua->T, *arg);
7262 hlua->nargs++;
7263 }
7264
7265 RESET_SAFE_LJMP(hlua->T);
7266
7267 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007268 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007269
7270 return 1;
7271}
7272
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007273static void hlua_applet_htx_fct(struct appctx *ctx)
7274{
7275 struct stream_interface *si = ctx->owner;
7276 struct stream *strm = si_strm(si);
7277 struct channel *req = si_oc(si);
7278 struct channel *res = si_ic(si);
7279 struct act_rule *rule = ctx->rule;
7280 struct proxy *px = strm->be;
7281 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
7282 struct htx *req_htx, *res_htx;
7283
7284 res_htx = htx_from_buf(&res->buf);
7285
7286 /* If the stream is disconnect or closed, ldo nothing. */
7287 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7288 goto out;
7289
7290 /* Check if the input buffer is avalaible. */
7291 if (!b_size(&res->buf)) {
7292 si_rx_room_blk(si);
7293 goto out;
7294 }
7295 /* check that the output is not closed */
7296 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW))
7297 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7298
7299 /* Set the currently running flag. */
7300 if (!HLUA_IS_RUNNING(hlua) &&
7301 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7302 struct htx_blk *blk;
7303 size_t count = co_data(req);
7304
7305 if (!count) {
7306 si_cant_get(si);
7307 goto out;
7308 }
7309
7310 /* We need to flush the request header. This left the body for
7311 * the Lua.
7312 */
7313 req_htx = htx_from_buf(&req->buf);
7314 blk = htx_get_head_blk(req_htx);
7315 while (count && blk) {
7316 enum htx_blk_type type = htx_get_blk_type(blk);
7317 uint32_t sz = htx_get_blksz(blk);
7318
7319 if (sz > count) {
7320 si_cant_get(si);
7321 goto out;
7322 }
7323
7324 count -= sz;
7325 co_set_data(req, co_data(req) - sz);
7326 blk = htx_remove_blk(req_htx, blk);
7327
7328 if (type == HTX_BLK_EOH)
7329 break;
7330 }
7331 }
7332
7333 /* Executes The applet if it is not done. */
7334 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7335
7336 /* Execute the function. */
7337 switch (hlua_ctx_resume(hlua, 1)) {
7338 /* finished. */
7339 case HLUA_E_OK:
7340 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7341 break;
7342
7343 /* yield. */
7344 case HLUA_E_AGAIN:
7345 if (hlua->wake_time != TICK_ETERNITY)
7346 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
7347 return;
7348
7349 /* finished with error. */
7350 case HLUA_E_ERRMSG:
7351 /* Display log. */
7352 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7353 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7354 lua_pop(hlua->T, 1);
7355 goto error;
7356
7357 case HLUA_E_ETMOUT:
7358 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7359 rule->arg.hlua_rule->fcn.name);
7360 goto error;
7361
7362 case HLUA_E_NOMEM:
7363 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7364 rule->arg.hlua_rule->fcn.name);
7365 goto error;
7366
7367 case HLUA_E_YIELD: /* unexpected */
7368 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7369 rule->arg.hlua_rule->fcn.name);
7370 goto error;
7371
7372 case HLUA_E_ERR:
7373 /* Display log. */
7374 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7375 rule->arg.hlua_rule->fcn.name);
7376 goto error;
7377
7378 default:
7379 goto error;
7380 }
7381 }
7382
7383 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7384 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7385 goto error;
7386
7387 /* Don't add EOD and TLR because mux-h1 will take care of it */
7388 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
7389 si_rx_room_blk(si);
7390 goto out;
7391 }
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007392 channel_add_input(res, 1);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007393 }
7394
7395 done:
7396 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7397 /* eat the whole request */
7398 req_htx = htxbuf(&req->buf);
7399 htx_reset(req_htx);
7400 htx_to_buf(req_htx, &req->buf);
7401 co_set_data(req, 0);
7402 res->flags |= CF_READ_NULL;
7403 si_shutr(si);
7404 }
7405
7406 if ((res->flags & CF_SHUTR) && (si->state == SI_ST_EST))
7407 si_shutw(si);
7408
7409 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7410 if ((req->flags & CF_SHUTW) && (si->state == SI_ST_EST)) {
7411 si_shutr(si);
7412 res->flags |= CF_READ_NULL;
7413 }
7414 }
7415
7416 out:
7417 /* we have left the request in the buffer for the case where we
7418 * process a POST, and this automatically re-enables activity on
7419 * read. It's better to indicate that we want to stop reading when
7420 * we're sending, so that we know there's at most one direction
7421 * deciding to wake the applet up. It saves it from looping when
7422 * emitting large blocks into small TCP windows.
7423 */
7424 htx_to_buf(res_htx, &res->buf);
7425 if (!channel_is_empty(res))
7426 si_stop_get(si);
7427 return;
7428
7429 error:
7430
7431 /* If we are in HTTP mode, and we are not send any
7432 * data, return a 500 server error in best effort:
7433 * if there is no room available in the buffer,
7434 * just close the connection.
7435 */
7436 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7437 struct buffer *err = &htx_err_chunks[HTTP_ERR_500];
7438
7439 channel_erase(res);
7440 res->buf.data = b_data(err);
7441 memcpy(res->buf.area, b_head(err), b_data(err));
7442 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007443 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007444 }
7445 if (!(strm->flags & SF_ERR_MASK))
7446 strm->flags |= SF_ERR_RESOURCE;
7447 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7448 goto done;
7449}
7450
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007451static void hlua_applet_http_fct(struct appctx *ctx)
7452{
7453 struct stream_interface *si = ctx->owner;
7454 struct stream *strm = si_strm(si);
7455 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007456 struct act_rule *rule = ctx->rule;
7457 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007458 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02007459 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007460 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02007461 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007462 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007463 int ret;
7464
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007465 if (IS_HTX_STRM(strm))
7466 return hlua_applet_htx_fct(ctx);
7467
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007468 /* If the stream is disconnect or closed, ldo nothing. */
7469 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7470 return;
7471
7472 /* Set the currently running flag. */
7473 if (!HLUA_IS_RUNNING(hlua) &&
7474 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007475 /* Store the max amount of bytes that we can read. */
7476 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
7477
7478 /* We need to flush the request header. This left the body
7479 * for the Lua.
7480 */
7481
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007482 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007483 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007484 if (ret == -1)
7485 return;
7486
7487 /* No data available, ask for more data. */
7488 if (ret == 1)
7489 len2 = 0;
7490 if (ret == 0)
7491 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02007492 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007493 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007494 return;
7495 }
7496
7497 /* skip the requests bytes. */
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02007498 co_skip(si_oc(si), strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007499 }
7500
7501 /* Executes The applet if it is not done. */
7502 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7503
7504 /* Execute the function. */
7505 switch (hlua_ctx_resume(hlua, 1)) {
7506 /* finished. */
7507 case HLUA_E_OK:
7508 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7509 break;
7510
7511 /* yield. */
7512 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007513 if (hlua->wake_time != TICK_ETERNITY)
7514 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007515 return;
7516
7517 /* finished with error. */
7518 case HLUA_E_ERRMSG:
7519 /* Display log. */
7520 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7521 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7522 lua_pop(hlua->T, 1);
7523 goto error;
7524
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007525 case HLUA_E_ETMOUT:
7526 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7527 rule->arg.hlua_rule->fcn.name);
7528 goto error;
7529
7530 case HLUA_E_NOMEM:
7531 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7532 rule->arg.hlua_rule->fcn.name);
7533 goto error;
7534
7535 case HLUA_E_YIELD: /* unexpected */
7536 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7537 rule->arg.hlua_rule->fcn.name);
7538 goto error;
7539
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007540 case HLUA_E_ERR:
7541 /* Display log. */
7542 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7543 rule->arg.hlua_rule->fcn.name);
7544 goto error;
7545
7546 default:
7547 goto error;
7548 }
7549 }
7550
7551 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Fauletcc26b132018-12-18 21:20:57 +01007552 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7553 goto error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007554
7555 /* We must send the final chunk. */
7556 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
7557 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
7558
7559 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007560 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007561
7562 /* critical error. */
7563 if (ret == -2 || ret == -3) {
7564 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
7565 rule->arg.hlua_rule->fcn.name);
7566 goto error;
7567 }
7568
7569 /* no enough space error. */
7570 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01007571 si_rx_room_blk(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007572 return;
7573 }
7574
7575 /* set the last chunk sent. */
7576 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
7577 }
7578
7579 /* close the connection. */
7580
Frédéric Lécaille83ed5d52018-07-18 14:25:26 +02007581 /* status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007582 strm->txn->status = ctx->ctx.hlua_apphttp.status;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007583
7584 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007585 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007586 res->flags |= CF_READ_NULL;
7587 si_shutr(si);
7588
7589 return;
7590 }
7591
7592error:
7593
7594 /* If we are in HTTP mode, and we are not send any
7595 * data, return a 500 server error in best effort:
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007596 * if there is no room available in the buffer,
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007597 * just close the connection.
7598 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007599 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007600 if (!(strm->flags & SF_ERR_MASK))
7601 strm->flags |= SF_ERR_RESOURCE;
7602 si_shutw(si);
7603 si_shutr(si);
7604 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7605}
7606
7607static void hlua_applet_http_release(struct appctx *ctx)
7608{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02007609 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007610 task_free(ctx->ctx.hlua_apphttp.task);
7611 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007612 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007613 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007614}
7615
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007616/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
7617 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007618 *
7619 * This function can fail with an abort() due to an Lua critical error.
7620 * We are in the configuration parsing process of HAProxy, this abort() is
7621 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007622 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007623static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7624 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007625{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007626 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007627 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007628
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007629 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007630 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007631 if (!rule->arg.hlua_rule) {
7632 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007633 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007634 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007635
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007636 /* Memory for arguments. */
7637 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
7638 if (!rule->arg.hlua_rule->args) {
7639 memprintf(err, "out of memory error");
7640 return ACT_RET_PRS_ERR;
7641 }
7642
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007643 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007644 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007645
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007646 /* Expect some arguments */
7647 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007648 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007649 memprintf(err, "expect %d arguments", fcn->nargs);
7650 return ACT_RET_PRS_ERR;
7651 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007652 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007653 if (!rule->arg.hlua_rule->args[i]) {
7654 memprintf(err, "out of memory error");
7655 return ACT_RET_PRS_ERR;
7656 }
7657 (*cur_arg)++;
7658 }
7659 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007660
Thierry FOURNIER42148732015-09-02 17:17:33 +02007661 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007662 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007663 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007664}
7665
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007666static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7667 struct act_rule *rule, char **err)
7668{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007669 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007670
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007671 /* HTTP applets are forbidden in tcp-request rules.
7672 * HTTP applet request requires everything initilized by
7673 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
7674 * The applet will be immediately initilized, but its before
7675 * the call of this analyzer.
7676 */
7677 if (rule->from != ACT_F_HTTP_REQ) {
7678 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7679 return ACT_RET_PRS_ERR;
7680 }
7681
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007682 /* Memory for the rule. */
7683 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7684 if (!rule->arg.hlua_rule) {
7685 memprintf(err, "out of memory error");
7686 return ACT_RET_PRS_ERR;
7687 }
7688
7689 /* Reference the Lua function and store the reference. */
7690 rule->arg.hlua_rule->fcn = *fcn;
7691
7692 /* TODO: later accept arguments. */
7693 rule->arg.hlua_rule->args = NULL;
7694
7695 /* Add applet pointer in the rule. */
7696 rule->applet.obj_type = OBJ_TYPE_APPLET;
7697 rule->applet.name = fcn->name;
7698 rule->applet.init = hlua_applet_http_init;
7699 rule->applet.fct = hlua_applet_http_fct;
7700 rule->applet.release = hlua_applet_http_release;
7701 rule->applet.timeout = hlua_timeout_applet;
7702
7703 return ACT_RET_PRS_OK;
7704}
7705
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007706/* This function is an LUA binding used for registering
7707 * "sample-conv" functions. It expects a converter name used
7708 * in the haproxy configuration file, and an LUA function.
7709 */
7710__LJMP static int hlua_register_action(lua_State *L)
7711{
7712 struct action_kw_list *akl;
7713 const char *name;
7714 int ref;
7715 int len;
7716 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007717 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007718
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007719 /* Initialise the number of expected arguments at 0. */
7720 nargs = 0;
7721
7722 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7723 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007724
7725 /* First argument : converter name. */
7726 name = MAY_LJMP(luaL_checkstring(L, 1));
7727
7728 /* Second argument : environment. */
7729 if (lua_type(L, 2) != LUA_TTABLE)
7730 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7731
7732 /* Third argument : lua function. */
7733 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7734
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007735 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007736 if (lua_gettop(L) >= 4)
7737 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7738
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007739 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007740 lua_pushnil(L);
7741 while (lua_next(L, 2) != 0) {
7742 if (lua_type(L, -1) != LUA_TSTRING)
7743 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7744
7745 /* Check required environment. Only accepted "http" or "tcp". */
7746 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007747 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007748 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007749 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007750 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007751 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007752 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007753
7754 /* Fill fcn. */
7755 fcn->name = strdup(name);
7756 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007757 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007758 fcn->function_ref = ref;
7759
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007760 /* Set the expected number od arguments. */
7761 fcn->nargs = nargs;
7762
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007763 /* List head */
7764 akl->list.n = akl->list.p = NULL;
7765
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007766 /* action keyword. */
7767 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007768 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007769 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007770 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007771
7772 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7773
7774 akl->kw[0].match_pfx = 0;
7775 akl->kw[0].private = fcn;
7776 akl->kw[0].parse = action_register_lua;
7777
7778 /* select the action registering point. */
7779 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7780 tcp_req_cont_keywords_register(akl);
7781 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7782 tcp_res_cont_keywords_register(akl);
7783 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7784 http_req_keywords_register(akl);
7785 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7786 http_res_keywords_register(akl);
7787 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007788 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007789 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7790 "are expected.", lua_tostring(L, -1)));
7791
7792 /* pop the environment string. */
7793 lua_pop(L, 1);
7794 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007795 return ACT_RET_PRS_OK;
7796}
7797
7798static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7799 struct act_rule *rule, char **err)
7800{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007801 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007802
Christopher Fauletafd8f102018-11-08 11:34:21 +01007803 if (px->options2 & PR_O2_USE_HTX) {
7804 memprintf(err, "Lua services cannot be used when the HTX internal representation is enabled");
7805 return ACT_RET_PRS_ERR;
7806 }
7807
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007808 /* Memory for the rule. */
7809 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7810 if (!rule->arg.hlua_rule) {
7811 memprintf(err, "out of memory error");
7812 return ACT_RET_PRS_ERR;
7813 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007814
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007815 /* Reference the Lua function and store the reference. */
7816 rule->arg.hlua_rule->fcn = *fcn;
7817
7818 /* TODO: later accept arguments. */
7819 rule->arg.hlua_rule->args = NULL;
7820
7821 /* Add applet pointer in the rule. */
7822 rule->applet.obj_type = OBJ_TYPE_APPLET;
7823 rule->applet.name = fcn->name;
7824 rule->applet.init = hlua_applet_tcp_init;
7825 rule->applet.fct = hlua_applet_tcp_fct;
7826 rule->applet.release = hlua_applet_tcp_release;
7827 rule->applet.timeout = hlua_timeout_applet;
7828
7829 return 0;
7830}
7831
7832/* This function is an LUA binding used for registering
7833 * "sample-conv" functions. It expects a converter name used
7834 * in the haproxy configuration file, and an LUA function.
7835 */
7836__LJMP static int hlua_register_service(lua_State *L)
7837{
7838 struct action_kw_list *akl;
7839 const char *name;
7840 const char *env;
7841 int ref;
7842 int len;
7843 struct hlua_function *fcn;
7844
7845 MAY_LJMP(check_args(L, 3, "register_service"));
7846
7847 /* First argument : converter name. */
7848 name = MAY_LJMP(luaL_checkstring(L, 1));
7849
7850 /* Second argument : environment. */
7851 env = MAY_LJMP(luaL_checkstring(L, 2));
7852
7853 /* Third argument : lua function. */
7854 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7855
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007856 /* Allocate and fill the sample fetch keyword struct. */
7857 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7858 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007859 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007860 fcn = calloc(1, sizeof(*fcn));
7861 if (!fcn)
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 /* Fill fcn. */
7865 len = strlen("<lua.>") + strlen(name) + 1;
7866 fcn->name = calloc(1, len);
7867 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007868 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007869 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7870 fcn->function_ref = ref;
7871
7872 /* List head */
7873 akl->list.n = akl->list.p = NULL;
7874
7875 /* converter keyword. */
7876 len = strlen("lua.") + strlen(name) + 1;
7877 akl->kw[0].kw = calloc(1, len);
7878 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007879 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007880
7881 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7882
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007883 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007884 if (strcmp(env, "tcp") == 0)
7885 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007886 else if (strcmp(env, "http") == 0)
7887 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007888 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007889 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007890 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007891
7892 akl->kw[0].match_pfx = 0;
7893 akl->kw[0].private = fcn;
7894
7895 /* End of array. */
7896 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7897
7898 /* Register this new converter */
7899 service_keywords_register(akl);
7900
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007901 return 0;
7902}
7903
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007904/* This function initialises Lua cli handler. It copies the
7905 * arguments in the Lua stack and create channel IO objects.
7906 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007907static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007908{
7909 struct hlua *hlua;
7910 struct hlua_function *fcn;
7911 int i;
7912 const char *error;
7913
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007914 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007915 appctx->ctx.hlua_cli.fcn = private;
7916
Willy Tarreaubafbe012017-11-24 17:34:44 +01007917 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007918 if (!hlua) {
7919 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007920 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007921 }
7922 HLUA_INIT(hlua);
7923 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007924
7925 /* Create task used by signal to wakeup applets.
7926 * We use the same wakeup fonction than the Lua applet_tcp and
7927 * applet_http. It is absolutely compatible.
7928 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007929 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007930 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007931 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007932 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007933 }
7934 appctx->ctx.hlua_cli.task->nice = 0;
7935 appctx->ctx.hlua_cli.task->context = appctx;
7936 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7937
7938 /* Initialises the Lua context */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007939 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007940 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007941 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007942 }
7943
7944 /* The following Lua calls can fail. */
7945 if (!SET_SAFE_LJMP(hlua->T)) {
7946 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7947 error = lua_tostring(hlua->T, -1);
7948 else
7949 error = "critical error";
7950 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7951 goto error;
7952 }
7953
7954 /* Check stack available size. */
7955 if (!lua_checkstack(hlua->T, 2)) {
7956 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7957 goto error;
7958 }
7959
7960 /* Restore the function in the stack. */
7961 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7962
7963 /* Once the arguments parsed, the CLI is like an AppletTCP,
7964 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007965 */
7966 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7967 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7968 goto error;
7969 }
7970 hlua->nargs = 1;
7971
7972 /* push keywords in the stack. */
7973 for (i = 0; *args[i]; i++) {
7974 /* Check stack available size. */
7975 if (!lua_checkstack(hlua->T, 1)) {
7976 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7977 goto error;
7978 }
7979 lua_pushstring(hlua->T, args[i]);
7980 hlua->nargs++;
7981 }
7982
7983 /* We must initialize the execution timeouts. */
7984 hlua->max_time = hlua_timeout_session;
7985
7986 /* At this point the execution is safe. */
7987 RESET_SAFE_LJMP(hlua->T);
7988
7989 /* It's ok */
7990 return 0;
7991
7992 /* It's not ok. */
7993error:
7994 RESET_SAFE_LJMP(hlua->T);
7995 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007996 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007997 return 1;
7998}
7999
8000static int hlua_cli_io_handler_fct(struct appctx *appctx)
8001{
8002 struct hlua *hlua;
8003 struct stream_interface *si;
8004 struct hlua_function *fcn;
8005
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008006 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008007 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01008008 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008009
8010 /* If the stream is disconnect or closed, ldo nothing. */
8011 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8012 return 1;
8013
8014 /* Execute the function. */
8015 switch (hlua_ctx_resume(hlua, 1)) {
8016
8017 /* finished. */
8018 case HLUA_E_OK:
8019 return 1;
8020
8021 /* yield. */
8022 case HLUA_E_AGAIN:
8023 /* We want write. */
8024 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01008025 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008026 /* Set the timeout. */
8027 if (hlua->wake_time != TICK_ETERNITY)
8028 task_schedule(hlua->task, hlua->wake_time);
8029 return 0;
8030
8031 /* finished with error. */
8032 case HLUA_E_ERRMSG:
8033 /* Display log. */
8034 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
8035 fcn->name, lua_tostring(hlua->T, -1));
8036 lua_pop(hlua->T, 1);
8037 return 1;
8038
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008039 case HLUA_E_ETMOUT:
8040 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
8041 fcn->name);
8042 return 1;
8043
8044 case HLUA_E_NOMEM:
8045 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
8046 fcn->name);
8047 return 1;
8048
8049 case HLUA_E_YIELD: /* unexpected */
8050 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
8051 fcn->name);
8052 return 1;
8053
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008054 case HLUA_E_ERR:
8055 /* Display log. */
8056 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
8057 fcn->name);
8058 return 1;
8059
8060 default:
8061 return 1;
8062 }
8063
8064 return 1;
8065}
8066
8067static void hlua_cli_io_release_fct(struct appctx *appctx)
8068{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008069 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008070 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008071}
8072
8073/* This function is an LUA binding used for registering
8074 * new keywords in the cli. It expects a list of keywords
8075 * which are the "path". It is limited to 5 keywords. A
8076 * description of the command, a function to be executed
8077 * for the parsing and a function for io handlers.
8078 */
8079__LJMP static int hlua_register_cli(lua_State *L)
8080{
8081 struct cli_kw_list *cli_kws;
8082 const char *message;
8083 int ref_io;
8084 int len;
8085 struct hlua_function *fcn;
8086 int index;
8087 int i;
8088
8089 MAY_LJMP(check_args(L, 3, "register_cli"));
8090
8091 /* First argument : an array of maximum 5 keywords. */
8092 if (!lua_istable(L, 1))
8093 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
8094
8095 /* Second argument : string with contextual message. */
8096 message = MAY_LJMP(luaL_checkstring(L, 2));
8097
8098 /* Third and fourth argument : lua function. */
8099 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
8100
8101 /* Allocate and fill the sample fetch keyword struct. */
8102 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
8103 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008104 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008105 fcn = calloc(1, sizeof(*fcn));
8106 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008107 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008108
8109 /* Fill path. */
8110 index = 0;
8111 lua_pushnil(L);
8112 while(lua_next(L, 1) != 0) {
8113 if (index >= 5)
8114 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8115 if (lua_type(L, -1) != LUA_TSTRING)
8116 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8117 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
8118 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008119 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008120 index++;
8121 lua_pop(L, 1);
8122 }
8123
8124 /* Copy help message. */
8125 cli_kws->kw[0].usage = strdup(message);
8126 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008127 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008128
8129 /* Fill fcn io handler. */
8130 len = strlen("<lua.cli>") + 1;
8131 for (i = 0; i < index; i++)
8132 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
8133 fcn->name = calloc(1, len);
8134 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008135 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008136 strncat((char *)fcn->name, "<lua.cli", len);
8137 for (i = 0; i < index; i++) {
8138 strncat((char *)fcn->name, ".", len);
8139 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
8140 }
8141 strncat((char *)fcn->name, ">", len);
8142 fcn->function_ref = ref_io;
8143
8144 /* Fill last entries. */
8145 cli_kws->kw[0].private = fcn;
8146 cli_kws->kw[0].parse = hlua_cli_parse_fct;
8147 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
8148 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
8149
8150 /* Register this new converter */
8151 cli_register_kw(cli_kws);
8152
8153 return 0;
8154}
8155
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008156static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
8157 struct proxy *defpx, const char *file, int line,
8158 char **err, unsigned int *timeout)
8159{
8160 const char *error;
8161
8162 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
8163 if (error && *error != '\0') {
8164 memprintf(err, "%s: invalid timeout", args[0]);
8165 return -1;
8166 }
8167 return 0;
8168}
8169
8170static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
8171 struct proxy *defpx, const char *file, int line,
8172 char **err)
8173{
8174 return hlua_read_timeout(args, section_type, curpx, defpx,
8175 file, line, err, &hlua_timeout_session);
8176}
8177
8178static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
8179 struct proxy *defpx, const char *file, int line,
8180 char **err)
8181{
8182 return hlua_read_timeout(args, section_type, curpx, defpx,
8183 file, line, err, &hlua_timeout_task);
8184}
8185
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008186static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
8187 struct proxy *defpx, const char *file, int line,
8188 char **err)
8189{
8190 return hlua_read_timeout(args, section_type, curpx, defpx,
8191 file, line, err, &hlua_timeout_applet);
8192}
8193
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008194static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
8195 struct proxy *defpx, const char *file, int line,
8196 char **err)
8197{
8198 char *error;
8199
8200 hlua_nb_instruction = strtoll(args[1], &error, 10);
8201 if (*error != '\0') {
8202 memprintf(err, "%s: invalid number", args[0]);
8203 return -1;
8204 }
8205 return 0;
8206}
8207
Willy Tarreau32f61e22015-03-18 17:54:59 +01008208static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
8209 struct proxy *defpx, const char *file, int line,
8210 char **err)
8211{
8212 char *error;
8213
8214 if (*(args[1]) == 0) {
8215 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
8216 return -1;
8217 }
8218 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
8219 if (*error != '\0') {
8220 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
8221 return -1;
8222 }
8223 return 0;
8224}
8225
8226
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008227/* This function is called by the main configuration key "lua-load". It loads and
8228 * execute an lua file during the parsing of the HAProxy configuration file. It is
8229 * the main lua entry point.
8230 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008231 * This function runs with the HAProxy keywords API. It returns -1 if an error
8232 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008233 *
8234 * In some error case, LUA set an error message in top of the stack. This function
8235 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008236 *
8237 * This function can fail with an abort() due to an Lua critical error.
8238 * We are in the configuration parsing process of HAProxy, this abort() is
8239 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008240 */
8241static int hlua_load(char **args, int section_type, struct proxy *curpx,
8242 struct proxy *defpx, const char *file, int line,
8243 char **err)
8244{
8245 int error;
8246
8247 /* Just load and compile the file. */
8248 error = luaL_loadfile(gL.T, args[1]);
8249 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008250 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008251 lua_pop(gL.T, 1);
8252 return -1;
8253 }
8254
8255 /* If no syntax error where detected, execute the code. */
8256 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
8257 switch (error) {
8258 case LUA_OK:
8259 break;
8260 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008261 memprintf(err, "Lua runtime 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_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008265 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008266 return -1;
8267 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008268 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008269 lua_pop(gL.T, 1);
8270 return -1;
8271 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008272 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008273 lua_pop(gL.T, 1);
8274 return -1;
8275 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008276 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008277 lua_pop(gL.T, 1);
8278 return -1;
8279 }
8280
8281 return 0;
8282}
8283
8284/* configuration keywords declaration */
8285static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008286 { CFG_GLOBAL, "lua-load", hlua_load },
8287 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
8288 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02008289 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008290 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01008291 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008292 { 0, NULL, NULL },
8293}};
8294
Willy Tarreau0108d902018-11-25 19:14:37 +01008295INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
8296
Christopher Fauletafd8f102018-11-08 11:34:21 +01008297
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008298/* This function can fail with an abort() due to an Lua critical error.
8299 * We are in the initialisation process of HAProxy, this abort() is
8300 * tolerated.
8301 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008302int hlua_post_init()
8303{
8304 struct hlua_init_function *init;
8305 const char *msg;
8306 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008307 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008308
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008309 /* Call post initialisation function in safe environement. */
8310 if (!SET_SAFE_LJMP(gL.T)) {
8311 if (lua_type(gL.T, -1) == LUA_TSTRING)
8312 error = lua_tostring(gL.T, -1);
8313 else
8314 error = "critical error";
8315 fprintf(stderr, "Lua post-init: %s.\n", error);
8316 exit(1);
8317 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02008318
8319#if USE_OPENSSL
8320 /* Initialize SSL server. */
8321 if (socket_ssl.xprt->prepare_srv) {
8322 int saved_used_backed = global.ssl_used_backend;
8323 // don't affect maxconn automatic computation
8324 socket_ssl.xprt->prepare_srv(&socket_ssl);
8325 global.ssl_used_backend = saved_used_backed;
8326 }
8327#endif
8328
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008329 hlua_fcn_post_init(gL.T);
8330 RESET_SAFE_LJMP(gL.T);
8331
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008332 list_for_each_entry(init, &hlua_init_functions, l) {
8333 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
8334 ret = hlua_ctx_resume(&gL, 0);
8335 switch (ret) {
8336 case HLUA_E_OK:
8337 lua_pop(gL.T, -1);
8338 return 1;
8339 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008340 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008341 return 0;
8342 case HLUA_E_ERRMSG:
8343 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01008344 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008345 return 0;
8346 case HLUA_E_ERR:
8347 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008348 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008349 return 0;
8350 }
8351 }
8352 return 1;
8353}
8354
Willy Tarreau32f61e22015-03-18 17:54:59 +01008355/* The memory allocator used by the Lua stack. <ud> is a pointer to the
8356 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
8357 * is the previously allocated size or the kind of object in case of a new
8358 * allocation. <nsize> is the requested new size.
8359 */
8360static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
8361{
8362 struct hlua_mem_allocator *zone = ud;
8363
8364 if (nsize == 0) {
8365 /* it's a free */
8366 if (ptr)
8367 zone->allocated -= osize;
8368 free(ptr);
8369 return NULL;
8370 }
8371
8372 if (!ptr) {
8373 /* it's a new allocation */
8374 if (zone->limit && zone->allocated + nsize > zone->limit)
8375 return NULL;
8376
8377 ptr = malloc(nsize);
8378 if (ptr)
8379 zone->allocated += nsize;
8380 return ptr;
8381 }
8382
8383 /* it's a realloc */
8384 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
8385 return NULL;
8386
8387 ptr = realloc(ptr, nsize);
8388 if (ptr)
8389 zone->allocated += nsize - osize;
8390 return ptr;
8391}
8392
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008393/* Ithis function can fail with an abort() due to an Lua critical error.
8394 * We are in the initialisation process of HAProxy, this abort() is
8395 * tolerated.
8396 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008397void hlua_init(void)
8398{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008399 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008400 int idx;
8401 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008402 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008403 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008404 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008405#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008406 struct srv_kw *kw;
8407 int tmp_error;
8408 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008409 char *args[] = { /* SSL client configuration. */
8410 "ssl",
8411 "verify",
8412 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008413 NULL
8414 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008415#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008416
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008417 /* Init main lua stack. */
8418 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01008419 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01008420 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02008421 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008422 hlua_sethlua(&gL);
8423 gL.Tref = LUA_REFNIL;
8424 gL.task = NULL;
8425
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008426 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008427 * the Lua function can fail with an abort. We are in the initialisation
8428 * process of HAProxy, this abort() is tolerated.
8429 */
8430
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008431 /* Initialise lua. */
8432 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008433
Thierry Fournier75933d42016-01-21 09:30:18 +01008434 /* Set safe environment for the initialisation. */
8435 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008436 if (lua_type(gL.T, -1) == LUA_TSTRING)
8437 error_msg = lua_tostring(gL.T, -1);
8438 else
8439 error_msg = "critical error";
8440 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01008441 exit(1);
8442 }
8443
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008444 /*
8445 *
8446 * Create "core" object.
8447 *
8448 */
8449
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008450 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008451 lua_newtable(gL.T);
8452
8453 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008454 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008455 hlua_class_const_int(gL.T, log_levels[i], i);
8456
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008457 /* Register special functions. */
8458 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008459 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008460 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008461 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008462 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008463 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008464 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008465 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01008466 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008467 hlua_class_function(gL.T, "sleep", hlua_sleep);
8468 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01008469 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
8470 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
8471 hlua_class_function(gL.T, "set_map", hlua_set_map);
8472 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008473 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008474 hlua_class_function(gL.T, "log", hlua_log);
8475 hlua_class_function(gL.T, "Debug", hlua_log_debug);
8476 hlua_class_function(gL.T, "Info", hlua_log_info);
8477 hlua_class_function(gL.T, "Warning", hlua_log_warning);
8478 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02008479 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01008480 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008481
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008482 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008483
8484 /*
8485 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008486 * Register class Map
8487 *
8488 */
8489
8490 /* This table entry is the object "Map" base. */
8491 lua_newtable(gL.T);
8492
8493 /* register pattern types. */
8494 for (i=0; i<PAT_MATCH_NUM; i++)
8495 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008496 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008497 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
8498 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008499 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008500
8501 /* register constructor. */
8502 hlua_class_function(gL.T, "new", hlua_map_new);
8503
8504 /* Create and fill the metatable. */
8505 lua_newtable(gL.T);
8506
8507 /* Create and fille the __index entry. */
8508 lua_pushstring(gL.T, "__index");
8509 lua_newtable(gL.T);
8510
8511 /* Register . */
8512 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
8513 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
8514
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008515 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008516
Thierry Fournier45e78d72016-02-19 18:34:46 +01008517 /* Register previous table in the registry with reference and named entry.
8518 * The function hlua_register_metatable() pops the stack, so we
8519 * previously create a copy of the table.
8520 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008521 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008522 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008523
8524 /* Assign the metatable to the mai Map object. */
8525 lua_setmetatable(gL.T, -2);
8526
8527 /* Set a name to the table. */
8528 lua_setglobal(gL.T, "Map");
8529
8530 /*
8531 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008532 * Register class Channel
8533 *
8534 */
8535
8536 /* Create and fill the metatable. */
8537 lua_newtable(gL.T);
8538
8539 /* Create and fille the __index entry. */
8540 lua_pushstring(gL.T, "__index");
8541 lua_newtable(gL.T);
8542
8543 /* Register . */
8544 hlua_class_function(gL.T, "get", hlua_channel_get);
8545 hlua_class_function(gL.T, "dup", hlua_channel_dup);
8546 hlua_class_function(gL.T, "getline", hlua_channel_getline);
8547 hlua_class_function(gL.T, "set", hlua_channel_set);
8548 hlua_class_function(gL.T, "append", hlua_channel_append);
8549 hlua_class_function(gL.T, "send", hlua_channel_send);
8550 hlua_class_function(gL.T, "forward", hlua_channel_forward);
8551 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
8552 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01008553 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008554
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008555 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008556
8557 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008558 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008559
8560 /*
8561 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008562 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008563 *
8564 */
8565
8566 /* Create and fill the metatable. */
8567 lua_newtable(gL.T);
8568
8569 /* Create and fille the __index entry. */
8570 lua_pushstring(gL.T, "__index");
8571 lua_newtable(gL.T);
8572
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008573 /* Browse existing fetches and create the associated
8574 * object method.
8575 */
8576 sf = NULL;
8577 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
8578
8579 /* Dont register the keywork if the arguments check function are
8580 * not safe during the runtime.
8581 */
8582 if ((sf->val_args != NULL) &&
8583 (sf->val_args != val_payload_lv) &&
8584 (sf->val_args != val_hdr))
8585 continue;
8586
8587 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8588 * by an underscore.
8589 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008590 strncpy(trash.area, sf->kw, trash.size);
8591 trash.area[trash.size - 1] = '\0';
8592 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008593 if (*p == '.' || *p == '-' || *p == '+')
8594 *p = '_';
8595
8596 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008597 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01008598 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008599 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008600 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008601 }
8602
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008603 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008604
8605 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008606 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008607
8608 /*
8609 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008610 * Register class Converters
8611 *
8612 */
8613
8614 /* Create and fill the metatable. */
8615 lua_newtable(gL.T);
8616
8617 /* Create and fill the __index entry. */
8618 lua_pushstring(gL.T, "__index");
8619 lua_newtable(gL.T);
8620
8621 /* Browse existing converters and create the associated
8622 * object method.
8623 */
8624 sc = NULL;
8625 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
8626 /* Dont register the keywork if the arguments check function are
8627 * not safe during the runtime.
8628 */
8629 if (sc->val_args != NULL)
8630 continue;
8631
8632 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8633 * by an underscore.
8634 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008635 strncpy(trash.area, sc->kw, trash.size);
8636 trash.area[trash.size - 1] = '\0';
8637 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008638 if (*p == '.' || *p == '-' || *p == '+')
8639 *p = '_';
8640
8641 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008642 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008643 lua_pushlightuserdata(gL.T, sc);
8644 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008645 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008646 }
8647
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008648 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008649
8650 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008651 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008652
8653 /*
8654 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008655 * Register class HTTP
8656 *
8657 */
8658
8659 /* Create and fill the metatable. */
8660 lua_newtable(gL.T);
8661
8662 /* Create and fille the __index entry. */
8663 lua_pushstring(gL.T, "__index");
8664 lua_newtable(gL.T);
8665
8666 /* Register Lua functions. */
8667 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
8668 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
8669 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
8670 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
8671 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
8672 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
8673 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
8674 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
8675 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
8676 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
8677
8678 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
8679 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
8680 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
8681 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
8682 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
8683 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02008684 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008685
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008686 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008687
8688 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008689 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008690
8691 /*
8692 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008693 * Register class AppletTCP
8694 *
8695 */
8696
8697 /* Create and fill the metatable. */
8698 lua_newtable(gL.T);
8699
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008700 /* Create and fille the __index entry. */
8701 lua_pushstring(gL.T, "__index");
8702 lua_newtable(gL.T);
8703
8704 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01008705 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
8706 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
8707 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
8708 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
8709 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008710 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
8711 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
8712 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008713
8714 lua_settable(gL.T, -3);
8715
8716 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008717 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008718
8719 /*
8720 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008721 * Register class AppletHTTP
8722 *
8723 */
8724
8725 /* Create and fill the metatable. */
8726 lua_newtable(gL.T);
8727
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008728 /* Create and fille the __index entry. */
8729 lua_pushstring(gL.T, "__index");
8730 lua_newtable(gL.T);
8731
8732 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01008733 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
8734 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008735 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
8736 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
8737 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008738 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
8739 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
8740 hlua_class_function(gL.T, "send", hlua_applet_http_send);
8741 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
8742 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
8743 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
8744
8745 lua_settable(gL.T, -3);
8746
8747 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008748 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008749
8750 /*
8751 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008752 * Register class TXN
8753 *
8754 */
8755
8756 /* Create and fill the metatable. */
8757 lua_newtable(gL.T);
8758
8759 /* Create and fille the __index entry. */
8760 lua_pushstring(gL.T, "__index");
8761 lua_newtable(gL.T);
8762
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008763 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04008764 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
8765 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
8766 hlua_class_function(gL.T, "set_var", hlua_set_var);
8767 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
8768 hlua_class_function(gL.T, "get_var", hlua_get_var);
8769 hlua_class_function(gL.T, "done", hlua_txn_done);
8770 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
8771 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
8772 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
8773 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
8774 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
8775 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
8776 hlua_class_function(gL.T, "log", hlua_txn_log);
8777 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
8778 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
8779 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
8780 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008781
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008782 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008783
8784 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008785 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008786
8787 /*
8788 *
8789 * Register class Socket
8790 *
8791 */
8792
8793 /* Create and fill the metatable. */
8794 lua_newtable(gL.T);
8795
8796 /* Create and fille the __index entry. */
8797 lua_pushstring(gL.T, "__index");
8798 lua_newtable(gL.T);
8799
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008800#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008801 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008802#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008803 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8804 hlua_class_function(gL.T, "send", hlua_socket_send);
8805 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8806 hlua_class_function(gL.T, "close", hlua_socket_close);
8807 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8808 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8809 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8810 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8811
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008812 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008813
8814 /* Register the garbage collector entry. */
8815 lua_pushstring(gL.T, "__gc");
8816 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008817 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008818
8819 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008820 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008821
8822 /* Proxy and server configuration initialisation. */
8823 memset(&socket_proxy, 0, sizeof(socket_proxy));
8824 init_new_proxy(&socket_proxy);
8825 socket_proxy.parent = NULL;
8826 socket_proxy.last_change = now.tv_sec;
8827 socket_proxy.id = "LUA-SOCKET";
8828 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8829 socket_proxy.maxconn = 0;
8830 socket_proxy.accept = NULL;
8831 socket_proxy.options2 |= PR_O2_INDEPSTR;
8832 socket_proxy.srv = NULL;
8833 socket_proxy.conn_retries = 0;
8834 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8835
8836 /* Init TCP server: unchanged parameters */
8837 memset(&socket_tcp, 0, sizeof(socket_tcp));
8838 socket_tcp.next = NULL;
8839 socket_tcp.proxy = &socket_proxy;
8840 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8841 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008842 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008843 socket_tcp.priv_conns = NULL;
8844 socket_tcp.idle_conns = NULL;
8845 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008846 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008847 socket_tcp.last_change = 0;
8848 socket_tcp.id = "LUA-TCP-CONN";
8849 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8850 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8851 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8852
8853 /* XXX: Copy default parameter from default server,
8854 * but the default server is not initialized.
8855 */
8856 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8857 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8858 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8859 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8860 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8861 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8862 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8863 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8864 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8865 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8866
8867 socket_tcp.check.status = HCHK_STATUS_INI;
8868 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8869 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8870 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8871 socket_tcp.check.server = &socket_tcp;
8872
8873 socket_tcp.agent.status = HCHK_STATUS_INI;
8874 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8875 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8876 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8877 socket_tcp.agent.server = &socket_tcp;
8878
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008879 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008880
8881#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008882 /* Init TCP server: unchanged parameters */
8883 memset(&socket_ssl, 0, sizeof(socket_ssl));
8884 socket_ssl.next = NULL;
8885 socket_ssl.proxy = &socket_proxy;
8886 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8887 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008888 socket_ssl.pendconns = EB_ROOT;
Willy Tarreaub784b352019-02-07 14:48:24 +01008889 socket_ssl.priv_conns = NULL;
8890 socket_ssl.idle_conns = NULL;
8891 socket_ssl.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008892 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008893 socket_ssl.last_change = 0;
8894 socket_ssl.id = "LUA-SSL-CONN";
8895 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8896 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8897 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8898
8899 /* XXX: Copy default parameter from default server,
8900 * but the default server is not initialized.
8901 */
8902 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8903 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8904 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8905 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8906 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8907 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8908 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8909 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8910 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8911 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8912
8913 socket_ssl.check.status = HCHK_STATUS_INI;
8914 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8915 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8916 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8917 socket_ssl.check.server = &socket_ssl;
8918
8919 socket_ssl.agent.status = HCHK_STATUS_INI;
8920 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8921 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8922 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8923 socket_ssl.agent.server = &socket_ssl;
8924
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008925 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008926 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008927
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008928 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008929 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8930 /*
8931 *
8932 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008933 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008934 * features like client certificates and ssl_verify.
8935 *
8936 */
8937 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8938 if (tmp_error != 0) {
8939 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8940 abort(); /* This must be never arrives because the command line
8941 not editable by the user. */
8942 }
8943 idx += kw->skip;
8944 }
8945 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008946#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008947
8948 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008949}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008950
Willy Tarreau80713382018-11-26 10:19:54 +01008951static void hlua_register_build_options(void)
8952{
Willy Tarreaubb57d942016-12-21 19:04:56 +01008953 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01008954
Willy Tarreaubb57d942016-12-21 19:04:56 +01008955 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8956 hap_register_build_opts(ptr, 1);
8957}
Willy Tarreau80713382018-11-26 10:19:54 +01008958
8959INITCALL0(STG_REGISTER, hlua_register_build_options);