blob: 3d09d27abf3d9df8c0669c4fe4bd8ba9d1bc6a56 [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);
4216 res->total += data;
4217 res->flags |= CF_READ_PARTIAL;
4218 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4219 return;
4220
4221 fail:
4222 hlua_pusherror(L, "Lua applet http '%s': Failed to create 100-Continue response.\n",
4223 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4224 WILL_LJMP(lua_error(L));
4225}
4226
4227
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004228/* If expected data not yet available, it returns a yield. This function
4229 * consumes the data in the buffer. It returns a string containing the
4230 * data. This string can be empty.
4231 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004232__LJMP static int hlua_applet_htx_getline_yield(lua_State *L, int status, lua_KContext ctx)
4233{
4234 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4235 struct stream_interface *si = appctx->appctx->owner;
4236 struct channel *req = si_oc(si);
4237 struct htx *htx;
4238 struct htx_blk *blk;
4239 size_t count;
4240 int stop = 0;
4241
4242 /* Maybe we cant send a 100-continue ? */
4243 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C)
4244 MAY_LJMP(hlua_applet_htx_reply_100_continue(L));
4245
4246 htx = htx_from_buf(&req->buf);
4247 count = co_data(req);
4248 blk = htx_get_head_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004249
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004250 while (count && !stop && blk) {
4251 enum htx_blk_type type = htx_get_blk_type(blk);
4252 uint32_t sz = htx_get_blksz(blk);
4253 struct ist v;
4254 uint32_t vlen;
4255 char *nl;
4256
Christopher Faulete461e342018-12-18 16:43:35 +01004257 if (type == HTX_BLK_EOM) {
4258 stop = 1;
4259 break;
4260 }
4261
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004262 vlen = sz;
4263 if (vlen > count) {
4264 if (type != HTX_BLK_DATA)
4265 break;
4266 vlen = count;
4267 }
4268
4269 switch (type) {
4270 case HTX_BLK_UNUSED:
4271 break;
4272
4273 case HTX_BLK_DATA:
4274 v = htx_get_blk_value(htx, blk);
4275 v.len = vlen;
4276 nl = istchr(v, '\n');
4277 if (nl != NULL) {
4278 stop = 1;
4279 vlen = nl - v.ptr + 1;
4280 }
4281 luaL_addlstring(&appctx->b, v.ptr, vlen);
4282 break;
4283
4284 case HTX_BLK_EOD:
4285 case HTX_BLK_TLR:
4286 case HTX_BLK_EOM:
4287 stop = 1;
4288 break;
4289
4290 default:
4291 break;
4292 }
4293
4294 co_set_data(req, co_data(req) - vlen);
4295 count -= vlen;
4296 if (sz == vlen)
4297 blk = htx_remove_blk(htx, blk);
4298 else {
4299 htx_cut_data_blk(htx, blk, vlen);
4300 break;
4301 }
4302 }
4303
4304 if (!stop) {
4305 si_cant_get(si);
4306 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_getline_yield, TICK_ETERNITY, 0));
4307 }
4308
4309 /* return the result. */
4310 luaL_pushresult(&appctx->b);
4311 return 1;
4312}
4313
4314
4315/* If expected data not yet available, it returns a yield. This function
4316 * consumes the data in the buffer. It returns a string containing the
4317 * data. This string can be empty.
4318 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004319__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004320{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004321 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4322 struct stream_interface *si = appctx->appctx->owner;
4323 struct channel *chn = si_ic(si);
4324 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004325 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004326 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004327 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004328 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004329
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004330 /* Maybe we cant send a 100-continue ? */
4331 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02004332 ret = ci_putblk(chn, HTTP_100.ptr, HTTP_100.len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004333 /* if ret == -2 or -3 the channel closed or the message si too
4334 * big for the buffers. We cant send anything. So, we ignoring
4335 * the error, considers that the 100-continue is sent, and try
4336 * to receive.
4337 * If ret is -1, we dont have room in the buffer, so we yield.
4338 */
4339 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004340 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004341 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004342 }
4343 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4344 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004345
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004346 /* Check for the end of the data. */
4347 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4348 luaL_pushresult(&appctx->b);
4349 return 1;
4350 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004351
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004352 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004353 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004354
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004355 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004356 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004357 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004358 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004359 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004360
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004361 /* End of data: commit the total strings and return. */
4362 if (ret < 0) {
4363 luaL_pushresult(&appctx->b);
4364 return 1;
4365 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004366
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004367 /* Ensure that the block 2 length is usable. */
4368 if (ret == 1)
4369 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004370
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004371 /* Copy the fisrt block caping to the length required. */
4372 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4373 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4374 luaL_addlstring(&appctx->b, blk1, len1);
4375 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004376
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004377 /* Copy the second block. */
4378 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4379 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4380 luaL_addlstring(&appctx->b, blk2, len2);
4381 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004382
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004383 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004384 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004385 luaL_pushresult(&appctx->b);
4386 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004387}
4388
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004389/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004390__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004391{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004392 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004393
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004394 /* Initialise the string catenation. */
4395 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004396
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004397 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
4398 return MAY_LJMP(hlua_applet_htx_getline_yield(L, 0, 0));
4399 else
4400 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004401}
4402
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004403/* If expected data not yet available, it returns a yield. This function
4404 * consumes the data in the buffer. It returns a string containing the
4405 * data. This string can be empty.
4406 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004407__LJMP static int hlua_applet_htx_recv_yield(lua_State *L, int status, lua_KContext ctx)
4408{
4409 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4410 struct stream_interface *si = appctx->appctx->owner;
4411 struct channel *req = si_oc(si);
4412 struct htx *htx;
4413 struct htx_blk *blk;
4414 size_t count;
4415 int len;
4416
4417 /* Maybe we cant send a 100-continue ? */
4418 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C)
4419 MAY_LJMP(hlua_applet_htx_reply_100_continue(L));
4420
4421 htx = htx_from_buf(&req->buf);
4422 len = MAY_LJMP(luaL_checkinteger(L, 2));
4423 count = co_data(req);
4424 blk = htx_get_head_blk(htx);
4425 while (count && len && blk) {
4426 enum htx_blk_type type = htx_get_blk_type(blk);
4427 uint32_t sz = htx_get_blksz(blk);
4428 struct ist v;
4429 uint32_t vlen;
4430
Christopher Faulete461e342018-12-18 16:43:35 +01004431 if (type == HTX_BLK_EOM) {
4432 len = 0;
4433 break;
4434 }
4435
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004436 vlen = sz;
4437 if (len > 0 && vlen > len)
4438 vlen = len;
4439 if (vlen > count) {
4440 if (type != HTX_BLK_DATA)
4441 break;
4442 vlen = count;
4443 }
4444
4445 switch (type) {
4446 case HTX_BLK_UNUSED:
4447 break;
4448
4449 case HTX_BLK_DATA:
4450 v = htx_get_blk_value(htx, blk);
4451 luaL_addlstring(&appctx->b, v.ptr, vlen);
4452 break;
4453
4454 case HTX_BLK_EOD:
4455 case HTX_BLK_TLR:
4456 case HTX_BLK_EOM:
4457 len = 0;
4458 break;
4459
4460 default:
4461 break;
4462 }
4463
4464 co_set_data(req, co_data(req) - vlen);
4465 count -= vlen;
4466 if (len > 0)
4467 len -= vlen;
4468 if (sz == vlen)
4469 blk = htx_remove_blk(htx, blk);
4470 else {
4471 htx_cut_data_blk(htx, blk, vlen);
4472 break;
4473 }
4474 }
4475
4476 /* If we are no other data available, yield waiting for new data. */
4477 if (len) {
4478 if (len > 0) {
4479 lua_pushinteger(L, len);
4480 lua_replace(L, 2);
4481 }
4482 si_cant_get(si);
4483 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_recv_yield, TICK_ETERNITY, 0));
4484 }
4485
4486 /* return the result. */
4487 luaL_pushresult(&appctx->b);
4488 return 1;
4489}
4490
4491/* If expected data not yet available, it returns a yield. This function
4492 * consumes the data in the buffer. It returns a string containing the
4493 * data. This string can be empty.
4494 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004495__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004496{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004497 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4498 struct stream_interface *si = appctx->appctx->owner;
4499 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4500 struct channel *chn = si_ic(si);
4501 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004502 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004503 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004504 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004505 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004506
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004507 /* Maybe we cant send a 100-continue ? */
4508 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02004509 ret = ci_putblk(chn, HTTP_100.ptr, HTTP_100.len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004510 /* if ret == -2 or -3 the channel closed or the message si too
4511 * big for the buffers. We cant send anything. So, we ignoring
4512 * the error, considers that the 100-continue is sent, and try
4513 * to receive.
4514 * If ret is -1, we dont have room in the buffer, so we yield.
4515 */
4516 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004517 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004518 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004519 }
4520 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4521 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004522
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004523 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004524 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004525
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004526 /* Data not yet available. return yield. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004527 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004528 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004529 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004530 }
4531
4532 /* End of data: commit the total strings and return. */
4533 if (ret < 0) {
4534 luaL_pushresult(&appctx->b);
4535 return 1;
4536 }
4537
4538 /* Ensure that the block 2 length is usable. */
4539 if (ret == 1)
4540 len2 = 0;
4541
4542 /* Copy the fisrt block caping to the length required. */
4543 if (len1 > len)
4544 len1 = len;
4545 luaL_addlstring(&appctx->b, blk1, len1);
4546 len -= len1;
4547
4548 /* Copy the second block. */
4549 if (len2 > len)
4550 len2 = len;
4551 luaL_addlstring(&appctx->b, blk2, len2);
4552 len -= len2;
4553
4554 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004555 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004556 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4557 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4558
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004559 /* If we are no other data available, yield waiting for new data. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004560 if (len > 0) {
4561 lua_pushinteger(L, len);
4562 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004563 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004564 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004565 }
4566
4567 /* return the result. */
4568 luaL_pushresult(&appctx->b);
4569 return 1;
4570}
4571
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004572/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004573__LJMP static int hlua_applet_http_recv(lua_State *L)
4574{
4575 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4576 int len = -1;
4577
4578 /* Check arguments. */
4579 if (lua_gettop(L) > 2)
4580 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4581 if (lua_gettop(L) >= 2) {
4582 len = MAY_LJMP(luaL_checkinteger(L, 2));
4583 lua_pop(L, 1);
4584 }
4585
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004586 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4587 /* HTX version */
4588 lua_pushinteger(L, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004589
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004590 /* Initialise the string catenation. */
4591 luaL_buffinit(L, &appctx->b);
4592
4593 return MAY_LJMP(hlua_applet_htx_recv_yield(L, 0, 0));
4594 }
4595 else {
4596 /* Legacy HTTP version */
4597 /* Check the required length */
4598 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4599 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4600 lua_pushinteger(L, len);
4601
4602 /* Initialise the string catenation. */
4603 luaL_buffinit(L, &appctx->b);
4604
4605 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4606 }
4607}
4608
4609/* Append data in the output side of the buffer. This data is immediately
4610 * sent. The function returns the amount of data written. If the buffer
4611 * cannot contain the data, the function yields. The function returns -1
4612 * if the channel is closed.
4613 */
4614__LJMP static int hlua_applet_htx_send_yield(lua_State *L, int status, lua_KContext ctx)
4615{
4616 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4617 struct stream_interface *si = appctx->appctx->owner;
4618 struct channel *res = si_ic(si);
4619 struct htx *htx = htx_from_buf(&res->buf);
4620 const char *data;
4621 size_t len;
4622 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4623 int max;
4624
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004625 max = channel_htx_recv_max(res, htx);
4626 if (!max)
4627 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004628
4629 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4630
4631 /* Get the max amount of data which can write as input in the channel. */
4632 if (max > (len - l))
4633 max = len - l;
4634
4635 /* Copy data. */
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004636 if (!htx_add_data(htx, ist2(data + l, max)))
4637 goto snd_yield;
4638 res->total += max;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004639 res->flags |= CF_READ_PARTIAL;
4640 htx_to_buf(htx, &res->buf);
4641
4642 /* update counters. */
4643 l += max;
4644 lua_pop(L, 1);
4645 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004646
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004647 /* If some data is not send, declares the situation to the
4648 * applet, and returns a yield.
4649 */
4650 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004651 snd_yield:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004652 si_rx_room_blk(si);
4653 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_send_yield, TICK_ETERNITY, 0));
4654 }
4655
4656 return 1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004657}
4658
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004659/* Append data in the output side of the buffer. This data is immediately
4660 * sent. The function returns the amount of data written. If the buffer
4661 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004662 * if the channel is closed.
4663 */
4664__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4665{
4666 size_t len;
4667 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4668 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4669 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4670 struct stream_interface *si = appctx->appctx->owner;
4671 struct channel *chn = si_ic(si);
4672 int max;
4673
4674 /* Get the max amount of data which can write as input in the channel. */
4675 max = channel_recv_max(chn);
4676 if (max > (len - l))
4677 max = len - l;
4678
4679 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004680 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004681
4682 /* update counters. */
4683 l += max;
4684 lua_pop(L, 1);
4685 lua_pushinteger(L, l);
4686
4687 /* If some data is not send, declares the situation to the
4688 * applet, and returns a yield.
4689 */
4690 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004691 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004692 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004693 }
4694
4695 return 1;
4696}
4697
4698/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4699 * yield the LUA process, and resume it without checking the
4700 * input arguments.
4701 */
4702__LJMP static int hlua_applet_http_send(lua_State *L)
4703{
4704 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004705
4706 /* We want to send some data. Headers must be sent. */
4707 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4708 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4709 WILL_LJMP(lua_error(L));
4710 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004711
4712 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4713 /* HTX version */
4714 /* This interger is used for followinf the amount of data sent. */
4715 lua_pushinteger(L, 0);
4716
4717 return MAY_LJMP(hlua_applet_htx_send_yield(L, 0, 0));
4718 }
4719 else {
4720 /* Legacy HTTP version */
4721 size_t len;
4722 char hex[10];
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004723
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004724 MAY_LJMP(luaL_checklstring(L, 2, &len));
4725
4726 /* If transfer encoding chunked is selected, we surround the data
4727 * by chunk data.
4728 */
4729 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4730 snprintf(hex, 9, "%x", (unsigned int)len);
4731 lua_pushfstring(L, "%s\r\n", hex);
4732 lua_insert(L, 2); /* swap the last 2 entries. */
4733 lua_pushstring(L, "\r\n");
4734 lua_concat(L, 3);
4735 }
4736
4737 /* This interger is used for followinf the amount of data sent. */
4738 lua_pushinteger(L, 0);
4739
4740 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4741 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004742}
4743
4744__LJMP static int hlua_applet_http_addheader(lua_State *L)
4745{
4746 const char *name;
4747 int ret;
4748
4749 MAY_LJMP(hlua_checkapplet_http(L, 1));
4750 name = MAY_LJMP(luaL_checkstring(L, 2));
4751 MAY_LJMP(luaL_checkstring(L, 3));
4752
4753 /* Push in the stack the "response" entry. */
4754 ret = lua_getfield(L, 1, "response");
4755 if (ret != LUA_TTABLE) {
4756 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4757 "is expected as an array. %s found", lua_typename(L, ret));
4758 WILL_LJMP(lua_error(L));
4759 }
4760
4761 /* check if the header is already registered if it is not
4762 * the case, register it.
4763 */
4764 ret = lua_getfield(L, -1, name);
4765 if (ret == LUA_TNIL) {
4766
4767 /* Entry not found. */
4768 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4769
4770 /* Insert the new header name in the array in the top of the stack.
4771 * It left the new array in the top of the stack.
4772 */
4773 lua_newtable(L);
4774 lua_pushvalue(L, 2);
4775 lua_pushvalue(L, -2);
4776 lua_settable(L, -4);
4777
4778 } else if (ret != LUA_TTABLE) {
4779
4780 /* corruption error. */
4781 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4782 "is expected as an array. %s found", name, lua_typename(L, ret));
4783 WILL_LJMP(lua_error(L));
4784 }
4785
4786 /* Now the top od thestack is an array of values. We push
4787 * the header value as new entry.
4788 */
4789 lua_pushvalue(L, 3);
4790 ret = lua_rawlen(L, -2);
4791 lua_rawseti(L, -2, ret + 1);
4792 lua_pushboolean(L, 1);
4793 return 1;
4794}
4795
4796__LJMP static int hlua_applet_http_status(lua_State *L)
4797{
4798 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4799 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004800 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004801
4802 if (status < 100 || status > 599) {
4803 lua_pushboolean(L, 0);
4804 return 1;
4805 }
4806
4807 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004808 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004809 lua_pushboolean(L, 1);
4810 return 1;
4811}
4812
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004813
4814__LJMP static int hlua_applet_htx_send_response(lua_State *L)
4815{
4816 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4817 struct stream_interface *si = appctx->appctx->owner;
4818 struct channel *res = si_ic(si);
4819 struct htx *htx;
4820 struct htx_sl *sl;
4821 struct h1m h1m;
4822 const char *status, *reason;
4823 const char *name, *value;
4824 size_t nlen, vlen;
4825 unsigned int flags;
4826
4827 /* Send the message at once. */
4828 htx = htx_from_buf(&res->buf);
4829 h1m_init_res(&h1m);
4830
4831 /* Use the same http version than the request. */
4832 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4833 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4834 if (reason == NULL)
4835 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4836 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4837 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4838 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4839 }
4840 else {
4841 flags = HTX_SL_F_IS_RESP;
4842 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4843 }
4844 if (!sl) {
4845 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
4846 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4847 WILL_LJMP(lua_error(L));
4848 }
4849 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4850
4851 /* Get the array associated to the field "response" in the object AppletHTTP. */
4852 lua_pushvalue(L, 0);
4853 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4854 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4855 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4856 WILL_LJMP(lua_error(L));
4857 }
4858
4859 /* Browse the list of headers. */
4860 lua_pushnil(L);
4861 while(lua_next(L, -2) != 0) {
4862 /* We expect a string as -2. */
4863 if (lua_type(L, -2) != LUA_TSTRING) {
4864 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4865 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4866 lua_typename(L, lua_type(L, -2)));
4867 WILL_LJMP(lua_error(L));
4868 }
4869 name = lua_tolstring(L, -2, &nlen);
4870
4871 /* We expect an array as -1. */
4872 if (lua_type(L, -1) != LUA_TTABLE) {
4873 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4874 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4875 name,
4876 lua_typename(L, lua_type(L, -1)));
4877 WILL_LJMP(lua_error(L));
4878 }
4879
4880 /* Browse the table who is on the top of the stack. */
4881 lua_pushnil(L);
4882 while(lua_next(L, -2) != 0) {
4883 int id;
4884
4885 /* We expect a number as -2. */
4886 if (lua_type(L, -2) != LUA_TNUMBER) {
4887 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4888 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4889 name,
4890 lua_typename(L, lua_type(L, -2)));
4891 WILL_LJMP(lua_error(L));
4892 }
4893 id = lua_tointeger(L, -2);
4894
4895 /* We expect a string as -2. */
4896 if (lua_type(L, -1) != LUA_TSTRING) {
4897 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4898 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4899 name, id,
4900 lua_typename(L, lua_type(L, -1)));
4901 WILL_LJMP(lua_error(L));
4902 }
4903 value = lua_tolstring(L, -1, &vlen);
4904
4905 /* Simple Protocol checks. */
4906 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
4907 h1_parse_xfer_enc_header(&h1m, ist2(name, nlen));
4908 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4909 struct ist v = ist2(value, vlen);
4910 int ret;
4911
4912 ret = h1_parse_cont_len_header(&h1m, &v);
4913 if (ret < 0) {
4914 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
4915 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4916 name);
4917 WILL_LJMP(lua_error(L));
4918 }
4919 else if (ret == 0)
4920 goto next; /* Skip it */
4921 }
4922
4923 /* Add a new header */
4924 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4925 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
4926 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4927 name);
4928 WILL_LJMP(lua_error(L));
4929 }
4930 next:
4931 /* Remove the array from the stack, and get next element with a remaining string. */
4932 lua_pop(L, 1);
4933 }
4934
4935 /* Remove the array from the stack, and get next element with a remaining string. */
4936 lua_pop(L, 1);
4937 }
4938
4939 if (h1m.flags & H1_MF_CHNK)
4940 h1m.flags &= ~H1_MF_CLEN;
4941 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4942 h1m.flags |= H1_MF_XFER_LEN;
4943
4944 /* Uset HTX start-line flags */
4945 if (h1m.flags & H1_MF_XFER_ENC)
4946 flags |= HTX_SL_F_XFER_ENC;
4947 if (h1m.flags & H1_MF_XFER_LEN) {
4948 flags |= HTX_SL_F_XFER_LEN;
4949 if (h1m.flags & H1_MF_CHNK)
4950 flags |= HTX_SL_F_CHNK;
4951 else if (h1m.flags & H1_MF_CLEN)
4952 flags |= HTX_SL_F_CLEN;
4953 if (h1m.body_len == 0)
4954 flags |= HTX_SL_F_BODYLESS;
4955 }
4956 sl->flags |= flags;
4957
4958 /* If we dont have a content-length set, and the HTTP version is 1.1
4959 * and the status code implies the presence of a message body, we must
4960 * announce a transfer encoding chunked. This is required by haproxy
4961 * for the keepalive compliance. If the applet annouces a transfer-encoding
4962 * chunked itslef, don't do anything.
4963 */
4964 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4965 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4966 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4967 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4968 /* Add a new header */
4969 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4970 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4971 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
4972 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4973 WILL_LJMP(lua_error(L));
4974 }
4975 }
4976
4977 /* Finalize headers. */
4978 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4979 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
4980 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4981 WILL_LJMP(lua_error(L));
4982 }
4983
4984 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4985 b_reset(&res->buf);
4986 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4987 WILL_LJMP(lua_error(L));
4988 }
4989
4990 htx_to_buf(htx, &res->buf);
4991 res->total += htx->data;
4992 res->flags |= CF_READ_PARTIAL;
4993
4994 /* Headers sent, set the flag. */
4995 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4996 return 0;
4997
4998}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004999/* We will build the status line and the headers of the HTTP response.
5000 * We will try send at once if its not possible, we give back the hand
5001 * waiting for more room.
5002 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005003__LJMP static int hlua_applet_htx_start_response_yield(lua_State *L, int status, lua_KContext ctx)
5004{
5005 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5006 struct stream_interface *si = appctx->appctx->owner;
5007 struct channel *res = si_ic(si);
5008
5009 if (co_data(res)) {
5010 si_rx_room_blk(si);
5011 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_start_response_yield, TICK_ETERNITY, 0));
5012 }
5013 return MAY_LJMP(hlua_applet_htx_send_response(L));
5014}
5015
5016
5017__LJMP static int hlua_applet_htx_start_response(lua_State *L)
5018{
5019 return MAY_LJMP(hlua_applet_htx_start_response_yield(L, 0, 0));
5020}
5021
5022/* We will build the status line and the headers of the HTTP response.
5023 * We will try send at once if its not possible, we give back the hand
5024 * waiting for more room.
5025 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005026__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
5027{
5028 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5029 struct stream_interface *si = appctx->appctx->owner;
5030 struct channel *chn = si_ic(si);
5031 int ret;
5032 size_t len;
5033 const char *msg;
5034
5035 /* Get the message as the first argument on the stack. */
5036 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
5037
5038 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02005039 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005040
5041 /* if ret == -2 or -3 the channel closed or the message si too
5042 * big for the buffers.
5043 */
5044 if (ret == -2 || ret == -3) {
5045 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5046 WILL_LJMP(lua_error(L));
5047 }
5048
5049 /* If ret is -1, we dont have room in the buffer, so we yield. */
5050 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01005051 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005052 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005053 }
5054
5055 /* Headers sent, set the flag. */
5056 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
5057 return 0;
5058}
5059
5060__LJMP static int hlua_applet_http_start_response(lua_State *L)
5061{
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005062 struct buffer *tmp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005063 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005064 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02005065 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005066 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02005067 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005068 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005069 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005070 int hdr_chunked = 0;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005071 const char *reason;
5072
5073 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
5074 return MAY_LJMP(hlua_applet_htx_start_response(L));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005075
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005076 reason = appctx->appctx->ctx.hlua_apphttp.reason;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005077 if (reason == NULL)
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02005078 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005079
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005080 tmp = get_trash_chunk();
5081
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005082 /* Use the same http version than the request. */
5083 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005084 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005085 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005086 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005087
5088 /* Get the array associated to the field "response" in the object AppletHTTP. */
5089 lua_pushvalue(L, 0);
5090 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5091 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
5092 appctx->appctx->rule->arg.hlua_rule->fcn.name);
5093 WILL_LJMP(lua_error(L));
5094 }
5095
5096 /* Browse the list of headers. */
5097 lua_pushnil(L);
5098 while(lua_next(L, -2) != 0) {
5099
5100 /* We expect a string as -2. */
5101 if (lua_type(L, -2) != LUA_TSTRING) {
5102 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
5103 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5104 lua_typename(L, lua_type(L, -2)));
5105 WILL_LJMP(lua_error(L));
5106 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005107 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005108
5109 /* We expect an array as -1. */
5110 if (lua_type(L, -1) != LUA_TTABLE) {
5111 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
5112 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5113 name,
5114 lua_typename(L, lua_type(L, -1)));
5115 WILL_LJMP(lua_error(L));
5116 }
5117
5118 /* Browse the table who is on the top of the stack. */
5119 lua_pushnil(L);
5120 while(lua_next(L, -2) != 0) {
5121
5122 /* We expect a number as -2. */
5123 if (lua_type(L, -2) != LUA_TNUMBER) {
5124 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
5125 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5126 name,
5127 lua_typename(L, lua_type(L, -2)));
5128 WILL_LJMP(lua_error(L));
5129 }
5130 id = lua_tointeger(L, -2);
5131
5132 /* We expect a string as -2. */
5133 if (lua_type(L, -1) != LUA_TSTRING) {
5134 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
5135 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5136 name, id,
5137 lua_typename(L, lua_type(L, -1)));
5138 WILL_LJMP(lua_error(L));
5139 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005140 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005141
5142 /* Catenate a new header. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005143 if (tmp->data + name_len + 2 + value_len + 2 < tmp->size) {
5144 memcpy(tmp->area + tmp->data, name, name_len);
5145 tmp->data += name_len;
5146 tmp->area[tmp->data++] = ':';
5147 tmp->area[tmp->data++] = ' ';
Willy Tarreaua3294632017-08-23 11:24:47 +02005148
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005149 memcpy(tmp->area + tmp->data, value,
5150 value_len);
5151 tmp->data += value_len;
5152 tmp->area[tmp->data++] = '\r';
5153 tmp->area[tmp->data++] = '\n';
Willy Tarreaua3294632017-08-23 11:24:47 +02005154 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005155
5156 /* Protocol checks. */
5157
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005158 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005159 * is done without control. If it contains a bad value,
5160 * the content-length remains negative so that we can
5161 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005162 */
Willy Tarreaua3294632017-08-23 11:24:47 +02005163 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005164 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005165
5166 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02005167 if (name_len == 17 && value_len == 7 &&
5168 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005169 strcasecmp("chunked", value) == 0)
5170 hdr_chunked = 1;
5171
5172 /* Remove the array from the stack, and get next element with a remaining string. */
5173 lua_pop(L, 1);
5174 }
5175
5176 /* Remove the array from the stack, and get next element with a remaining string. */
5177 lua_pop(L, 1);
5178 }
5179
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005180 /* If we dont have a content-length set, and the HTTP version is 1.1
5181 * and the status code implies the presence of a message body, we must
5182 * announce a transfer encoding chunked. This is required by haproxy
5183 * for the keepalive compliance. If the applet annouces a transfer-encoding
5184 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005185 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005186 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005187 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
5188 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
5189 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
5190 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005191 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
5192 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
5193 }
5194
5195 /* Finalize headers. */
5196 chunk_appendf(tmp, "\r\n");
5197
5198 /* Remove the last entry and the array of headers */
5199 lua_pop(L, 2);
5200
5201 /* Push the headers block. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005202 lua_pushlstring(L, tmp->area, tmp->data);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005203
5204 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
5205}
5206
5207/*
5208 *
5209 *
5210 * Class HTTP
5211 *
5212 *
5213 */
5214
5215/* Returns a struct hlua_txn if the stack entry "ud" is
5216 * a class stream, otherwise it throws an error.
5217 */
5218__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
5219{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005220 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005221}
5222
5223/* This function creates and push in the stack a HTTP object
5224 * according with a current TXN.
5225 */
5226static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5227{
5228 struct hlua_txn *htxn;
5229
5230 /* Check stack size. */
5231 if (!lua_checkstack(L, 3))
5232 return 0;
5233
5234 /* Create the object: obj[0] = userdata.
5235 * Note that the base of the Converters object is the
5236 * same than the TXN object.
5237 */
5238 lua_newtable(L);
5239 htxn = lua_newuserdata(L, sizeof(*htxn));
5240 lua_rawseti(L, -2, 0);
5241
5242 htxn->s = txn->s;
5243 htxn->p = txn->p;
5244
5245 /* Pop a class stream metatable and affect it to the table. */
5246 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5247 lua_setmetatable(L, -2);
5248
5249 return 1;
5250}
5251
5252/* This function creates ans returns an array of HTTP headers.
5253 * This function does not fails. It is used as wrapper with the
5254 * 2 following functions.
5255 */
5256__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5257{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005258 /* Create the table. */
5259 lua_newtable(L);
5260
5261 if (!htxn->s->txn)
5262 return 1;
5263
Christopher Faulet724a12c2018-12-13 22:12:15 +01005264 if (IS_HTX_STRM(htxn->s)) {
5265 /* HTX version */
5266 struct htx *htx = htxbuf(&msg->chn->buf);
5267 int32_t pos;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005268
Christopher Faulet724a12c2018-12-13 22:12:15 +01005269 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5270 struct htx_blk *blk = htx_get_blk(htx, pos);
5271 enum htx_blk_type type = htx_get_blk_type(blk);
5272 struct ist n, v;
5273 int len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005274
Christopher Faulet724a12c2018-12-13 22:12:15 +01005275 if (type == HTX_BLK_HDR) {
5276 n = htx_get_blk_name(htx,blk);
5277 v = htx_get_blk_value(htx, blk);
5278 }
5279 else if (type == HTX_BLK_EOH)
5280 break;
5281 else
5282 continue;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005283
Christopher Faulet724a12c2018-12-13 22:12:15 +01005284 /* Check for existing entry:
5285 * assume that the table is on the top of the stack, and
5286 * push the key in the stack, the function lua_gettable()
5287 * perform the lookup.
5288 */
5289 lua_pushlstring(L, n.ptr, n.len);
5290 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005291
Christopher Faulet724a12c2018-12-13 22:12:15 +01005292 switch (lua_type(L, -1)) {
5293 case LUA_TNIL:
5294 /* Table not found, create it. */
5295 lua_pop(L, 1); /* remove the nil value. */
5296 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5297 lua_newtable(L); /* create and push empty table. */
5298 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5299 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5300 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5301 break;
5302
5303 case LUA_TTABLE:
5304 /* Entry found: push the value in the table. */
5305 len = lua_rawlen(L, -1);
5306 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5307 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5308 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5309 break;
5310
5311 default:
5312 /* Other cases are errors. */
5313 hlua_pusherror(L, "internal error during the parsing of headers.");
5314 WILL_LJMP(lua_error(L));
5315 }
5316 }
5317 }
5318 else {
5319 /* Legacy HTTP version */
5320 const char *cur_ptr, *cur_next, *p;
5321 int old_idx, cur_idx;
5322 struct hdr_idx_elem *cur_hdr;
5323 const char *hn, *hv;
5324 int hnl, hvl;
5325 const char *in;
5326 char *out;
5327 int len;
5328
5329 /* Build array of headers. */
5330 old_idx = 0;
5331 cur_next = ci_head(msg->chn) + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
5332
5333 while (1) {
5334 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
5335 if (!cur_idx)
5336 break;
5337 old_idx = cur_idx;
5338
5339 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
5340 cur_ptr = cur_next;
5341 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
5342
5343 /* Now we have one full header at cur_ptr of len cur_hdr->len,
5344 * and the next header starts at cur_next. We'll check
5345 * this header in the list as well as against the default
5346 * rule.
5347 */
5348
5349 /* look for ': *'. */
5350 hn = cur_ptr;
5351 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
5352 if (p >= cur_ptr+cur_hdr->len)
5353 continue;
5354 hnl = p - hn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005355 p++;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005356 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
5357 p++;
5358 if (p >= cur_ptr+cur_hdr->len)
5359 continue;
5360 hv = p;
5361 hvl = cur_ptr+cur_hdr->len-p;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005362
Christopher Faulet724a12c2018-12-13 22:12:15 +01005363 /* Lowercase the key. Don't check the size of trash, it have
5364 * the size of one buffer and the input data contains in one
5365 * buffer.
5366 */
5367 out = trash.area;
5368 for (in=hn; in<hn+hnl; in++, out++)
5369 *out = tolower(*in);
5370 *out = '\0';
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005371
Christopher Faulet724a12c2018-12-13 22:12:15 +01005372 /* Check for existing entry:
5373 * assume that the table is on the top of the stack, and
5374 * push the key in the stack, the function lua_gettable()
5375 * perform the lookup.
5376 */
5377 lua_pushlstring(L, trash.area, hnl);
5378 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005379
Christopher Faulet724a12c2018-12-13 22:12:15 +01005380 switch (lua_type(L, -1)) {
5381 case LUA_TNIL:
5382 /* Table not found, create it. */
5383 lua_pop(L, 1); /* remove the nil value. */
5384 lua_pushlstring(L, trash.area, hnl); /* push the header name as key. */
5385 lua_newtable(L); /* create and push empty table. */
5386 lua_pushlstring(L, hv, hvl); /* push header value. */
5387 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5388 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5389 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005390
Christopher Faulet724a12c2018-12-13 22:12:15 +01005391 case LUA_TTABLE:
5392 /* Entry found: push the value in the table. */
5393 len = lua_rawlen(L, -1);
5394 lua_pushlstring(L, hv, hvl); /* push header value. */
5395 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5396 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5397 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005398
Christopher Faulet724a12c2018-12-13 22:12:15 +01005399 default:
5400 /* Other cases are errors. */
5401 hlua_pusherror(L, "internal error during the parsing of headers.");
5402 WILL_LJMP(lua_error(L));
5403 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005404 }
5405 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005406 return 1;
5407}
5408
5409__LJMP static int hlua_http_req_get_headers(lua_State *L)
5410{
5411 struct hlua_txn *htxn;
5412
5413 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5414 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5415
5416 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
5417}
5418
5419__LJMP static int hlua_http_res_get_headers(lua_State *L)
5420{
5421 struct hlua_txn *htxn;
5422
5423 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5424 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5425
5426 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
5427}
5428
5429/* This function replace full header, or just a value in
5430 * the request or in the response. It is a wrapper fir the
5431 * 4 following functions.
5432 */
5433__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
5434 struct http_msg *msg, int action)
5435{
5436 size_t name_len;
5437 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5438 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5439 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
5440 struct my_regex re;
5441
5442 if (!regex_comp(reg, &re, 1, 1, NULL))
5443 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5444
5445 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
5446 regex_free(&re);
5447 return 0;
5448}
5449
5450__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5451{
5452 struct hlua_txn *htxn;
5453
5454 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5455 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5456
5457 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
5458}
5459
5460__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5461{
5462 struct hlua_txn *htxn;
5463
5464 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5465 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5466
5467 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
5468}
5469
5470__LJMP static int hlua_http_req_rep_val(lua_State *L)
5471{
5472 struct hlua_txn *htxn;
5473
5474 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5475 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5476
5477 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
5478}
5479
5480__LJMP static int hlua_http_res_rep_val(lua_State *L)
5481{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005482 struct hlua_txn *htxn;
5483
5484 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5485 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5486
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02005487 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005488}
5489
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005490/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005491 * It is a wrapper for the 2 following functions.
5492 */
5493__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5494{
5495 size_t len;
5496 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005497
Christopher Faulet724a12c2018-12-13 22:12:15 +01005498 if (IS_HTX_STRM(htxn->s)) {
5499 /* HTX version */
5500 struct htx *htx = htxbuf(&msg->chn->buf);
5501 struct http_hdr_ctx ctx;
5502
5503 ctx.blk = NULL;
5504 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5505 http_remove_header(htx, &ctx);
5506 }
5507 else {
5508 /* Legacy HTTP version */
5509 struct hdr_ctx ctx;
5510 struct http_txn *txn = htxn->s->txn;
5511
5512 ctx.idx = 0;
5513 while (http_find_header2(name, len, ci_head(msg->chn), &txn->hdr_idx, &ctx))
5514 http_remove_header2(msg, &txn->hdr_idx, &ctx);
5515 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005516 return 0;
5517}
5518
5519__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5520{
5521 struct hlua_txn *htxn;
5522
5523 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5524 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5525
Willy Tarreaueee5b512015-04-03 23:46:31 +02005526 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005527}
5528
5529__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5530{
5531 struct hlua_txn *htxn;
5532
5533 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5534 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5535
Willy Tarreaueee5b512015-04-03 23:46:31 +02005536 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005537}
5538
5539/* This function adds an header. It is a wrapper used by
5540 * the 2 following functions.
5541 */
5542__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5543{
5544 size_t name_len;
5545 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5546 size_t value_len;
5547 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
5548 char *p;
5549
Christopher Faulet724a12c2018-12-13 22:12:15 +01005550 if (IS_HTX_STRM(htxn->s)) {
5551 /* HTX version */
5552 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005553
Christopher Faulet724a12c2018-12-13 22:12:15 +01005554 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5555 ist2(value, value_len)));
5556 }
5557 else {
5558 /* Legacy HTTP version */
5559 /* Check length. */
5560 trash.data = value_len + name_len + 2;
5561 if (trash.data > trash.size)
5562 return 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005563
Christopher Faulet724a12c2018-12-13 22:12:15 +01005564 /* Creates the header string. */
5565 p = trash.area;
5566 memcpy(p, name, name_len);
5567 p += name_len;
5568 *p = ':';
5569 p++;
5570 *p = ' ';
5571 p++;
5572 memcpy(p, value, value_len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005573
Christopher Faulet724a12c2018-12-13 22:12:15 +01005574 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
5575 trash.area, trash.data) != 0);
5576 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005577 return 0;
5578}
5579
5580__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5581{
5582 struct hlua_txn *htxn;
5583
5584 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5585 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5586
Willy Tarreaueee5b512015-04-03 23:46:31 +02005587 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005588}
5589
5590__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5591{
5592 struct hlua_txn *htxn;
5593
5594 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5595 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5596
Willy Tarreaueee5b512015-04-03 23:46:31 +02005597 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005598}
5599
5600static int hlua_http_req_set_hdr(lua_State *L)
5601{
5602 struct hlua_txn *htxn;
5603
5604 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5605 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5606
Willy Tarreaueee5b512015-04-03 23:46:31 +02005607 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
5608 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005609}
5610
5611static int hlua_http_res_set_hdr(lua_State *L)
5612{
5613 struct hlua_txn *htxn;
5614
5615 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5616 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5617
Willy Tarreaueee5b512015-04-03 23:46:31 +02005618 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
5619 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005620}
5621
5622/* This function set the method. */
5623static int hlua_http_req_set_meth(lua_State *L)
5624{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005625 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005626 size_t name_len;
5627 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005628
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005629 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005630 return 1;
5631}
5632
5633/* This function set the method. */
5634static int hlua_http_req_set_path(lua_State *L)
5635{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005636 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005637 size_t name_len;
5638 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005639
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005640 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005641 return 1;
5642}
5643
5644/* This function set the query-string. */
5645static int hlua_http_req_set_query(lua_State *L)
5646{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005647 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005648 size_t name_len;
5649 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005650
5651 /* Check length. */
5652 if (name_len > trash.size - 1) {
5653 lua_pushboolean(L, 0);
5654 return 1;
5655 }
5656
5657 /* Add the mark question as prefix. */
5658 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005659 trash.area[trash.data++] = '?';
5660 memcpy(trash.area + trash.data, name, name_len);
5661 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005662
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005663 lua_pushboolean(L,
5664 http_replace_req_line(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005665 return 1;
5666}
5667
5668/* This function set the uri. */
5669static int hlua_http_req_set_uri(lua_State *L)
5670{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005671 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005672 size_t name_len;
5673 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005674
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005675 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005676 return 1;
5677}
5678
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005679/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005680static int hlua_http_res_set_status(lua_State *L)
5681{
5682 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5683 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005684 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005685
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005686 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005687 return 0;
5688}
5689
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005690/*
5691 *
5692 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005693 * Class TXN
5694 *
5695 *
5696 */
5697
5698/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005699 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005700 */
5701__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5702{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005703 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005704}
5705
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005706__LJMP static int hlua_set_var(lua_State *L)
5707{
5708 struct hlua_txn *htxn;
5709 const char *name;
5710 size_t len;
5711 struct sample smp;
5712
5713 MAY_LJMP(check_args(L, 3, "set_var"));
5714
5715 /* It is useles to retrieve the stream, but this function
5716 * runs only in a stream context.
5717 */
5718 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5719 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5720
5721 /* Converts the third argument in a sample. */
5722 hlua_lua2smp(L, 3, &smp);
5723
5724 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005725 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005726 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005727 return 0;
5728}
5729
Christopher Faulet85d79c92016-11-09 16:54:56 +01005730__LJMP static int hlua_unset_var(lua_State *L)
5731{
5732 struct hlua_txn *htxn;
5733 const char *name;
5734 size_t len;
5735 struct sample smp;
5736
5737 MAY_LJMP(check_args(L, 2, "unset_var"));
5738
5739 /* It is useles to retrieve the stream, but this function
5740 * runs only in a stream context.
5741 */
5742 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5743 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5744
5745 /* Unset the variable. */
5746 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5747 vars_unset_by_name(name, len, &smp);
5748 return 0;
5749}
5750
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005751__LJMP static int hlua_get_var(lua_State *L)
5752{
5753 struct hlua_txn *htxn;
5754 const char *name;
5755 size_t len;
5756 struct sample smp;
5757
5758 MAY_LJMP(check_args(L, 2, "get_var"));
5759
5760 /* It is useles to retrieve the stream, but this function
5761 * runs only in a stream context.
5762 */
5763 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5764 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5765
Willy Tarreau7560dd42016-03-10 16:28:58 +01005766 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005767 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005768 lua_pushnil(L);
5769 return 1;
5770 }
5771
5772 return hlua_smp2lua(L, &smp);
5773}
5774
Willy Tarreau59551662015-03-10 14:23:13 +01005775__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005776{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005777 struct hlua *hlua;
5778
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005779 MAY_LJMP(check_args(L, 2, "set_priv"));
5780
Willy Tarreau87b09662015-04-03 00:22:06 +02005781 /* It is useles to retrieve the stream, but this function
5782 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005783 */
5784 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005785 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005786
5787 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005788 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005789
5790 /* Get and store new value. */
5791 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5792 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5793
5794 return 0;
5795}
5796
Willy Tarreau59551662015-03-10 14:23:13 +01005797__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005798{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005799 struct hlua *hlua;
5800
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005801 MAY_LJMP(check_args(L, 1, "get_priv"));
5802
Willy Tarreau87b09662015-04-03 00:22:06 +02005803 /* It is useles to retrieve the stream, but this function
5804 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005805 */
5806 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005807 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005808
5809 /* Push configuration index in the stack. */
5810 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5811
5812 return 1;
5813}
5814
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005815/* Create stack entry containing a class TXN. This function
5816 * return 0 if the stack does not contains free slots,
5817 * otherwise it returns 1.
5818 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005819static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005820{
Willy Tarreaude491382015-04-06 11:04:28 +02005821 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005822
5823 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005824 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005825 return 0;
5826
5827 /* NOTE: The allocation never fails. The failure
5828 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005829 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005830 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005831 /* Create the object: obj[0] = userdata. */
5832 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005833 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005834 lua_rawseti(L, -2, 0);
5835
Willy Tarreaude491382015-04-06 11:04:28 +02005836 htxn->s = s;
5837 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005838 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005839 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005840
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005841 /* Create the "f" field that contains a list of fetches. */
5842 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005843 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005844 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005845 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005846
5847 /* Create the "sf" field that contains a list of stringsafe fetches. */
5848 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005849 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005850 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005851 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005852
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005853 /* Create the "c" field that contains a list of converters. */
5854 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005855 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005856 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005857 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005858
5859 /* Create the "sc" field that contains a list of stringsafe converters. */
5860 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005861 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005862 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005863 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005864
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005865 /* Create the "req" field that contains the request channel object. */
5866 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005867 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005868 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005869 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005870
5871 /* Create the "res" field that contains the response channel object. */
5872 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005873 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005874 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005875 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005876
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005877 /* Creates the HTTP object is the current proxy allows http. */
5878 lua_pushstring(L, "http");
5879 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005880 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005881 return 0;
5882 }
5883 else
5884 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005885 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005886
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005887 /* Pop a class sesison metatable and affect it to the userdata. */
5888 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5889 lua_setmetatable(L, -2);
5890
5891 return 1;
5892}
5893
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005894__LJMP static int hlua_txn_deflog(lua_State *L)
5895{
5896 const char *msg;
5897 struct hlua_txn *htxn;
5898
5899 MAY_LJMP(check_args(L, 2, "deflog"));
5900 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5901 msg = MAY_LJMP(luaL_checkstring(L, 2));
5902
5903 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5904 return 0;
5905}
5906
5907__LJMP static int hlua_txn_log(lua_State *L)
5908{
5909 int level;
5910 const char *msg;
5911 struct hlua_txn *htxn;
5912
5913 MAY_LJMP(check_args(L, 3, "log"));
5914 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5915 level = MAY_LJMP(luaL_checkinteger(L, 2));
5916 msg = MAY_LJMP(luaL_checkstring(L, 3));
5917
5918 if (level < 0 || level >= NB_LOG_LEVELS)
5919 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5920
5921 hlua_sendlog(htxn->s->be, level, msg);
5922 return 0;
5923}
5924
5925__LJMP static int hlua_txn_log_debug(lua_State *L)
5926{
5927 const char *msg;
5928 struct hlua_txn *htxn;
5929
5930 MAY_LJMP(check_args(L, 2, "Debug"));
5931 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5932 msg = MAY_LJMP(luaL_checkstring(L, 2));
5933 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5934 return 0;
5935}
5936
5937__LJMP static int hlua_txn_log_info(lua_State *L)
5938{
5939 const char *msg;
5940 struct hlua_txn *htxn;
5941
5942 MAY_LJMP(check_args(L, 2, "Info"));
5943 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5944 msg = MAY_LJMP(luaL_checkstring(L, 2));
5945 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5946 return 0;
5947}
5948
5949__LJMP static int hlua_txn_log_warning(lua_State *L)
5950{
5951 const char *msg;
5952 struct hlua_txn *htxn;
5953
5954 MAY_LJMP(check_args(L, 2, "Warning"));
5955 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5956 msg = MAY_LJMP(luaL_checkstring(L, 2));
5957 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5958 return 0;
5959}
5960
5961__LJMP static int hlua_txn_log_alert(lua_State *L)
5962{
5963 const char *msg;
5964 struct hlua_txn *htxn;
5965
5966 MAY_LJMP(check_args(L, 2, "Alert"));
5967 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5968 msg = MAY_LJMP(luaL_checkstring(L, 2));
5969 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5970 return 0;
5971}
5972
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005973__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5974{
5975 struct hlua_txn *htxn;
5976 int ll;
5977
5978 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5979 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5980 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5981
5982 if (ll < 0 || ll > 7)
5983 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5984
5985 htxn->s->logs.level = ll;
5986 return 0;
5987}
5988
5989__LJMP static int hlua_txn_set_tos(lua_State *L)
5990{
5991 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005992 int tos;
5993
5994 MAY_LJMP(check_args(L, 2, "set_tos"));
5995 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5996 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5997
Willy Tarreau1a18b542018-12-11 16:37:42 +01005998 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005999 return 0;
6000}
6001
6002__LJMP static int hlua_txn_set_mark(lua_State *L)
6003{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006004 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006005 int mark;
6006
6007 MAY_LJMP(check_args(L, 2, "set_mark"));
6008 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6009 mark = MAY_LJMP(luaL_checkinteger(L, 2));
6010
Willy Tarreau1a18b542018-12-11 16:37:42 +01006011 conn_set_tos(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006012 return 0;
6013}
6014
Patrick Hemmer268a7072018-05-11 12:52:31 -04006015__LJMP static int hlua_txn_set_priority_class(lua_State *L)
6016{
6017 struct hlua_txn *htxn;
6018
6019 MAY_LJMP(check_args(L, 2, "set_priority_class"));
6020 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6021 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
6022 return 0;
6023}
6024
6025__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
6026{
6027 struct hlua_txn *htxn;
6028
6029 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
6030 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6031 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
6032 return 0;
6033}
6034
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006035/* This function is an Lua binding that send pending data
6036 * to the client, and close the stream interface.
6037 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006038__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006039{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006040 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006041 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01006042 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006043
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006044 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006045 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006046 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006047
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006048 /* If the flags NOTERM is set, we cannot terminate the http
6049 * session, so we just end the execution of the current
6050 * lua code.
6051 */
6052 if (htxn->flags & HLUA_TXN_NOTERM) {
6053 WILL_LJMP(hlua_done(L));
6054 return 0;
6055 }
6056
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006057 ic = &htxn->s->req;
6058 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01006059
Willy Tarreau630ef452015-08-28 10:06:15 +02006060 if (htxn->s->txn) {
6061 /* HTTP mode, let's stay in sync with the stream */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02006062 b_del(&ic->buf, htxn->s->txn->req.sov);
Willy Tarreau630ef452015-08-28 10:06:15 +02006063 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
6064 htxn->s->txn->req.sov = 0;
6065 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
6066 oc->analysers = AN_RES_HTTP_XFER_BODY;
6067 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
6068 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
6069
Willy Tarreau630ef452015-08-28 10:06:15 +02006070 /* Note that if we want to support keep-alive, we need
6071 * to bypass the close/shutr_now calls below, but that
6072 * may only be done if the HTTP request was already
6073 * processed and the connection header is known (ie
6074 * not during TCP rules).
6075 */
6076 }
6077
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006078 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01006079 channel_abort(ic);
6080 channel_auto_close(ic);
6081 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006082
6083 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01006084 channel_auto_read(oc);
6085 channel_auto_close(oc);
6086 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006087
Willy Tarreau0458b082015-08-28 09:40:04 +02006088 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006089
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006090 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006091 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006092 return 0;
6093}
6094
6095__LJMP static int hlua_log(lua_State *L)
6096{
6097 int level;
6098 const char *msg;
6099
6100 MAY_LJMP(check_args(L, 2, "log"));
6101 level = MAY_LJMP(luaL_checkinteger(L, 1));
6102 msg = MAY_LJMP(luaL_checkstring(L, 2));
6103
6104 if (level < 0 || level >= NB_LOG_LEVELS)
6105 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
6106
6107 hlua_sendlog(NULL, level, msg);
6108 return 0;
6109}
6110
6111__LJMP static int hlua_log_debug(lua_State *L)
6112{
6113 const char *msg;
6114
6115 MAY_LJMP(check_args(L, 1, "debug"));
6116 msg = MAY_LJMP(luaL_checkstring(L, 1));
6117 hlua_sendlog(NULL, LOG_DEBUG, msg);
6118 return 0;
6119}
6120
6121__LJMP static int hlua_log_info(lua_State *L)
6122{
6123 const char *msg;
6124
6125 MAY_LJMP(check_args(L, 1, "info"));
6126 msg = MAY_LJMP(luaL_checkstring(L, 1));
6127 hlua_sendlog(NULL, LOG_INFO, msg);
6128 return 0;
6129}
6130
6131__LJMP static int hlua_log_warning(lua_State *L)
6132{
6133 const char *msg;
6134
6135 MAY_LJMP(check_args(L, 1, "warning"));
6136 msg = MAY_LJMP(luaL_checkstring(L, 1));
6137 hlua_sendlog(NULL, LOG_WARNING, msg);
6138 return 0;
6139}
6140
6141__LJMP static int hlua_log_alert(lua_State *L)
6142{
6143 const char *msg;
6144
6145 MAY_LJMP(check_args(L, 1, "alert"));
6146 msg = MAY_LJMP(luaL_checkstring(L, 1));
6147 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006148 return 0;
6149}
6150
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006151__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006152{
6153 int wakeup_ms = lua_tointeger(L, -1);
6154 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02006155 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006156 return 0;
6157}
6158
6159__LJMP static int hlua_sleep(lua_State *L)
6160{
6161 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006162 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006163
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006164 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006165
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006166 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006167 wakeup_ms = tick_add(now_ms, delay);
6168 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006169
Willy Tarreau9635e032018-10-16 17:52:55 +02006170 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006171 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006172}
6173
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006174__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006175{
6176 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006177 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006178
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006179 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006180
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006181 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006182 wakeup_ms = tick_add(now_ms, delay);
6183 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006184
Willy Tarreau9635e032018-10-16 17:52:55 +02006185 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006186 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006187}
6188
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006189/* This functionis an LUA binding. it permits to give back
6190 * the hand at the HAProxy scheduler. It is used when the
6191 * LUA processing consumes a lot of time.
6192 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006193__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006194{
6195 return 0;
6196}
6197
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006198__LJMP static int hlua_yield(lua_State *L)
6199{
Willy Tarreau9635e032018-10-16 17:52:55 +02006200 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006201 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006202}
6203
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006204/* This function change the nice of the currently executed
6205 * task. It is used set low or high priority at the current
6206 * task.
6207 */
Willy Tarreau59551662015-03-10 14:23:13 +01006208__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006209{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006210 struct hlua *hlua;
6211 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006212
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006213 MAY_LJMP(check_args(L, 1, "set_nice"));
6214 hlua = hlua_gethlua(L);
6215 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006216
6217 /* If he task is not set, I'm in a start mode. */
6218 if (!hlua || !hlua->task)
6219 return 0;
6220
6221 if (nice < -1024)
6222 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006223 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006224 nice = 1024;
6225
6226 hlua->task->nice = nice;
6227 return 0;
6228}
6229
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006230/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006231 * HAProxy task subsystem when the task is awaked. The LUA runtime can
6232 * return an E_AGAIN signal, the emmiter of this signal must set a
6233 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006234 *
6235 * Task wrapper are longjmp safe because the only one Lua code
6236 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006237 */
Olivier Houchard9f6af332018-05-25 14:04:04 +02006238static struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006239{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006240 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006241 enum hlua_exec status;
6242
Christopher Faulet5bc99722018-04-25 10:34:45 +02006243 if (task->thread_mask == MAX_THREADS_MASK)
6244 task_set_affinity(task, tid_bit);
6245
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006246 /* If it is the first call to the task, we must initialize the
6247 * execution timeouts.
6248 */
6249 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006250 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006251
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006252 /* Execute the Lua code. */
6253 status = hlua_ctx_resume(hlua, 1);
6254
6255 switch (status) {
6256 /* finished or yield */
6257 case HLUA_E_OK:
6258 hlua_ctx_destroy(hlua);
6259 task_delete(task);
6260 task_free(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006261 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006262 break;
6263
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006264 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006265 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006266 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006267 break;
6268
6269 /* finished with error. */
6270 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006271 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006272 hlua_ctx_destroy(hlua);
6273 task_delete(task);
6274 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006275 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006276 break;
6277
6278 case HLUA_E_ERR:
6279 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006280 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006281 hlua_ctx_destroy(hlua);
6282 task_delete(task);
6283 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006284 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006285 break;
6286 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006287 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006288}
6289
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006290/* This function is an LUA binding that register LUA function to be
6291 * executed after the HAProxy configuration parsing and before the
6292 * HAProxy scheduler starts. This function expect only one LUA
6293 * argument that is a function. This function returns nothing, but
6294 * throws if an error is encountered.
6295 */
6296__LJMP static int hlua_register_init(lua_State *L)
6297{
6298 struct hlua_init_function *init;
6299 int ref;
6300
6301 MAY_LJMP(check_args(L, 1, "register_init"));
6302
6303 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6304
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006305 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006306 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006307 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006308
6309 init->function_ref = ref;
6310 LIST_ADDQ(&hlua_init_functions, &init->l);
6311 return 0;
6312}
6313
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006314/* This functio is an LUA binding. It permits to register a task
6315 * executed in parallel of the main HAroxy activity. The task is
6316 * created and it is set in the HAProxy scheduler. It can be called
6317 * from the "init" section, "post init" or during the runtime.
6318 *
6319 * Lua prototype:
6320 *
6321 * <none> core.register_task(<function>)
6322 */
6323static int hlua_register_task(lua_State *L)
6324{
6325 struct hlua *hlua;
6326 struct task *task;
6327 int ref;
6328
6329 MAY_LJMP(check_args(L, 1, "register_task"));
6330
6331 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6332
Willy Tarreaubafbe012017-11-24 17:34:44 +01006333 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006334 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006335 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006336
Emeric Brunc60def82017-09-27 14:59:38 +02006337 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006338 if (!task)
6339 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6340
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006341 task->context = hlua;
6342 task->process = hlua_process_task;
6343
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006344 if (!hlua_ctx_init(hlua, task, 1))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006345 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006346
6347 /* Restore the function in the stack. */
6348 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6349 hlua->nargs = 0;
6350
6351 /* Schedule task. */
6352 task_schedule(task, now_ms);
6353
6354 return 0;
6355}
6356
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006357/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6358 * doesn't allow "yield" functions because the HAProxy engine cannot
6359 * resume converters.
6360 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006361static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006362{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006363 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006364 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006365 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006366
Willy Tarreaube508f12016-03-10 11:47:01 +01006367 if (!stream)
6368 return 0;
6369
Willy Tarreau87b09662015-04-03 00:22:06 +02006370 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006371 * Lua context can be not initialized. This behavior
6372 * permits to save performances because a systematic
6373 * Lua initialization cause 5% performances loss.
6374 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006375 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006376 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006377 if (!stream->hlua) {
6378 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6379 return 0;
6380 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006381 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006382 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6383 return 0;
6384 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006385 }
6386
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006387 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006388 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006389
6390 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006391 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6392 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6393 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006394 else
6395 error = "critical error";
6396 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006397 return 0;
6398 }
6399
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006400 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006401 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006402 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006403 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006404 return 0;
6405 }
6406
6407 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006408 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006409
6410 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006411 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006412 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006413 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006414 return 0;
6415 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006416 hlua_smp2lua(stream->hlua->T, smp);
6417 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006418
6419 /* push keywords in the stack. */
6420 if (arg_p) {
6421 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006422 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006423 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006424 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006425 return 0;
6426 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006427 hlua_arg2lua(stream->hlua->T, arg_p);
6428 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006429 }
6430 }
6431
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006432 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006433 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006434
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006435 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006436 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006437 }
6438
6439 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006440 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006441 /* finished. */
6442 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006443 /* If the stack is empty, the function fails. */
6444 if (lua_gettop(stream->hlua->T) <= 0)
6445 return 0;
6446
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006447 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006448 hlua_lua2smp(stream->hlua->T, -1, smp);
6449 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006450 return 1;
6451
6452 /* yield. */
6453 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006454 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006455 return 0;
6456
6457 /* finished with error. */
6458 case HLUA_E_ERRMSG:
6459 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006460 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006461 fcn->name, lua_tostring(stream->hlua->T, -1));
6462 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006463 return 0;
6464
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006465 case HLUA_E_ETMOUT:
6466 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6467 return 0;
6468
6469 case HLUA_E_NOMEM:
6470 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6471 return 0;
6472
6473 case HLUA_E_YIELD:
6474 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6475 return 0;
6476
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006477 case HLUA_E_ERR:
6478 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006479 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006480
6481 default:
6482 return 0;
6483 }
6484}
6485
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006486/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6487 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006488 * resume sample-fetches. This function will be called by the sample
6489 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006490 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006491static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6492 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006493{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006494 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006495 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006496 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006497 const struct buffer msg = { };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006498
Willy Tarreaube508f12016-03-10 11:47:01 +01006499 if (!stream)
6500 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006501
Willy Tarreau87b09662015-04-03 00:22:06 +02006502 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006503 * Lua context can be not initialized. This behavior
6504 * permits to save performances because a systematic
6505 * Lua initialization cause 5% performances loss.
6506 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006507 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006508 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006509 if (!stream->hlua) {
6510 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6511 return 0;
6512 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006513 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006514 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6515 return 0;
6516 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006517 }
6518
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006519 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006520
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006521 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006522 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006523
6524 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006525 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6526 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6527 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006528 else
6529 error = "critical error";
6530 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006531 return 0;
6532 }
6533
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006534 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006535 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006536 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006537 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006538 return 0;
6539 }
6540
6541 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006542 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006543
6544 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006545 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006546 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006547 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006548 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006549 return 0;
6550 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006551 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006552
6553 /* push keywords in the stack. */
6554 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6555 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006556 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006557 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006558 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006559 return 0;
6560 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006561 hlua_arg2lua(stream->hlua->T, arg_p);
6562 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006563 }
6564
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006565 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006566 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006567
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006568 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006569 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006570 }
6571
6572 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006573 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006574 /* finished. */
6575 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006576 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006577 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006578 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006579 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006580 /* If the stack is empty, the function fails. */
6581 if (lua_gettop(stream->hlua->T) <= 0)
6582 return 0;
6583
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006584 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006585 hlua_lua2smp(stream->hlua->T, -1, smp);
6586 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006587
6588 /* Set the end of execution flag. */
6589 smp->flags &= ~SMP_F_MAY_CHANGE;
6590 return 1;
6591
6592 /* yield. */
6593 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006594 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006595 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006596 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006597 return 0;
6598
6599 /* finished with error. */
6600 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006601 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006602 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006603 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006604 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006605 fcn->name, lua_tostring(stream->hlua->T, -1));
6606 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006607 return 0;
6608
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006609 case HLUA_E_ETMOUT:
6610 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006611 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006612 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6613 return 0;
6614
6615 case HLUA_E_NOMEM:
6616 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006617 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006618 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6619 return 0;
6620
6621 case HLUA_E_YIELD:
6622 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006623 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006624 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6625 return 0;
6626
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006627 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006628 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006629 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006630 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006631 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006632
6633 default:
6634 return 0;
6635 }
6636}
6637
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006638/* This function is an LUA binding used for registering
6639 * "sample-conv" functions. It expects a converter name used
6640 * in the haproxy configuration file, and an LUA function.
6641 */
6642__LJMP static int hlua_register_converters(lua_State *L)
6643{
6644 struct sample_conv_kw_list *sck;
6645 const char *name;
6646 int ref;
6647 int len;
6648 struct hlua_function *fcn;
6649
6650 MAY_LJMP(check_args(L, 2, "register_converters"));
6651
6652 /* First argument : converter name. */
6653 name = MAY_LJMP(luaL_checkstring(L, 1));
6654
6655 /* Second argument : lua function. */
6656 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6657
6658 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006659 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006660 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006661 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006662 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006663 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006664 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006665
6666 /* Fill fcn. */
6667 fcn->name = strdup(name);
6668 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006669 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006670 fcn->function_ref = ref;
6671
6672 /* List head */
6673 sck->list.n = sck->list.p = NULL;
6674
6675 /* converter keyword. */
6676 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006677 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006678 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006679 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006680
6681 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6682 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006683 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 +01006684 sck->kw[0].val_args = NULL;
6685 sck->kw[0].in_type = SMP_T_STR;
6686 sck->kw[0].out_type = SMP_T_STR;
6687 sck->kw[0].private = fcn;
6688
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006689 /* Register this new converter */
6690 sample_register_convs(sck);
6691
6692 return 0;
6693}
6694
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006695/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006696 * "sample-fetch" functions. It expects a converter name used
6697 * in the haproxy configuration file, and an LUA function.
6698 */
6699__LJMP static int hlua_register_fetches(lua_State *L)
6700{
6701 const char *name;
6702 int ref;
6703 int len;
6704 struct sample_fetch_kw_list *sfk;
6705 struct hlua_function *fcn;
6706
6707 MAY_LJMP(check_args(L, 2, "register_fetches"));
6708
6709 /* First argument : sample-fetch name. */
6710 name = MAY_LJMP(luaL_checkstring(L, 1));
6711
6712 /* Second argument : lua function. */
6713 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6714
6715 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006716 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006717 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006718 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006719 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006720 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006721 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006722
6723 /* Fill fcn. */
6724 fcn->name = strdup(name);
6725 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006726 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006727 fcn->function_ref = ref;
6728
6729 /* List head */
6730 sfk->list.n = sfk->list.p = NULL;
6731
6732 /* sample-fetch keyword. */
6733 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006734 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006735 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006736 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006737
6738 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6739 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006740 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 +01006741 sfk->kw[0].val_args = NULL;
6742 sfk->kw[0].out_type = SMP_T_STR;
6743 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6744 sfk->kw[0].val = 0;
6745 sfk->kw[0].private = fcn;
6746
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006747 /* Register this new fetch. */
6748 sample_register_fetches(sfk);
6749
6750 return 0;
6751}
6752
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006753/* This function is a wrapper to execute each LUA function declared
6754 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006755 * return ACT_RET_CONT if the processing is finished (with or without
6756 * error) and return ACT_RET_YIELD if the function must be called again
6757 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006758 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006759static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006760 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006761{
6762 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006763 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006764 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006765 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006766 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006767
6768 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006769 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6770 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6771 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6772 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006773 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006774 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006775 return ACT_RET_CONT;
6776 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006777
Willy Tarreau87b09662015-04-03 00:22:06 +02006778 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006779 * Lua context can be not initialized. This behavior
6780 * permits to save performances because a systematic
6781 * Lua initialization cause 5% performances loss.
6782 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006783 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006784 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006785 if (!s->hlua) {
6786 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6787 rule->arg.hlua_rule->fcn.name);
6788 return ACT_RET_CONT;
6789 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006790 if (!hlua_ctx_init(s->hlua, s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006791 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6792 rule->arg.hlua_rule->fcn.name);
6793 return ACT_RET_CONT;
6794 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006795 }
6796
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006797 consistency_set(s, dir, &s->hlua->cons);
6798
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006799 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006800 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006801
6802 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006803 if (!SET_SAFE_LJMP(s->hlua->T)) {
6804 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6805 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006806 else
6807 error = "critical error";
6808 SEND_ERR(px, "Lua function '%s': %s.\n",
6809 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006810 return ACT_RET_CONT;
6811 }
6812
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006813 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006814 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006815 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006816 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006817 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006818 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006819 }
6820
6821 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006822 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006823
Willy Tarreau87b09662015-04-03 00:22:06 +02006824 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006825 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006826 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006827 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006828 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006829 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006830 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006831 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006832
6833 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006834 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006835 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006836 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006837 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006838 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006839 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006840 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006841 lua_pushstring(s->hlua->T, *arg);
6842 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006843 }
6844
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006845 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006846 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006847
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006848 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006849 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006850 }
6851
6852 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006853 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006854 /* finished. */
6855 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006856 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006857 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006858 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006859 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006860 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006861 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006862 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006863
6864 /* yield. */
6865 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006866 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006867 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006868 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006869 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006870 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006871 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006872 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006873 /* Some actions can be wake up when a "write" event
6874 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006875 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006876 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006877 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006878 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006879 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006880 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006881 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006882 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006883 s->req.flags |= CF_WAKE_WRITE;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006884 /* We can quit the function without consistency check
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006885 * because HAProxy is not able to manipulate data, it
6886 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006887 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006888
6889 /* finished with error. */
6890 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006891 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006892 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006893 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006894 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006895 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006896 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006897 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6898 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006899 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006900
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006901 case HLUA_E_ETMOUT:
6902 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006903 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006904 return ACT_RET_ERR;
6905 }
6906 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6907 return 0;
6908
6909 case HLUA_E_NOMEM:
6910 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006911 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006912 return ACT_RET_ERR;
6913 }
6914 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6915 return 0;
6916
6917 case HLUA_E_YIELD:
6918 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006919 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006920 return ACT_RET_ERR;
6921 }
6922 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6923 rule->arg.hlua_rule->fcn.name);
6924 return 0;
6925
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006926 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006927 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006928 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006929 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006930 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006931 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006932 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006933 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006934
6935 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006936 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006937 }
6938}
6939
Olivier Houchard9f6af332018-05-25 14:04:04 +02006940struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006941{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006942 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006943
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006944 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006945 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006946 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006947}
6948
6949static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6950{
6951 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006952 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006953 struct task *task;
6954 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006955 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006956
Willy Tarreaubafbe012017-11-24 17:34:44 +01006957 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006958 if (!hlua) {
6959 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6960 ctx->rule->arg.hlua_rule->fcn.name);
6961 return 0;
6962 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006963 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006964 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006965 ctx->ctx.hlua_apptcp.flags = 0;
6966
6967 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006968 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006969 if (!task) {
6970 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6971 ctx->rule->arg.hlua_rule->fcn.name);
6972 return 0;
6973 }
6974 task->nice = 0;
6975 task->context = ctx;
6976 task->process = hlua_applet_wakeup;
6977 ctx->ctx.hlua_apptcp.task = task;
6978
6979 /* In the execution wrappers linked with a stream, the
6980 * Lua context can be not initialized. This behavior
6981 * permits to save performances because a systematic
6982 * Lua initialization cause 5% performances loss.
6983 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006984 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006985 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6986 ctx->rule->arg.hlua_rule->fcn.name);
6987 return 0;
6988 }
6989
6990 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006991 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006992
6993 /* The following Lua calls can fail. */
6994 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006995 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6996 error = lua_tostring(hlua->T, -1);
6997 else
6998 error = "critical error";
6999 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7000 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007001 return 0;
7002 }
7003
7004 /* Check stack available size. */
7005 if (!lua_checkstack(hlua->T, 1)) {
7006 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7007 ctx->rule->arg.hlua_rule->fcn.name);
7008 RESET_SAFE_LJMP(hlua->T);
7009 return 0;
7010 }
7011
7012 /* Restore the function in the stack. */
7013 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7014
7015 /* Create and and push object stream in the stack. */
7016 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
7017 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7018 ctx->rule->arg.hlua_rule->fcn.name);
7019 RESET_SAFE_LJMP(hlua->T);
7020 return 0;
7021 }
7022 hlua->nargs = 1;
7023
7024 /* push keywords in the stack. */
7025 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7026 if (!lua_checkstack(hlua->T, 1)) {
7027 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7028 ctx->rule->arg.hlua_rule->fcn.name);
7029 RESET_SAFE_LJMP(hlua->T);
7030 return 0;
7031 }
7032 lua_pushstring(hlua->T, *arg);
7033 hlua->nargs++;
7034 }
7035
7036 RESET_SAFE_LJMP(hlua->T);
7037
7038 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007039 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01007040 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007041
7042 return 1;
7043}
7044
7045static void hlua_applet_tcp_fct(struct appctx *ctx)
7046{
7047 struct stream_interface *si = ctx->owner;
7048 struct stream *strm = si_strm(si);
7049 struct channel *res = si_ic(si);
7050 struct act_rule *rule = ctx->rule;
7051 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007052 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007053
7054 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02007055 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
7056 /* eat the whole request */
7057 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007058 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02007059 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007060
7061 /* If the stream is disconnect or closed, ldo nothing. */
7062 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7063 return;
7064
7065 /* Execute the function. */
7066 switch (hlua_ctx_resume(hlua, 1)) {
7067 /* finished. */
7068 case HLUA_E_OK:
7069 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7070
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007071 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007072 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007073 res->flags |= CF_READ_NULL;
7074 si_shutr(si);
7075 return;
7076
7077 /* yield. */
7078 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007079 if (hlua->wake_time != TICK_ETERNITY)
7080 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007081 return;
7082
7083 /* finished with error. */
7084 case HLUA_E_ERRMSG:
7085 /* Display log. */
7086 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7087 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7088 lua_pop(hlua->T, 1);
7089 goto error;
7090
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007091 case HLUA_E_ETMOUT:
7092 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
7093 rule->arg.hlua_rule->fcn.name);
7094 goto error;
7095
7096 case HLUA_E_NOMEM:
7097 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
7098 rule->arg.hlua_rule->fcn.name);
7099 goto error;
7100
7101 case HLUA_E_YIELD: /* unexpected */
7102 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
7103 rule->arg.hlua_rule->fcn.name);
7104 goto error;
7105
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007106 case HLUA_E_ERR:
7107 /* Display log. */
7108 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
7109 rule->arg.hlua_rule->fcn.name);
7110 goto error;
7111
7112 default:
7113 goto error;
7114 }
7115
7116error:
7117
7118 /* For all other cases, just close the stream. */
7119 si_shutw(si);
7120 si_shutr(si);
7121 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7122}
7123
7124static void hlua_applet_tcp_release(struct appctx *ctx)
7125{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02007126 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007127 task_free(ctx->ctx.hlua_apptcp.task);
7128 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007129 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007130 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007131}
7132
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007133/* The function returns 1 if the initialisation is complete, 0 if
7134 * an errors occurs and -1 if more data are required for initializing
7135 * the applet.
7136 */
7137static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7138{
7139 struct stream_interface *si = ctx->owner;
7140 struct channel *req = si_oc(si);
7141 struct http_msg *msg;
7142 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007143 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007144 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007145 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007146 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007147
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007148 txn = strm->txn;
7149 msg = &txn->req;
7150
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007151 /* We want two things in HTTP mode :
7152 * - enforce server-close mode if we were in keep-alive, so that the
7153 * applet is released after each response ;
7154 * - enable request body transfer to the applet in order to resync
7155 * with the response body.
7156 */
7157 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
7158 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007159
Willy Tarreaubafbe012017-11-24 17:34:44 +01007160 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007161 if (!hlua) {
7162 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7163 ctx->rule->arg.hlua_rule->fcn.name);
7164 return 0;
7165 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007166 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007167 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007168 ctx->ctx.hlua_apphttp.left_bytes = -1;
7169 ctx->ctx.hlua_apphttp.flags = 0;
7170
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01007171 if (txn->req.flags & HTTP_MSGF_VER_11)
7172 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
7173
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007174 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007175 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007176 if (!task) {
7177 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7178 ctx->rule->arg.hlua_rule->fcn.name);
7179 return 0;
7180 }
7181 task->nice = 0;
7182 task->context = ctx;
7183 task->process = hlua_applet_wakeup;
7184 ctx->ctx.hlua_apphttp.task = task;
7185
7186 /* In the execution wrappers linked with a stream, the
7187 * Lua context can be not initialized. This behavior
7188 * permits to save performances because a systematic
7189 * Lua initialization cause 5% performances loss.
7190 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007191 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007192 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
7193 ctx->rule->arg.hlua_rule->fcn.name);
7194 return 0;
7195 }
7196
7197 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007198 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007199
7200 /* The following Lua calls can fail. */
7201 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007202 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7203 error = lua_tostring(hlua->T, -1);
7204 else
7205 error = "critical error";
7206 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7207 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007208 return 0;
7209 }
7210
7211 /* Check stack available size. */
7212 if (!lua_checkstack(hlua->T, 1)) {
7213 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7214 ctx->rule->arg.hlua_rule->fcn.name);
7215 RESET_SAFE_LJMP(hlua->T);
7216 return 0;
7217 }
7218
7219 /* Restore the function in the stack. */
7220 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7221
7222 /* Create and and push object stream in the stack. */
7223 if (!hlua_applet_http_new(hlua->T, ctx)) {
7224 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7225 ctx->rule->arg.hlua_rule->fcn.name);
7226 RESET_SAFE_LJMP(hlua->T);
7227 return 0;
7228 }
7229 hlua->nargs = 1;
7230
7231 /* Look for a 100-continue expected. */
7232 if (msg->flags & HTTP_MSGF_VER_11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007233 if (IS_HTX_STRM(si_strm(si))) {
7234 /* HTX version */
7235 struct htx *htx = htxbuf(&req->buf);
7236 struct ist hdr = { .ptr = "Expect", .len = 6 };
7237 struct http_hdr_ctx hdr_ctx;
7238
7239 hdr_ctx.blk = NULL;
7240 /* Expect is allowed in 1.1, look for it */
7241 if (http_find_header(htx, hdr, &hdr_ctx, 0) &&
7242 unlikely(isteqi(hdr_ctx.value, ist2("100-continue", 12))))
7243 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
7244 }
7245 else {
7246 /* Legacy HTTP version */
7247 struct hdr_ctx hdr;
7248
7249 hdr.idx = 0;
7250 if (http_find_header2("Expect", 6, ci_head(req), &txn->hdr_idx, &hdr) &&
7251 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
7252 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
7253 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007254 }
7255
7256 /* push keywords in the stack. */
7257 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7258 if (!lua_checkstack(hlua->T, 1)) {
7259 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7260 ctx->rule->arg.hlua_rule->fcn.name);
7261 RESET_SAFE_LJMP(hlua->T);
7262 return 0;
7263 }
7264 lua_pushstring(hlua->T, *arg);
7265 hlua->nargs++;
7266 }
7267
7268 RESET_SAFE_LJMP(hlua->T);
7269
7270 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007271 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007272
7273 return 1;
7274}
7275
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007276static void hlua_applet_htx_fct(struct appctx *ctx)
7277{
7278 struct stream_interface *si = ctx->owner;
7279 struct stream *strm = si_strm(si);
7280 struct channel *req = si_oc(si);
7281 struct channel *res = si_ic(si);
7282 struct act_rule *rule = ctx->rule;
7283 struct proxy *px = strm->be;
7284 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
7285 struct htx *req_htx, *res_htx;
7286
7287 res_htx = htx_from_buf(&res->buf);
7288
7289 /* If the stream is disconnect or closed, ldo nothing. */
7290 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7291 goto out;
7292
7293 /* Check if the input buffer is avalaible. */
7294 if (!b_size(&res->buf)) {
7295 si_rx_room_blk(si);
7296 goto out;
7297 }
7298 /* check that the output is not closed */
7299 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW))
7300 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7301
7302 /* Set the currently running flag. */
7303 if (!HLUA_IS_RUNNING(hlua) &&
7304 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7305 struct htx_blk *blk;
7306 size_t count = co_data(req);
7307
7308 if (!count) {
7309 si_cant_get(si);
7310 goto out;
7311 }
7312
7313 /* We need to flush the request header. This left the body for
7314 * the Lua.
7315 */
7316 req_htx = htx_from_buf(&req->buf);
7317 blk = htx_get_head_blk(req_htx);
7318 while (count && blk) {
7319 enum htx_blk_type type = htx_get_blk_type(blk);
7320 uint32_t sz = htx_get_blksz(blk);
7321
7322 if (sz > count) {
7323 si_cant_get(si);
7324 goto out;
7325 }
7326
7327 count -= sz;
7328 co_set_data(req, co_data(req) - sz);
7329 blk = htx_remove_blk(req_htx, blk);
7330
7331 if (type == HTX_BLK_EOH)
7332 break;
7333 }
7334 }
7335
7336 /* Executes The applet if it is not done. */
7337 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7338
7339 /* Execute the function. */
7340 switch (hlua_ctx_resume(hlua, 1)) {
7341 /* finished. */
7342 case HLUA_E_OK:
7343 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7344 break;
7345
7346 /* yield. */
7347 case HLUA_E_AGAIN:
7348 if (hlua->wake_time != TICK_ETERNITY)
7349 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
7350 return;
7351
7352 /* finished with error. */
7353 case HLUA_E_ERRMSG:
7354 /* Display log. */
7355 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7356 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7357 lua_pop(hlua->T, 1);
7358 goto error;
7359
7360 case HLUA_E_ETMOUT:
7361 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7362 rule->arg.hlua_rule->fcn.name);
7363 goto error;
7364
7365 case HLUA_E_NOMEM:
7366 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7367 rule->arg.hlua_rule->fcn.name);
7368 goto error;
7369
7370 case HLUA_E_YIELD: /* unexpected */
7371 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7372 rule->arg.hlua_rule->fcn.name);
7373 goto error;
7374
7375 case HLUA_E_ERR:
7376 /* Display log. */
7377 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7378 rule->arg.hlua_rule->fcn.name);
7379 goto error;
7380
7381 default:
7382 goto error;
7383 }
7384 }
7385
7386 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7387 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7388 goto error;
7389
7390 /* Don't add EOD and TLR because mux-h1 will take care of it */
7391 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
7392 si_rx_room_blk(si);
7393 goto out;
7394 }
7395 res->total++;
7396 res->flags |= CF_READ_PARTIAL;
7397 }
7398
7399 done:
7400 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7401 /* eat the whole request */
7402 req_htx = htxbuf(&req->buf);
7403 htx_reset(req_htx);
7404 htx_to_buf(req_htx, &req->buf);
7405 co_set_data(req, 0);
7406 res->flags |= CF_READ_NULL;
7407 si_shutr(si);
7408 }
7409
7410 if ((res->flags & CF_SHUTR) && (si->state == SI_ST_EST))
7411 si_shutw(si);
7412
7413 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7414 if ((req->flags & CF_SHUTW) && (si->state == SI_ST_EST)) {
7415 si_shutr(si);
7416 res->flags |= CF_READ_NULL;
7417 }
7418 }
7419
7420 out:
7421 /* we have left the request in the buffer for the case where we
7422 * process a POST, and this automatically re-enables activity on
7423 * read. It's better to indicate that we want to stop reading when
7424 * we're sending, so that we know there's at most one direction
7425 * deciding to wake the applet up. It saves it from looping when
7426 * emitting large blocks into small TCP windows.
7427 */
7428 htx_to_buf(res_htx, &res->buf);
7429 if (!channel_is_empty(res))
7430 si_stop_get(si);
7431 return;
7432
7433 error:
7434
7435 /* If we are in HTTP mode, and we are not send any
7436 * data, return a 500 server error in best effort:
7437 * if there is no room available in the buffer,
7438 * just close the connection.
7439 */
7440 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7441 struct buffer *err = &htx_err_chunks[HTTP_ERR_500];
7442
7443 channel_erase(res);
7444 res->buf.data = b_data(err);
7445 memcpy(res->buf.area, b_head(err), b_data(err));
7446 res_htx = htx_from_buf(&res->buf);
7447
7448 res->total += res_htx->data;
7449 res->flags |= CF_READ_PARTIAL;
7450 }
7451 if (!(strm->flags & SF_ERR_MASK))
7452 strm->flags |= SF_ERR_RESOURCE;
7453 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7454 goto done;
7455}
7456
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007457static void hlua_applet_http_fct(struct appctx *ctx)
7458{
7459 struct stream_interface *si = ctx->owner;
7460 struct stream *strm = si_strm(si);
7461 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007462 struct act_rule *rule = ctx->rule;
7463 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007464 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02007465 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007466 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02007467 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007468 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007469 int ret;
7470
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007471 if (IS_HTX_STRM(strm))
7472 return hlua_applet_htx_fct(ctx);
7473
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007474 /* If the stream is disconnect or closed, ldo nothing. */
7475 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7476 return;
7477
7478 /* Set the currently running flag. */
7479 if (!HLUA_IS_RUNNING(hlua) &&
7480 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007481 /* Store the max amount of bytes that we can read. */
7482 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
7483
7484 /* We need to flush the request header. This left the body
7485 * for the Lua.
7486 */
7487
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007488 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007489 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007490 if (ret == -1)
7491 return;
7492
7493 /* No data available, ask for more data. */
7494 if (ret == 1)
7495 len2 = 0;
7496 if (ret == 0)
7497 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02007498 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007499 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007500 return;
7501 }
7502
7503 /* skip the requests bytes. */
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02007504 co_skip(si_oc(si), strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007505 }
7506
7507 /* Executes The applet if it is not done. */
7508 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7509
7510 /* Execute the function. */
7511 switch (hlua_ctx_resume(hlua, 1)) {
7512 /* finished. */
7513 case HLUA_E_OK:
7514 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7515 break;
7516
7517 /* yield. */
7518 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007519 if (hlua->wake_time != TICK_ETERNITY)
7520 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007521 return;
7522
7523 /* finished with error. */
7524 case HLUA_E_ERRMSG:
7525 /* Display log. */
7526 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7527 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7528 lua_pop(hlua->T, 1);
7529 goto error;
7530
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007531 case HLUA_E_ETMOUT:
7532 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7533 rule->arg.hlua_rule->fcn.name);
7534 goto error;
7535
7536 case HLUA_E_NOMEM:
7537 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7538 rule->arg.hlua_rule->fcn.name);
7539 goto error;
7540
7541 case HLUA_E_YIELD: /* unexpected */
7542 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7543 rule->arg.hlua_rule->fcn.name);
7544 goto error;
7545
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007546 case HLUA_E_ERR:
7547 /* Display log. */
7548 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7549 rule->arg.hlua_rule->fcn.name);
7550 goto error;
7551
7552 default:
7553 goto error;
7554 }
7555 }
7556
7557 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Fauletcc26b132018-12-18 21:20:57 +01007558 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7559 goto error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007560
7561 /* We must send the final chunk. */
7562 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
7563 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
7564
7565 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007566 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007567
7568 /* critical error. */
7569 if (ret == -2 || ret == -3) {
7570 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
7571 rule->arg.hlua_rule->fcn.name);
7572 goto error;
7573 }
7574
7575 /* no enough space error. */
7576 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01007577 si_rx_room_blk(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007578 return;
7579 }
7580
7581 /* set the last chunk sent. */
7582 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
7583 }
7584
7585 /* close the connection. */
7586
Frédéric Lécaille83ed5d52018-07-18 14:25:26 +02007587 /* status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007588 strm->txn->status = ctx->ctx.hlua_apphttp.status;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007589
7590 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007591 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007592 res->flags |= CF_READ_NULL;
7593 si_shutr(si);
7594
7595 return;
7596 }
7597
7598error:
7599
7600 /* If we are in HTTP mode, and we are not send any
7601 * data, return a 500 server error in best effort:
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007602 * if there is no room available in the buffer,
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007603 * just close the connection.
7604 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007605 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007606 if (!(strm->flags & SF_ERR_MASK))
7607 strm->flags |= SF_ERR_RESOURCE;
7608 si_shutw(si);
7609 si_shutr(si);
7610 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7611}
7612
7613static void hlua_applet_http_release(struct appctx *ctx)
7614{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02007615 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007616 task_free(ctx->ctx.hlua_apphttp.task);
7617 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007618 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007619 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007620}
7621
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007622/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
7623 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007624 *
7625 * This function can fail with an abort() due to an Lua critical error.
7626 * We are in the configuration parsing process of HAProxy, this abort() is
7627 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007628 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007629static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7630 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007631{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007632 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007633 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007634
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007635 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007636 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007637 if (!rule->arg.hlua_rule) {
7638 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007639 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007640 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007641
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007642 /* Memory for arguments. */
7643 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
7644 if (!rule->arg.hlua_rule->args) {
7645 memprintf(err, "out of memory error");
7646 return ACT_RET_PRS_ERR;
7647 }
7648
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007649 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007650 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007651
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007652 /* Expect some arguments */
7653 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007654 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007655 memprintf(err, "expect %d arguments", fcn->nargs);
7656 return ACT_RET_PRS_ERR;
7657 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007658 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007659 if (!rule->arg.hlua_rule->args[i]) {
7660 memprintf(err, "out of memory error");
7661 return ACT_RET_PRS_ERR;
7662 }
7663 (*cur_arg)++;
7664 }
7665 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007666
Thierry FOURNIER42148732015-09-02 17:17:33 +02007667 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007668 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007669 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007670}
7671
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007672static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7673 struct act_rule *rule, char **err)
7674{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007675 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007676
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007677 /* HTTP applets are forbidden in tcp-request rules.
7678 * HTTP applet request requires everything initilized by
7679 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
7680 * The applet will be immediately initilized, but its before
7681 * the call of this analyzer.
7682 */
7683 if (rule->from != ACT_F_HTTP_REQ) {
7684 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7685 return ACT_RET_PRS_ERR;
7686 }
7687
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007688 /* Memory for the rule. */
7689 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7690 if (!rule->arg.hlua_rule) {
7691 memprintf(err, "out of memory error");
7692 return ACT_RET_PRS_ERR;
7693 }
7694
7695 /* Reference the Lua function and store the reference. */
7696 rule->arg.hlua_rule->fcn = *fcn;
7697
7698 /* TODO: later accept arguments. */
7699 rule->arg.hlua_rule->args = NULL;
7700
7701 /* Add applet pointer in the rule. */
7702 rule->applet.obj_type = OBJ_TYPE_APPLET;
7703 rule->applet.name = fcn->name;
7704 rule->applet.init = hlua_applet_http_init;
7705 rule->applet.fct = hlua_applet_http_fct;
7706 rule->applet.release = hlua_applet_http_release;
7707 rule->applet.timeout = hlua_timeout_applet;
7708
7709 return ACT_RET_PRS_OK;
7710}
7711
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007712/* This function is an LUA binding used for registering
7713 * "sample-conv" functions. It expects a converter name used
7714 * in the haproxy configuration file, and an LUA function.
7715 */
7716__LJMP static int hlua_register_action(lua_State *L)
7717{
7718 struct action_kw_list *akl;
7719 const char *name;
7720 int ref;
7721 int len;
7722 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007723 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007724
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007725 /* Initialise the number of expected arguments at 0. */
7726 nargs = 0;
7727
7728 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7729 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007730
7731 /* First argument : converter name. */
7732 name = MAY_LJMP(luaL_checkstring(L, 1));
7733
7734 /* Second argument : environment. */
7735 if (lua_type(L, 2) != LUA_TTABLE)
7736 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7737
7738 /* Third argument : lua function. */
7739 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7740
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007741 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007742 if (lua_gettop(L) >= 4)
7743 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7744
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007745 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007746 lua_pushnil(L);
7747 while (lua_next(L, 2) != 0) {
7748 if (lua_type(L, -1) != LUA_TSTRING)
7749 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7750
7751 /* Check required environment. Only accepted "http" or "tcp". */
7752 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007753 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007754 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007755 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007756 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007757 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007758 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007759
7760 /* Fill fcn. */
7761 fcn->name = strdup(name);
7762 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007763 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007764 fcn->function_ref = ref;
7765
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007766 /* Set the expected number od arguments. */
7767 fcn->nargs = nargs;
7768
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007769 /* List head */
7770 akl->list.n = akl->list.p = NULL;
7771
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007772 /* action keyword. */
7773 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007774 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007775 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007776 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007777
7778 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7779
7780 akl->kw[0].match_pfx = 0;
7781 akl->kw[0].private = fcn;
7782 akl->kw[0].parse = action_register_lua;
7783
7784 /* select the action registering point. */
7785 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7786 tcp_req_cont_keywords_register(akl);
7787 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7788 tcp_res_cont_keywords_register(akl);
7789 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7790 http_req_keywords_register(akl);
7791 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7792 http_res_keywords_register(akl);
7793 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007794 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007795 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7796 "are expected.", lua_tostring(L, -1)));
7797
7798 /* pop the environment string. */
7799 lua_pop(L, 1);
7800 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007801 return ACT_RET_PRS_OK;
7802}
7803
7804static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7805 struct act_rule *rule, char **err)
7806{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007807 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007808
Christopher Fauletafd8f102018-11-08 11:34:21 +01007809 if (px->options2 & PR_O2_USE_HTX) {
7810 memprintf(err, "Lua services cannot be used when the HTX internal representation is enabled");
7811 return ACT_RET_PRS_ERR;
7812 }
7813
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007814 /* Memory for the rule. */
7815 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7816 if (!rule->arg.hlua_rule) {
7817 memprintf(err, "out of memory error");
7818 return ACT_RET_PRS_ERR;
7819 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007820
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007821 /* Reference the Lua function and store the reference. */
7822 rule->arg.hlua_rule->fcn = *fcn;
7823
7824 /* TODO: later accept arguments. */
7825 rule->arg.hlua_rule->args = NULL;
7826
7827 /* Add applet pointer in the rule. */
7828 rule->applet.obj_type = OBJ_TYPE_APPLET;
7829 rule->applet.name = fcn->name;
7830 rule->applet.init = hlua_applet_tcp_init;
7831 rule->applet.fct = hlua_applet_tcp_fct;
7832 rule->applet.release = hlua_applet_tcp_release;
7833 rule->applet.timeout = hlua_timeout_applet;
7834
7835 return 0;
7836}
7837
7838/* This function is an LUA binding used for registering
7839 * "sample-conv" functions. It expects a converter name used
7840 * in the haproxy configuration file, and an LUA function.
7841 */
7842__LJMP static int hlua_register_service(lua_State *L)
7843{
7844 struct action_kw_list *akl;
7845 const char *name;
7846 const char *env;
7847 int ref;
7848 int len;
7849 struct hlua_function *fcn;
7850
7851 MAY_LJMP(check_args(L, 3, "register_service"));
7852
7853 /* First argument : converter name. */
7854 name = MAY_LJMP(luaL_checkstring(L, 1));
7855
7856 /* Second argument : environment. */
7857 env = MAY_LJMP(luaL_checkstring(L, 2));
7858
7859 /* Third argument : lua function. */
7860 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7861
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007862 /* Allocate and fill the sample fetch keyword struct. */
7863 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7864 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007865 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007866 fcn = calloc(1, sizeof(*fcn));
7867 if (!fcn)
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
7870 /* Fill fcn. */
7871 len = strlen("<lua.>") + strlen(name) + 1;
7872 fcn->name = calloc(1, len);
7873 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007874 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007875 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7876 fcn->function_ref = ref;
7877
7878 /* List head */
7879 akl->list.n = akl->list.p = NULL;
7880
7881 /* converter keyword. */
7882 len = strlen("lua.") + strlen(name) + 1;
7883 akl->kw[0].kw = calloc(1, len);
7884 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007885 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007886
7887 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7888
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007889 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007890 if (strcmp(env, "tcp") == 0)
7891 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007892 else if (strcmp(env, "http") == 0)
7893 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007894 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007895 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007896 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007897
7898 akl->kw[0].match_pfx = 0;
7899 akl->kw[0].private = fcn;
7900
7901 /* End of array. */
7902 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7903
7904 /* Register this new converter */
7905 service_keywords_register(akl);
7906
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007907 return 0;
7908}
7909
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007910/* This function initialises Lua cli handler. It copies the
7911 * arguments in the Lua stack and create channel IO objects.
7912 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007913static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007914{
7915 struct hlua *hlua;
7916 struct hlua_function *fcn;
7917 int i;
7918 const char *error;
7919
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007920 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007921 appctx->ctx.hlua_cli.fcn = private;
7922
Willy Tarreaubafbe012017-11-24 17:34:44 +01007923 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007924 if (!hlua) {
7925 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007926 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007927 }
7928 HLUA_INIT(hlua);
7929 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007930
7931 /* Create task used by signal to wakeup applets.
7932 * We use the same wakeup fonction than the Lua applet_tcp and
7933 * applet_http. It is absolutely compatible.
7934 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007935 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007936 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007937 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007938 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007939 }
7940 appctx->ctx.hlua_cli.task->nice = 0;
7941 appctx->ctx.hlua_cli.task->context = appctx;
7942 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7943
7944 /* Initialises the Lua context */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007945 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007946 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007947 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007948 }
7949
7950 /* The following Lua calls can fail. */
7951 if (!SET_SAFE_LJMP(hlua->T)) {
7952 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7953 error = lua_tostring(hlua->T, -1);
7954 else
7955 error = "critical error";
7956 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7957 goto error;
7958 }
7959
7960 /* Check stack available size. */
7961 if (!lua_checkstack(hlua->T, 2)) {
7962 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7963 goto error;
7964 }
7965
7966 /* Restore the function in the stack. */
7967 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7968
7969 /* Once the arguments parsed, the CLI is like an AppletTCP,
7970 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007971 */
7972 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7973 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7974 goto error;
7975 }
7976 hlua->nargs = 1;
7977
7978 /* push keywords in the stack. */
7979 for (i = 0; *args[i]; i++) {
7980 /* Check stack available size. */
7981 if (!lua_checkstack(hlua->T, 1)) {
7982 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7983 goto error;
7984 }
7985 lua_pushstring(hlua->T, args[i]);
7986 hlua->nargs++;
7987 }
7988
7989 /* We must initialize the execution timeouts. */
7990 hlua->max_time = hlua_timeout_session;
7991
7992 /* At this point the execution is safe. */
7993 RESET_SAFE_LJMP(hlua->T);
7994
7995 /* It's ok */
7996 return 0;
7997
7998 /* It's not ok. */
7999error:
8000 RESET_SAFE_LJMP(hlua->T);
8001 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008002 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008003 return 1;
8004}
8005
8006static int hlua_cli_io_handler_fct(struct appctx *appctx)
8007{
8008 struct hlua *hlua;
8009 struct stream_interface *si;
8010 struct hlua_function *fcn;
8011
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008012 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008013 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01008014 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008015
8016 /* If the stream is disconnect or closed, ldo nothing. */
8017 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8018 return 1;
8019
8020 /* Execute the function. */
8021 switch (hlua_ctx_resume(hlua, 1)) {
8022
8023 /* finished. */
8024 case HLUA_E_OK:
8025 return 1;
8026
8027 /* yield. */
8028 case HLUA_E_AGAIN:
8029 /* We want write. */
8030 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01008031 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008032 /* Set the timeout. */
8033 if (hlua->wake_time != TICK_ETERNITY)
8034 task_schedule(hlua->task, hlua->wake_time);
8035 return 0;
8036
8037 /* finished with error. */
8038 case HLUA_E_ERRMSG:
8039 /* Display log. */
8040 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
8041 fcn->name, lua_tostring(hlua->T, -1));
8042 lua_pop(hlua->T, 1);
8043 return 1;
8044
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008045 case HLUA_E_ETMOUT:
8046 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
8047 fcn->name);
8048 return 1;
8049
8050 case HLUA_E_NOMEM:
8051 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
8052 fcn->name);
8053 return 1;
8054
8055 case HLUA_E_YIELD: /* unexpected */
8056 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
8057 fcn->name);
8058 return 1;
8059
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008060 case HLUA_E_ERR:
8061 /* Display log. */
8062 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
8063 fcn->name);
8064 return 1;
8065
8066 default:
8067 return 1;
8068 }
8069
8070 return 1;
8071}
8072
8073static void hlua_cli_io_release_fct(struct appctx *appctx)
8074{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008075 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008076 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008077}
8078
8079/* This function is an LUA binding used for registering
8080 * new keywords in the cli. It expects a list of keywords
8081 * which are the "path". It is limited to 5 keywords. A
8082 * description of the command, a function to be executed
8083 * for the parsing and a function for io handlers.
8084 */
8085__LJMP static int hlua_register_cli(lua_State *L)
8086{
8087 struct cli_kw_list *cli_kws;
8088 const char *message;
8089 int ref_io;
8090 int len;
8091 struct hlua_function *fcn;
8092 int index;
8093 int i;
8094
8095 MAY_LJMP(check_args(L, 3, "register_cli"));
8096
8097 /* First argument : an array of maximum 5 keywords. */
8098 if (!lua_istable(L, 1))
8099 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
8100
8101 /* Second argument : string with contextual message. */
8102 message = MAY_LJMP(luaL_checkstring(L, 2));
8103
8104 /* Third and fourth argument : lua function. */
8105 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
8106
8107 /* Allocate and fill the sample fetch keyword struct. */
8108 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
8109 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008110 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008111 fcn = calloc(1, sizeof(*fcn));
8112 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008113 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008114
8115 /* Fill path. */
8116 index = 0;
8117 lua_pushnil(L);
8118 while(lua_next(L, 1) != 0) {
8119 if (index >= 5)
8120 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8121 if (lua_type(L, -1) != LUA_TSTRING)
8122 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8123 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
8124 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008125 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008126 index++;
8127 lua_pop(L, 1);
8128 }
8129
8130 /* Copy help message. */
8131 cli_kws->kw[0].usage = strdup(message);
8132 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008133 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008134
8135 /* Fill fcn io handler. */
8136 len = strlen("<lua.cli>") + 1;
8137 for (i = 0; i < index; i++)
8138 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
8139 fcn->name = calloc(1, len);
8140 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008141 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008142 strncat((char *)fcn->name, "<lua.cli", len);
8143 for (i = 0; i < index; i++) {
8144 strncat((char *)fcn->name, ".", len);
8145 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
8146 }
8147 strncat((char *)fcn->name, ">", len);
8148 fcn->function_ref = ref_io;
8149
8150 /* Fill last entries. */
8151 cli_kws->kw[0].private = fcn;
8152 cli_kws->kw[0].parse = hlua_cli_parse_fct;
8153 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
8154 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
8155
8156 /* Register this new converter */
8157 cli_register_kw(cli_kws);
8158
8159 return 0;
8160}
8161
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008162static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
8163 struct proxy *defpx, const char *file, int line,
8164 char **err, unsigned int *timeout)
8165{
8166 const char *error;
8167
8168 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
8169 if (error && *error != '\0') {
8170 memprintf(err, "%s: invalid timeout", args[0]);
8171 return -1;
8172 }
8173 return 0;
8174}
8175
8176static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
8177 struct proxy *defpx, const char *file, int line,
8178 char **err)
8179{
8180 return hlua_read_timeout(args, section_type, curpx, defpx,
8181 file, line, err, &hlua_timeout_session);
8182}
8183
8184static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
8185 struct proxy *defpx, const char *file, int line,
8186 char **err)
8187{
8188 return hlua_read_timeout(args, section_type, curpx, defpx,
8189 file, line, err, &hlua_timeout_task);
8190}
8191
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008192static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
8193 struct proxy *defpx, const char *file, int line,
8194 char **err)
8195{
8196 return hlua_read_timeout(args, section_type, curpx, defpx,
8197 file, line, err, &hlua_timeout_applet);
8198}
8199
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008200static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
8201 struct proxy *defpx, const char *file, int line,
8202 char **err)
8203{
8204 char *error;
8205
8206 hlua_nb_instruction = strtoll(args[1], &error, 10);
8207 if (*error != '\0') {
8208 memprintf(err, "%s: invalid number", args[0]);
8209 return -1;
8210 }
8211 return 0;
8212}
8213
Willy Tarreau32f61e22015-03-18 17:54:59 +01008214static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
8215 struct proxy *defpx, const char *file, int line,
8216 char **err)
8217{
8218 char *error;
8219
8220 if (*(args[1]) == 0) {
8221 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
8222 return -1;
8223 }
8224 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
8225 if (*error != '\0') {
8226 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
8227 return -1;
8228 }
8229 return 0;
8230}
8231
8232
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008233/* This function is called by the main configuration key "lua-load". It loads and
8234 * execute an lua file during the parsing of the HAProxy configuration file. It is
8235 * the main lua entry point.
8236 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008237 * This function runs with the HAProxy keywords API. It returns -1 if an error
8238 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008239 *
8240 * In some error case, LUA set an error message in top of the stack. This function
8241 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008242 *
8243 * This function can fail with an abort() due to an Lua critical error.
8244 * We are in the configuration parsing process of HAProxy, this abort() is
8245 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008246 */
8247static int hlua_load(char **args, int section_type, struct proxy *curpx,
8248 struct proxy *defpx, const char *file, int line,
8249 char **err)
8250{
8251 int error;
8252
8253 /* Just load and compile the file. */
8254 error = luaL_loadfile(gL.T, args[1]);
8255 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008256 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008257 lua_pop(gL.T, 1);
8258 return -1;
8259 }
8260
8261 /* If no syntax error where detected, execute the code. */
8262 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
8263 switch (error) {
8264 case LUA_OK:
8265 break;
8266 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008267 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008268 lua_pop(gL.T, 1);
8269 return -1;
8270 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008271 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008272 return -1;
8273 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008274 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008275 lua_pop(gL.T, 1);
8276 return -1;
8277 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008278 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008279 lua_pop(gL.T, 1);
8280 return -1;
8281 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008282 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008283 lua_pop(gL.T, 1);
8284 return -1;
8285 }
8286
8287 return 0;
8288}
8289
8290/* configuration keywords declaration */
8291static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008292 { CFG_GLOBAL, "lua-load", hlua_load },
8293 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
8294 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02008295 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008296 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01008297 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008298 { 0, NULL, NULL },
8299}};
8300
Willy Tarreau0108d902018-11-25 19:14:37 +01008301INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
8302
Christopher Fauletafd8f102018-11-08 11:34:21 +01008303
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008304/* This function can fail with an abort() due to an Lua critical error.
8305 * We are in the initialisation process of HAProxy, this abort() is
8306 * tolerated.
8307 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008308int hlua_post_init()
8309{
8310 struct hlua_init_function *init;
8311 const char *msg;
8312 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008313 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008314
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008315 /* Call post initialisation function in safe environement. */
8316 if (!SET_SAFE_LJMP(gL.T)) {
8317 if (lua_type(gL.T, -1) == LUA_TSTRING)
8318 error = lua_tostring(gL.T, -1);
8319 else
8320 error = "critical error";
8321 fprintf(stderr, "Lua post-init: %s.\n", error);
8322 exit(1);
8323 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02008324
8325#if USE_OPENSSL
8326 /* Initialize SSL server. */
8327 if (socket_ssl.xprt->prepare_srv) {
8328 int saved_used_backed = global.ssl_used_backend;
8329 // don't affect maxconn automatic computation
8330 socket_ssl.xprt->prepare_srv(&socket_ssl);
8331 global.ssl_used_backend = saved_used_backed;
8332 }
8333#endif
8334
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008335 hlua_fcn_post_init(gL.T);
8336 RESET_SAFE_LJMP(gL.T);
8337
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008338 list_for_each_entry(init, &hlua_init_functions, l) {
8339 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
8340 ret = hlua_ctx_resume(&gL, 0);
8341 switch (ret) {
8342 case HLUA_E_OK:
8343 lua_pop(gL.T, -1);
8344 return 1;
8345 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008346 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008347 return 0;
8348 case HLUA_E_ERRMSG:
8349 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01008350 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008351 return 0;
8352 case HLUA_E_ERR:
8353 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008354 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008355 return 0;
8356 }
8357 }
8358 return 1;
8359}
8360
Willy Tarreau32f61e22015-03-18 17:54:59 +01008361/* The memory allocator used by the Lua stack. <ud> is a pointer to the
8362 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
8363 * is the previously allocated size or the kind of object in case of a new
8364 * allocation. <nsize> is the requested new size.
8365 */
8366static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
8367{
8368 struct hlua_mem_allocator *zone = ud;
8369
8370 if (nsize == 0) {
8371 /* it's a free */
8372 if (ptr)
8373 zone->allocated -= osize;
8374 free(ptr);
8375 return NULL;
8376 }
8377
8378 if (!ptr) {
8379 /* it's a new allocation */
8380 if (zone->limit && zone->allocated + nsize > zone->limit)
8381 return NULL;
8382
8383 ptr = malloc(nsize);
8384 if (ptr)
8385 zone->allocated += nsize;
8386 return ptr;
8387 }
8388
8389 /* it's a realloc */
8390 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
8391 return NULL;
8392
8393 ptr = realloc(ptr, nsize);
8394 if (ptr)
8395 zone->allocated += nsize - osize;
8396 return ptr;
8397}
8398
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008399/* Ithis function can fail with an abort() due to an Lua critical error.
8400 * We are in the initialisation process of HAProxy, this abort() is
8401 * tolerated.
8402 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008403void hlua_init(void)
8404{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008405 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008406 int idx;
8407 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008408 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008409 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008410 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008411#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008412 struct srv_kw *kw;
8413 int tmp_error;
8414 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008415 char *args[] = { /* SSL client configuration. */
8416 "ssl",
8417 "verify",
8418 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008419 NULL
8420 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008421#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008422
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008423 /* Init main lua stack. */
8424 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01008425 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01008426 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02008427 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008428 hlua_sethlua(&gL);
8429 gL.Tref = LUA_REFNIL;
8430 gL.task = NULL;
8431
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008432 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008433 * the Lua function can fail with an abort. We are in the initialisation
8434 * process of HAProxy, this abort() is tolerated.
8435 */
8436
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008437 /* Initialise lua. */
8438 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008439
Thierry Fournier75933d42016-01-21 09:30:18 +01008440 /* Set safe environment for the initialisation. */
8441 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008442 if (lua_type(gL.T, -1) == LUA_TSTRING)
8443 error_msg = lua_tostring(gL.T, -1);
8444 else
8445 error_msg = "critical error";
8446 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01008447 exit(1);
8448 }
8449
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008450 /*
8451 *
8452 * Create "core" object.
8453 *
8454 */
8455
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008456 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008457 lua_newtable(gL.T);
8458
8459 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008460 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008461 hlua_class_const_int(gL.T, log_levels[i], i);
8462
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008463 /* Register special functions. */
8464 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008465 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008466 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008467 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008468 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008469 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008470 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008471 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01008472 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008473 hlua_class_function(gL.T, "sleep", hlua_sleep);
8474 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01008475 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
8476 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
8477 hlua_class_function(gL.T, "set_map", hlua_set_map);
8478 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008479 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008480 hlua_class_function(gL.T, "log", hlua_log);
8481 hlua_class_function(gL.T, "Debug", hlua_log_debug);
8482 hlua_class_function(gL.T, "Info", hlua_log_info);
8483 hlua_class_function(gL.T, "Warning", hlua_log_warning);
8484 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02008485 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01008486 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008487
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008488 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008489
8490 /*
8491 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008492 * Register class Map
8493 *
8494 */
8495
8496 /* This table entry is the object "Map" base. */
8497 lua_newtable(gL.T);
8498
8499 /* register pattern types. */
8500 for (i=0; i<PAT_MATCH_NUM; i++)
8501 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008502 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008503 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
8504 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008505 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008506
8507 /* register constructor. */
8508 hlua_class_function(gL.T, "new", hlua_map_new);
8509
8510 /* Create and fill the metatable. */
8511 lua_newtable(gL.T);
8512
8513 /* Create and fille the __index entry. */
8514 lua_pushstring(gL.T, "__index");
8515 lua_newtable(gL.T);
8516
8517 /* Register . */
8518 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
8519 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
8520
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008521 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008522
Thierry Fournier45e78d72016-02-19 18:34:46 +01008523 /* Register previous table in the registry with reference and named entry.
8524 * The function hlua_register_metatable() pops the stack, so we
8525 * previously create a copy of the table.
8526 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008527 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008528 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008529
8530 /* Assign the metatable to the mai Map object. */
8531 lua_setmetatable(gL.T, -2);
8532
8533 /* Set a name to the table. */
8534 lua_setglobal(gL.T, "Map");
8535
8536 /*
8537 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008538 * Register class Channel
8539 *
8540 */
8541
8542 /* Create and fill the metatable. */
8543 lua_newtable(gL.T);
8544
8545 /* Create and fille the __index entry. */
8546 lua_pushstring(gL.T, "__index");
8547 lua_newtable(gL.T);
8548
8549 /* Register . */
8550 hlua_class_function(gL.T, "get", hlua_channel_get);
8551 hlua_class_function(gL.T, "dup", hlua_channel_dup);
8552 hlua_class_function(gL.T, "getline", hlua_channel_getline);
8553 hlua_class_function(gL.T, "set", hlua_channel_set);
8554 hlua_class_function(gL.T, "append", hlua_channel_append);
8555 hlua_class_function(gL.T, "send", hlua_channel_send);
8556 hlua_class_function(gL.T, "forward", hlua_channel_forward);
8557 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
8558 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01008559 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008560
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008561 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008562
8563 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008564 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008565
8566 /*
8567 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008568 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008569 *
8570 */
8571
8572 /* Create and fill the metatable. */
8573 lua_newtable(gL.T);
8574
8575 /* Create and fille the __index entry. */
8576 lua_pushstring(gL.T, "__index");
8577 lua_newtable(gL.T);
8578
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008579 /* Browse existing fetches and create the associated
8580 * object method.
8581 */
8582 sf = NULL;
8583 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
8584
8585 /* Dont register the keywork if the arguments check function are
8586 * not safe during the runtime.
8587 */
8588 if ((sf->val_args != NULL) &&
8589 (sf->val_args != val_payload_lv) &&
8590 (sf->val_args != val_hdr))
8591 continue;
8592
8593 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8594 * by an underscore.
8595 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008596 strncpy(trash.area, sf->kw, trash.size);
8597 trash.area[trash.size - 1] = '\0';
8598 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008599 if (*p == '.' || *p == '-' || *p == '+')
8600 *p = '_';
8601
8602 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008603 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01008604 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008605 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008606 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008607 }
8608
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008609 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008610
8611 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008612 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008613
8614 /*
8615 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008616 * Register class Converters
8617 *
8618 */
8619
8620 /* Create and fill the metatable. */
8621 lua_newtable(gL.T);
8622
8623 /* Create and fill the __index entry. */
8624 lua_pushstring(gL.T, "__index");
8625 lua_newtable(gL.T);
8626
8627 /* Browse existing converters and create the associated
8628 * object method.
8629 */
8630 sc = NULL;
8631 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
8632 /* Dont register the keywork if the arguments check function are
8633 * not safe during the runtime.
8634 */
8635 if (sc->val_args != NULL)
8636 continue;
8637
8638 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8639 * by an underscore.
8640 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008641 strncpy(trash.area, sc->kw, trash.size);
8642 trash.area[trash.size - 1] = '\0';
8643 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008644 if (*p == '.' || *p == '-' || *p == '+')
8645 *p = '_';
8646
8647 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008648 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008649 lua_pushlightuserdata(gL.T, sc);
8650 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008651 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008652 }
8653
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008654 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008655
8656 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008657 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008658
8659 /*
8660 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008661 * Register class HTTP
8662 *
8663 */
8664
8665 /* Create and fill the metatable. */
8666 lua_newtable(gL.T);
8667
8668 /* Create and fille the __index entry. */
8669 lua_pushstring(gL.T, "__index");
8670 lua_newtable(gL.T);
8671
8672 /* Register Lua functions. */
8673 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
8674 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
8675 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
8676 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
8677 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
8678 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
8679 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
8680 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
8681 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
8682 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
8683
8684 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
8685 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
8686 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
8687 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
8688 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
8689 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02008690 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008691
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008692 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008693
8694 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008695 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008696
8697 /*
8698 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008699 * Register class AppletTCP
8700 *
8701 */
8702
8703 /* Create and fill the metatable. */
8704 lua_newtable(gL.T);
8705
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008706 /* Create and fille the __index entry. */
8707 lua_pushstring(gL.T, "__index");
8708 lua_newtable(gL.T);
8709
8710 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01008711 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
8712 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
8713 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
8714 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
8715 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008716 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
8717 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
8718 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008719
8720 lua_settable(gL.T, -3);
8721
8722 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008723 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008724
8725 /*
8726 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008727 * Register class AppletHTTP
8728 *
8729 */
8730
8731 /* Create and fill the metatable. */
8732 lua_newtable(gL.T);
8733
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008734 /* Create and fille the __index entry. */
8735 lua_pushstring(gL.T, "__index");
8736 lua_newtable(gL.T);
8737
8738 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01008739 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
8740 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008741 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
8742 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
8743 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008744 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
8745 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
8746 hlua_class_function(gL.T, "send", hlua_applet_http_send);
8747 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
8748 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
8749 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
8750
8751 lua_settable(gL.T, -3);
8752
8753 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008754 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008755
8756 /*
8757 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008758 * Register class TXN
8759 *
8760 */
8761
8762 /* Create and fill the metatable. */
8763 lua_newtable(gL.T);
8764
8765 /* Create and fille the __index entry. */
8766 lua_pushstring(gL.T, "__index");
8767 lua_newtable(gL.T);
8768
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008769 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04008770 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
8771 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
8772 hlua_class_function(gL.T, "set_var", hlua_set_var);
8773 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
8774 hlua_class_function(gL.T, "get_var", hlua_get_var);
8775 hlua_class_function(gL.T, "done", hlua_txn_done);
8776 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
8777 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
8778 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
8779 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
8780 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
8781 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
8782 hlua_class_function(gL.T, "log", hlua_txn_log);
8783 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
8784 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
8785 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
8786 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008787
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008788 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008789
8790 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008791 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008792
8793 /*
8794 *
8795 * Register class Socket
8796 *
8797 */
8798
8799 /* Create and fill the metatable. */
8800 lua_newtable(gL.T);
8801
8802 /* Create and fille the __index entry. */
8803 lua_pushstring(gL.T, "__index");
8804 lua_newtable(gL.T);
8805
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008806#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008807 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008808#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008809 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8810 hlua_class_function(gL.T, "send", hlua_socket_send);
8811 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8812 hlua_class_function(gL.T, "close", hlua_socket_close);
8813 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8814 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8815 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8816 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8817
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008818 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008819
8820 /* Register the garbage collector entry. */
8821 lua_pushstring(gL.T, "__gc");
8822 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008823 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008824
8825 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008826 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008827
8828 /* Proxy and server configuration initialisation. */
8829 memset(&socket_proxy, 0, sizeof(socket_proxy));
8830 init_new_proxy(&socket_proxy);
8831 socket_proxy.parent = NULL;
8832 socket_proxy.last_change = now.tv_sec;
8833 socket_proxy.id = "LUA-SOCKET";
8834 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8835 socket_proxy.maxconn = 0;
8836 socket_proxy.accept = NULL;
8837 socket_proxy.options2 |= PR_O2_INDEPSTR;
8838 socket_proxy.srv = NULL;
8839 socket_proxy.conn_retries = 0;
8840 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8841
8842 /* Init TCP server: unchanged parameters */
8843 memset(&socket_tcp, 0, sizeof(socket_tcp));
8844 socket_tcp.next = NULL;
8845 socket_tcp.proxy = &socket_proxy;
8846 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8847 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008848 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008849 socket_tcp.priv_conns = NULL;
8850 socket_tcp.idle_conns = NULL;
8851 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008852 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008853 socket_tcp.last_change = 0;
8854 socket_tcp.id = "LUA-TCP-CONN";
8855 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8856 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8857 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8858
8859 /* XXX: Copy default parameter from default server,
8860 * but the default server is not initialized.
8861 */
8862 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8863 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8864 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8865 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8866 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8867 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8868 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8869 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8870 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8871 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8872
8873 socket_tcp.check.status = HCHK_STATUS_INI;
8874 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8875 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8876 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8877 socket_tcp.check.server = &socket_tcp;
8878
8879 socket_tcp.agent.status = HCHK_STATUS_INI;
8880 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8881 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8882 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8883 socket_tcp.agent.server = &socket_tcp;
8884
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008885 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008886
8887#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008888 /* Init TCP server: unchanged parameters */
8889 memset(&socket_ssl, 0, sizeof(socket_ssl));
8890 socket_ssl.next = NULL;
8891 socket_ssl.proxy = &socket_proxy;
8892 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8893 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008894 socket_ssl.pendconns = EB_ROOT;
Willy Tarreaub784b352019-02-07 14:48:24 +01008895 socket_ssl.priv_conns = NULL;
8896 socket_ssl.idle_conns = NULL;
8897 socket_ssl.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008898 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008899 socket_ssl.last_change = 0;
8900 socket_ssl.id = "LUA-SSL-CONN";
8901 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8902 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8903 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8904
8905 /* XXX: Copy default parameter from default server,
8906 * but the default server is not initialized.
8907 */
8908 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8909 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8910 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8911 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8912 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8913 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8914 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8915 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8916 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8917 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8918
8919 socket_ssl.check.status = HCHK_STATUS_INI;
8920 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8921 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8922 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8923 socket_ssl.check.server = &socket_ssl;
8924
8925 socket_ssl.agent.status = HCHK_STATUS_INI;
8926 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8927 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8928 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8929 socket_ssl.agent.server = &socket_ssl;
8930
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008931 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008932 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008933
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008934 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008935 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8936 /*
8937 *
8938 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008939 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008940 * features like client certificates and ssl_verify.
8941 *
8942 */
8943 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8944 if (tmp_error != 0) {
8945 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8946 abort(); /* This must be never arrives because the command line
8947 not editable by the user. */
8948 }
8949 idx += kw->skip;
8950 }
8951 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008952#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008953
8954 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008955}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008956
Willy Tarreau80713382018-11-26 10:19:54 +01008957static void hlua_register_build_options(void)
8958{
Willy Tarreaubb57d942016-12-21 19:04:56 +01008959 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01008960
Willy Tarreaubb57d942016-12-21 19:04:56 +01008961 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8962 hap_register_build_opts(ptr, 1);
8963}
Willy Tarreau80713382018-11-26 10:19:54 +01008964
8965INITCALL0(STG_REGISTER, hlua_register_build_options);