blob: ca51477c4bca9cc368ca4d8585d092f18be3f479 [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
4625 max = htx_free_space(htx);
4626 if (channel_recv_limit(res) < b_size(&res->buf)) {
4627 if (max < global.tune.maxrewrite) {
4628 si_rx_room_blk(si);
4629 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_send_yield, TICK_ETERNITY, 0));
4630 }
4631 max -= global.tune.maxrewrite;
4632 }
4633
4634 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4635
4636 /* Get the max amount of data which can write as input in the channel. */
4637 if (max > (len - l))
4638 max = len - l;
4639
4640 /* Copy data. */
4641 htx_add_data(htx, ist2(data + l, max));
4642 res->total += l;
4643 res->flags |= CF_READ_PARTIAL;
4644 htx_to_buf(htx, &res->buf);
4645
4646 /* update counters. */
4647 l += max;
4648 lua_pop(L, 1);
4649 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004650
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004651 /* If some data is not send, declares the situation to the
4652 * applet, and returns a yield.
4653 */
4654 if (l < len) {
4655 si_rx_room_blk(si);
4656 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_send_yield, TICK_ETERNITY, 0));
4657 }
4658
4659 return 1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004660}
4661
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004662/* Append data in the output side of the buffer. This data is immediately
4663 * sent. The function returns the amount of data written. If the buffer
4664 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004665 * if the channel is closed.
4666 */
4667__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4668{
4669 size_t len;
4670 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4671 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4672 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4673 struct stream_interface *si = appctx->appctx->owner;
4674 struct channel *chn = si_ic(si);
4675 int max;
4676
4677 /* Get the max amount of data which can write as input in the channel. */
4678 max = channel_recv_max(chn);
4679 if (max > (len - l))
4680 max = len - l;
4681
4682 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004683 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004684
4685 /* update counters. */
4686 l += max;
4687 lua_pop(L, 1);
4688 lua_pushinteger(L, l);
4689
4690 /* If some data is not send, declares the situation to the
4691 * applet, and returns a yield.
4692 */
4693 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004694 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004695 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004696 }
4697
4698 return 1;
4699}
4700
4701/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4702 * yield the LUA process, and resume it without checking the
4703 * input arguments.
4704 */
4705__LJMP static int hlua_applet_http_send(lua_State *L)
4706{
4707 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004708
4709 /* We want to send some data. Headers must be sent. */
4710 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4711 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4712 WILL_LJMP(lua_error(L));
4713 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004714
4715 if (IS_HTX_STRM(si_strm(appctx->appctx->owner))) {
4716 /* HTX version */
4717 /* This interger is used for followinf the amount of data sent. */
4718 lua_pushinteger(L, 0);
4719
4720 return MAY_LJMP(hlua_applet_htx_send_yield(L, 0, 0));
4721 }
4722 else {
4723 /* Legacy HTTP version */
4724 size_t len;
4725 char hex[10];
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004726
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004727 MAY_LJMP(luaL_checklstring(L, 2, &len));
4728
4729 /* If transfer encoding chunked is selected, we surround the data
4730 * by chunk data.
4731 */
4732 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4733 snprintf(hex, 9, "%x", (unsigned int)len);
4734 lua_pushfstring(L, "%s\r\n", hex);
4735 lua_insert(L, 2); /* swap the last 2 entries. */
4736 lua_pushstring(L, "\r\n");
4737 lua_concat(L, 3);
4738 }
4739
4740 /* This interger is used for followinf the amount of data sent. */
4741 lua_pushinteger(L, 0);
4742
4743 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4744 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004745}
4746
4747__LJMP static int hlua_applet_http_addheader(lua_State *L)
4748{
4749 const char *name;
4750 int ret;
4751
4752 MAY_LJMP(hlua_checkapplet_http(L, 1));
4753 name = MAY_LJMP(luaL_checkstring(L, 2));
4754 MAY_LJMP(luaL_checkstring(L, 3));
4755
4756 /* Push in the stack the "response" entry. */
4757 ret = lua_getfield(L, 1, "response");
4758 if (ret != LUA_TTABLE) {
4759 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4760 "is expected as an array. %s found", lua_typename(L, ret));
4761 WILL_LJMP(lua_error(L));
4762 }
4763
4764 /* check if the header is already registered if it is not
4765 * the case, register it.
4766 */
4767 ret = lua_getfield(L, -1, name);
4768 if (ret == LUA_TNIL) {
4769
4770 /* Entry not found. */
4771 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4772
4773 /* Insert the new header name in the array in the top of the stack.
4774 * It left the new array in the top of the stack.
4775 */
4776 lua_newtable(L);
4777 lua_pushvalue(L, 2);
4778 lua_pushvalue(L, -2);
4779 lua_settable(L, -4);
4780
4781 } else if (ret != LUA_TTABLE) {
4782
4783 /* corruption error. */
4784 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4785 "is expected as an array. %s found", name, lua_typename(L, ret));
4786 WILL_LJMP(lua_error(L));
4787 }
4788
4789 /* Now the top od thestack is an array of values. We push
4790 * the header value as new entry.
4791 */
4792 lua_pushvalue(L, 3);
4793 ret = lua_rawlen(L, -2);
4794 lua_rawseti(L, -2, ret + 1);
4795 lua_pushboolean(L, 1);
4796 return 1;
4797}
4798
4799__LJMP static int hlua_applet_http_status(lua_State *L)
4800{
4801 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4802 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004803 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004804
4805 if (status < 100 || status > 599) {
4806 lua_pushboolean(L, 0);
4807 return 1;
4808 }
4809
4810 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004811 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004812 lua_pushboolean(L, 1);
4813 return 1;
4814}
4815
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004816
4817__LJMP static int hlua_applet_htx_send_response(lua_State *L)
4818{
4819 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4820 struct stream_interface *si = appctx->appctx->owner;
4821 struct channel *res = si_ic(si);
4822 struct htx *htx;
4823 struct htx_sl *sl;
4824 struct h1m h1m;
4825 const char *status, *reason;
4826 const char *name, *value;
4827 size_t nlen, vlen;
4828 unsigned int flags;
4829
4830 /* Send the message at once. */
4831 htx = htx_from_buf(&res->buf);
4832 h1m_init_res(&h1m);
4833
4834 /* Use the same http version than the request. */
4835 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4836 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4837 if (reason == NULL)
4838 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4839 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4840 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4841 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4842 }
4843 else {
4844 flags = HTX_SL_F_IS_RESP;
4845 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4846 }
4847 if (!sl) {
4848 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
4849 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4850 WILL_LJMP(lua_error(L));
4851 }
4852 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4853
4854 /* Get the array associated to the field "response" in the object AppletHTTP. */
4855 lua_pushvalue(L, 0);
4856 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4857 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4858 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4859 WILL_LJMP(lua_error(L));
4860 }
4861
4862 /* Browse the list of headers. */
4863 lua_pushnil(L);
4864 while(lua_next(L, -2) != 0) {
4865 /* We expect a string as -2. */
4866 if (lua_type(L, -2) != LUA_TSTRING) {
4867 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4868 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4869 lua_typename(L, lua_type(L, -2)));
4870 WILL_LJMP(lua_error(L));
4871 }
4872 name = lua_tolstring(L, -2, &nlen);
4873
4874 /* We expect an array as -1. */
4875 if (lua_type(L, -1) != LUA_TTABLE) {
4876 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4877 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4878 name,
4879 lua_typename(L, lua_type(L, -1)));
4880 WILL_LJMP(lua_error(L));
4881 }
4882
4883 /* Browse the table who is on the top of the stack. */
4884 lua_pushnil(L);
4885 while(lua_next(L, -2) != 0) {
4886 int id;
4887
4888 /* We expect a number as -2. */
4889 if (lua_type(L, -2) != LUA_TNUMBER) {
4890 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4891 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4892 name,
4893 lua_typename(L, lua_type(L, -2)));
4894 WILL_LJMP(lua_error(L));
4895 }
4896 id = lua_tointeger(L, -2);
4897
4898 /* We expect a string as -2. */
4899 if (lua_type(L, -1) != LUA_TSTRING) {
4900 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4901 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4902 name, id,
4903 lua_typename(L, lua_type(L, -1)));
4904 WILL_LJMP(lua_error(L));
4905 }
4906 value = lua_tolstring(L, -1, &vlen);
4907
4908 /* Simple Protocol checks. */
4909 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
4910 h1_parse_xfer_enc_header(&h1m, ist2(name, nlen));
4911 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4912 struct ist v = ist2(value, vlen);
4913 int ret;
4914
4915 ret = h1_parse_cont_len_header(&h1m, &v);
4916 if (ret < 0) {
4917 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
4918 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4919 name);
4920 WILL_LJMP(lua_error(L));
4921 }
4922 else if (ret == 0)
4923 goto next; /* Skip it */
4924 }
4925
4926 /* Add a new header */
4927 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4928 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
4929 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4930 name);
4931 WILL_LJMP(lua_error(L));
4932 }
4933 next:
4934 /* Remove the array from the stack, and get next element with a remaining string. */
4935 lua_pop(L, 1);
4936 }
4937
4938 /* Remove the array from the stack, and get next element with a remaining string. */
4939 lua_pop(L, 1);
4940 }
4941
4942 if (h1m.flags & H1_MF_CHNK)
4943 h1m.flags &= ~H1_MF_CLEN;
4944 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4945 h1m.flags |= H1_MF_XFER_LEN;
4946
4947 /* Uset HTX start-line flags */
4948 if (h1m.flags & H1_MF_XFER_ENC)
4949 flags |= HTX_SL_F_XFER_ENC;
4950 if (h1m.flags & H1_MF_XFER_LEN) {
4951 flags |= HTX_SL_F_XFER_LEN;
4952 if (h1m.flags & H1_MF_CHNK)
4953 flags |= HTX_SL_F_CHNK;
4954 else if (h1m.flags & H1_MF_CLEN)
4955 flags |= HTX_SL_F_CLEN;
4956 if (h1m.body_len == 0)
4957 flags |= HTX_SL_F_BODYLESS;
4958 }
4959 sl->flags |= flags;
4960
4961 /* If we dont have a content-length set, and the HTTP version is 1.1
4962 * and the status code implies the presence of a message body, we must
4963 * announce a transfer encoding chunked. This is required by haproxy
4964 * for the keepalive compliance. If the applet annouces a transfer-encoding
4965 * chunked itslef, don't do anything.
4966 */
4967 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4968 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4969 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4970 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4971 /* Add a new header */
4972 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4973 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4974 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
4975 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4976 WILL_LJMP(lua_error(L));
4977 }
4978 }
4979
4980 /* Finalize headers. */
4981 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4982 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
4983 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4984 WILL_LJMP(lua_error(L));
4985 }
4986
4987 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4988 b_reset(&res->buf);
4989 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4990 WILL_LJMP(lua_error(L));
4991 }
4992
4993 htx_to_buf(htx, &res->buf);
4994 res->total += htx->data;
4995 res->flags |= CF_READ_PARTIAL;
4996
4997 /* Headers sent, set the flag. */
4998 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4999 return 0;
5000
5001}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005002/* We will build the status line and the headers of the HTTP response.
5003 * We will try send at once if its not possible, we give back the hand
5004 * waiting for more room.
5005 */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005006__LJMP static int hlua_applet_htx_start_response_yield(lua_State *L, int status, lua_KContext ctx)
5007{
5008 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5009 struct stream_interface *si = appctx->appctx->owner;
5010 struct channel *res = si_ic(si);
5011
5012 if (co_data(res)) {
5013 si_rx_room_blk(si);
5014 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_htx_start_response_yield, TICK_ETERNITY, 0));
5015 }
5016 return MAY_LJMP(hlua_applet_htx_send_response(L));
5017}
5018
5019
5020__LJMP static int hlua_applet_htx_start_response(lua_State *L)
5021{
5022 return MAY_LJMP(hlua_applet_htx_start_response_yield(L, 0, 0));
5023}
5024
5025/* We will build the status line and the headers of the HTTP response.
5026 * We will try send at once if its not possible, we give back the hand
5027 * waiting for more room.
5028 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005029__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
5030{
5031 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
5032 struct stream_interface *si = appctx->appctx->owner;
5033 struct channel *chn = si_ic(si);
5034 int ret;
5035 size_t len;
5036 const char *msg;
5037
5038 /* Get the message as the first argument on the stack. */
5039 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
5040
5041 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02005042 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005043
5044 /* if ret == -2 or -3 the channel closed or the message si too
5045 * big for the buffers.
5046 */
5047 if (ret == -2 || ret == -3) {
5048 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
5049 WILL_LJMP(lua_error(L));
5050 }
5051
5052 /* If ret is -1, we dont have room in the buffer, so we yield. */
5053 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01005054 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02005055 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005056 }
5057
5058 /* Headers sent, set the flag. */
5059 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
5060 return 0;
5061}
5062
5063__LJMP static int hlua_applet_http_start_response(lua_State *L)
5064{
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005065 struct buffer *tmp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005066 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005067 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02005068 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005069 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02005070 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005071 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005072 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005073 int hdr_chunked = 0;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005074 const char *reason;
5075
5076 if (IS_HTX_STRM(si_strm(appctx->appctx->owner)))
5077 return MAY_LJMP(hlua_applet_htx_start_response(L));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005078
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005079 reason = appctx->appctx->ctx.hlua_apphttp.reason;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005080 if (reason == NULL)
Willy Tarreau04f1e2d2018-09-10 18:04:24 +02005081 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005082
Christopher Faulet9c832fc2018-12-14 13:34:05 +01005083 tmp = get_trash_chunk();
5084
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005085 /* Use the same http version than the request. */
5086 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01005087 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005088 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005089 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005090
5091 /* Get the array associated to the field "response" in the object AppletHTTP. */
5092 lua_pushvalue(L, 0);
5093 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
5094 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
5095 appctx->appctx->rule->arg.hlua_rule->fcn.name);
5096 WILL_LJMP(lua_error(L));
5097 }
5098
5099 /* Browse the list of headers. */
5100 lua_pushnil(L);
5101 while(lua_next(L, -2) != 0) {
5102
5103 /* We expect a string as -2. */
5104 if (lua_type(L, -2) != LUA_TSTRING) {
5105 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
5106 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5107 lua_typename(L, lua_type(L, -2)));
5108 WILL_LJMP(lua_error(L));
5109 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005110 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005111
5112 /* We expect an array as -1. */
5113 if (lua_type(L, -1) != LUA_TTABLE) {
5114 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
5115 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5116 name,
5117 lua_typename(L, lua_type(L, -1)));
5118 WILL_LJMP(lua_error(L));
5119 }
5120
5121 /* Browse the table who is on the top of the stack. */
5122 lua_pushnil(L);
5123 while(lua_next(L, -2) != 0) {
5124
5125 /* We expect a number as -2. */
5126 if (lua_type(L, -2) != LUA_TNUMBER) {
5127 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
5128 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5129 name,
5130 lua_typename(L, lua_type(L, -2)));
5131 WILL_LJMP(lua_error(L));
5132 }
5133 id = lua_tointeger(L, -2);
5134
5135 /* We expect a string as -2. */
5136 if (lua_type(L, -1) != LUA_TSTRING) {
5137 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
5138 appctx->appctx->rule->arg.hlua_rule->fcn.name,
5139 name, id,
5140 lua_typename(L, lua_type(L, -1)));
5141 WILL_LJMP(lua_error(L));
5142 }
Willy Tarreaua3294632017-08-23 11:24:47 +02005143 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005144
5145 /* Catenate a new header. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005146 if (tmp->data + name_len + 2 + value_len + 2 < tmp->size) {
5147 memcpy(tmp->area + tmp->data, name, name_len);
5148 tmp->data += name_len;
5149 tmp->area[tmp->data++] = ':';
5150 tmp->area[tmp->data++] = ' ';
Willy Tarreaua3294632017-08-23 11:24:47 +02005151
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005152 memcpy(tmp->area + tmp->data, value,
5153 value_len);
5154 tmp->data += value_len;
5155 tmp->area[tmp->data++] = '\r';
5156 tmp->area[tmp->data++] = '\n';
Willy Tarreaua3294632017-08-23 11:24:47 +02005157 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005158
5159 /* Protocol checks. */
5160
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005161 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005162 * is done without control. If it contains a bad value,
5163 * the content-length remains negative so that we can
5164 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005165 */
Willy Tarreaua3294632017-08-23 11:24:47 +02005166 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005167 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005168
5169 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02005170 if (name_len == 17 && value_len == 7 &&
5171 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005172 strcasecmp("chunked", value) == 0)
5173 hdr_chunked = 1;
5174
5175 /* Remove the array from the stack, and get next element with a remaining string. */
5176 lua_pop(L, 1);
5177 }
5178
5179 /* Remove the array from the stack, and get next element with a remaining string. */
5180 lua_pop(L, 1);
5181 }
5182
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005183 /* If we dont have a content-length set, and the HTTP version is 1.1
5184 * and the status code implies the presence of a message body, we must
5185 * announce a transfer encoding chunked. This is required by haproxy
5186 * for the keepalive compliance. If the applet annouces a transfer-encoding
5187 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005188 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02005189 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02005190 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
5191 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
5192 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
5193 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005194 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
5195 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
5196 }
5197
5198 /* Finalize headers. */
5199 chunk_appendf(tmp, "\r\n");
5200
5201 /* Remove the last entry and the array of headers */
5202 lua_pop(L, 2);
5203
5204 /* Push the headers block. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005205 lua_pushlstring(L, tmp->area, tmp->data);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005206
5207 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
5208}
5209
5210/*
5211 *
5212 *
5213 * Class HTTP
5214 *
5215 *
5216 */
5217
5218/* Returns a struct hlua_txn if the stack entry "ud" is
5219 * a class stream, otherwise it throws an error.
5220 */
5221__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
5222{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005223 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005224}
5225
5226/* This function creates and push in the stack a HTTP object
5227 * according with a current TXN.
5228 */
5229static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
5230{
5231 struct hlua_txn *htxn;
5232
5233 /* Check stack size. */
5234 if (!lua_checkstack(L, 3))
5235 return 0;
5236
5237 /* Create the object: obj[0] = userdata.
5238 * Note that the base of the Converters object is the
5239 * same than the TXN object.
5240 */
5241 lua_newtable(L);
5242 htxn = lua_newuserdata(L, sizeof(*htxn));
5243 lua_rawseti(L, -2, 0);
5244
5245 htxn->s = txn->s;
5246 htxn->p = txn->p;
5247
5248 /* Pop a class stream metatable and affect it to the table. */
5249 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
5250 lua_setmetatable(L, -2);
5251
5252 return 1;
5253}
5254
5255/* This function creates ans returns an array of HTTP headers.
5256 * This function does not fails. It is used as wrapper with the
5257 * 2 following functions.
5258 */
5259__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5260{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005261 /* Create the table. */
5262 lua_newtable(L);
5263
5264 if (!htxn->s->txn)
5265 return 1;
5266
Christopher Faulet724a12c2018-12-13 22:12:15 +01005267 if (IS_HTX_STRM(htxn->s)) {
5268 /* HTX version */
5269 struct htx *htx = htxbuf(&msg->chn->buf);
5270 int32_t pos;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005271
Christopher Faulet724a12c2018-12-13 22:12:15 +01005272 for (pos = htx_get_head(htx); pos != -1; pos = htx_get_next(htx, pos)) {
5273 struct htx_blk *blk = htx_get_blk(htx, pos);
5274 enum htx_blk_type type = htx_get_blk_type(blk);
5275 struct ist n, v;
5276 int len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005277
Christopher Faulet724a12c2018-12-13 22:12:15 +01005278 if (type == HTX_BLK_HDR) {
5279 n = htx_get_blk_name(htx,blk);
5280 v = htx_get_blk_value(htx, blk);
5281 }
5282 else if (type == HTX_BLK_EOH)
5283 break;
5284 else
5285 continue;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005286
Christopher Faulet724a12c2018-12-13 22:12:15 +01005287 /* Check for existing entry:
5288 * assume that the table is on the top of the stack, and
5289 * push the key in the stack, the function lua_gettable()
5290 * perform the lookup.
5291 */
5292 lua_pushlstring(L, n.ptr, n.len);
5293 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005294
Christopher Faulet724a12c2018-12-13 22:12:15 +01005295 switch (lua_type(L, -1)) {
5296 case LUA_TNIL:
5297 /* Table not found, create it. */
5298 lua_pop(L, 1); /* remove the nil value. */
5299 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5300 lua_newtable(L); /* create and push empty table. */
5301 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5302 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5303 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5304 break;
5305
5306 case LUA_TTABLE:
5307 /* Entry found: push the value in the table. */
5308 len = lua_rawlen(L, -1);
5309 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5310 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5311 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5312 break;
5313
5314 default:
5315 /* Other cases are errors. */
5316 hlua_pusherror(L, "internal error during the parsing of headers.");
5317 WILL_LJMP(lua_error(L));
5318 }
5319 }
5320 }
5321 else {
5322 /* Legacy HTTP version */
5323 const char *cur_ptr, *cur_next, *p;
5324 int old_idx, cur_idx;
5325 struct hdr_idx_elem *cur_hdr;
5326 const char *hn, *hv;
5327 int hnl, hvl;
5328 const char *in;
5329 char *out;
5330 int len;
5331
5332 /* Build array of headers. */
5333 old_idx = 0;
5334 cur_next = ci_head(msg->chn) + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
5335
5336 while (1) {
5337 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
5338 if (!cur_idx)
5339 break;
5340 old_idx = cur_idx;
5341
5342 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
5343 cur_ptr = cur_next;
5344 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
5345
5346 /* Now we have one full header at cur_ptr of len cur_hdr->len,
5347 * and the next header starts at cur_next. We'll check
5348 * this header in the list as well as against the default
5349 * rule.
5350 */
5351
5352 /* look for ': *'. */
5353 hn = cur_ptr;
5354 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
5355 if (p >= cur_ptr+cur_hdr->len)
5356 continue;
5357 hnl = p - hn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005358 p++;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005359 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
5360 p++;
5361 if (p >= cur_ptr+cur_hdr->len)
5362 continue;
5363 hv = p;
5364 hvl = cur_ptr+cur_hdr->len-p;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005365
Christopher Faulet724a12c2018-12-13 22:12:15 +01005366 /* Lowercase the key. Don't check the size of trash, it have
5367 * the size of one buffer and the input data contains in one
5368 * buffer.
5369 */
5370 out = trash.area;
5371 for (in=hn; in<hn+hnl; in++, out++)
5372 *out = tolower(*in);
5373 *out = '\0';
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005374
Christopher Faulet724a12c2018-12-13 22:12:15 +01005375 /* Check for existing entry:
5376 * assume that the table is on the top of the stack, and
5377 * push the key in the stack, the function lua_gettable()
5378 * perform the lookup.
5379 */
5380 lua_pushlstring(L, trash.area, hnl);
5381 lua_gettable(L, -2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005382
Christopher Faulet724a12c2018-12-13 22:12:15 +01005383 switch (lua_type(L, -1)) {
5384 case LUA_TNIL:
5385 /* Table not found, create it. */
5386 lua_pop(L, 1); /* remove the nil value. */
5387 lua_pushlstring(L, trash.area, hnl); /* push the header name as key. */
5388 lua_newtable(L); /* create and push empty table. */
5389 lua_pushlstring(L, hv, hvl); /* push header value. */
5390 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5391 lua_rawset(L, -3); /* index new table with header name (pop the values). */
5392 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005393
Christopher Faulet724a12c2018-12-13 22:12:15 +01005394 case LUA_TTABLE:
5395 /* Entry found: push the value in the table. */
5396 len = lua_rawlen(L, -1);
5397 lua_pushlstring(L, hv, hvl); /* push header value. */
5398 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5399 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5400 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005401
Christopher Faulet724a12c2018-12-13 22:12:15 +01005402 default:
5403 /* Other cases are errors. */
5404 hlua_pusherror(L, "internal error during the parsing of headers.");
5405 WILL_LJMP(lua_error(L));
5406 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005407 }
5408 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005409 return 1;
5410}
5411
5412__LJMP static int hlua_http_req_get_headers(lua_State *L)
5413{
5414 struct hlua_txn *htxn;
5415
5416 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5417 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5418
5419 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
5420}
5421
5422__LJMP static int hlua_http_res_get_headers(lua_State *L)
5423{
5424 struct hlua_txn *htxn;
5425
5426 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5427 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5428
5429 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
5430}
5431
5432/* This function replace full header, or just a value in
5433 * the request or in the response. It is a wrapper fir the
5434 * 4 following functions.
5435 */
5436__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
5437 struct http_msg *msg, int action)
5438{
5439 size_t name_len;
5440 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5441 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5442 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
5443 struct my_regex re;
5444
5445 if (!regex_comp(reg, &re, 1, 1, NULL))
5446 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5447
5448 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
5449 regex_free(&re);
5450 return 0;
5451}
5452
5453__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5454{
5455 struct hlua_txn *htxn;
5456
5457 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5458 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5459
5460 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
5461}
5462
5463__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5464{
5465 struct hlua_txn *htxn;
5466
5467 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5468 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5469
5470 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
5471}
5472
5473__LJMP static int hlua_http_req_rep_val(lua_State *L)
5474{
5475 struct hlua_txn *htxn;
5476
5477 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5478 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5479
5480 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
5481}
5482
5483__LJMP static int hlua_http_res_rep_val(lua_State *L)
5484{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005485 struct hlua_txn *htxn;
5486
5487 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5488 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5489
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02005490 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005491}
5492
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005493/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005494 * It is a wrapper for the 2 following functions.
5495 */
5496__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5497{
5498 size_t len;
5499 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005500
Christopher Faulet724a12c2018-12-13 22:12:15 +01005501 if (IS_HTX_STRM(htxn->s)) {
5502 /* HTX version */
5503 struct htx *htx = htxbuf(&msg->chn->buf);
5504 struct http_hdr_ctx ctx;
5505
5506 ctx.blk = NULL;
5507 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5508 http_remove_header(htx, &ctx);
5509 }
5510 else {
5511 /* Legacy HTTP version */
5512 struct hdr_ctx ctx;
5513 struct http_txn *txn = htxn->s->txn;
5514
5515 ctx.idx = 0;
5516 while (http_find_header2(name, len, ci_head(msg->chn), &txn->hdr_idx, &ctx))
5517 http_remove_header2(msg, &txn->hdr_idx, &ctx);
5518 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005519 return 0;
5520}
5521
5522__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5523{
5524 struct hlua_txn *htxn;
5525
5526 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5527 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5528
Willy Tarreaueee5b512015-04-03 23:46:31 +02005529 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005530}
5531
5532__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5533{
5534 struct hlua_txn *htxn;
5535
5536 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5537 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5538
Willy Tarreaueee5b512015-04-03 23:46:31 +02005539 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005540}
5541
5542/* This function adds an header. It is a wrapper used by
5543 * the 2 following functions.
5544 */
5545__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
5546{
5547 size_t name_len;
5548 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5549 size_t value_len;
5550 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
5551 char *p;
5552
Christopher Faulet724a12c2018-12-13 22:12:15 +01005553 if (IS_HTX_STRM(htxn->s)) {
5554 /* HTX version */
5555 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005556
Christopher Faulet724a12c2018-12-13 22:12:15 +01005557 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5558 ist2(value, value_len)));
5559 }
5560 else {
5561 /* Legacy HTTP version */
5562 /* Check length. */
5563 trash.data = value_len + name_len + 2;
5564 if (trash.data > trash.size)
5565 return 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005566
Christopher Faulet724a12c2018-12-13 22:12:15 +01005567 /* Creates the header string. */
5568 p = trash.area;
5569 memcpy(p, name, name_len);
5570 p += name_len;
5571 *p = ':';
5572 p++;
5573 *p = ' ';
5574 p++;
5575 memcpy(p, value, value_len);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005576
Christopher Faulet724a12c2018-12-13 22:12:15 +01005577 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
5578 trash.area, trash.data) != 0);
5579 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005580 return 0;
5581}
5582
5583__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5584{
5585 struct hlua_txn *htxn;
5586
5587 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5588 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5589
Willy Tarreaueee5b512015-04-03 23:46:31 +02005590 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005591}
5592
5593__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5594{
5595 struct hlua_txn *htxn;
5596
5597 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5598 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5599
Willy Tarreaueee5b512015-04-03 23:46:31 +02005600 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005601}
5602
5603static int hlua_http_req_set_hdr(lua_State *L)
5604{
5605 struct hlua_txn *htxn;
5606
5607 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5608 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5609
Willy Tarreaueee5b512015-04-03 23:46:31 +02005610 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
5611 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005612}
5613
5614static int hlua_http_res_set_hdr(lua_State *L)
5615{
5616 struct hlua_txn *htxn;
5617
5618 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5619 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5620
Willy Tarreaueee5b512015-04-03 23:46:31 +02005621 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
5622 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005623}
5624
5625/* This function set the method. */
5626static int hlua_http_req_set_meth(lua_State *L)
5627{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005628 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005629 size_t name_len;
5630 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005631
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005632 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005633 return 1;
5634}
5635
5636/* This function set the method. */
5637static int hlua_http_req_set_path(lua_State *L)
5638{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005639 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005640 size_t name_len;
5641 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005642
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005643 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005644 return 1;
5645}
5646
5647/* This function set the query-string. */
5648static int hlua_http_req_set_query(lua_State *L)
5649{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005650 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005651 size_t name_len;
5652 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005653
5654 /* Check length. */
5655 if (name_len > trash.size - 1) {
5656 lua_pushboolean(L, 0);
5657 return 1;
5658 }
5659
5660 /* Add the mark question as prefix. */
5661 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005662 trash.area[trash.data++] = '?';
5663 memcpy(trash.area + trash.data, name, name_len);
5664 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005665
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005666 lua_pushboolean(L,
5667 http_replace_req_line(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005668 return 1;
5669}
5670
5671/* This function set the uri. */
5672static int hlua_http_req_set_uri(lua_State *L)
5673{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005674 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005675 size_t name_len;
5676 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005677
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005678 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005679 return 1;
5680}
5681
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005682/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005683static int hlua_http_res_set_status(lua_State *L)
5684{
5685 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5686 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005687 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005688
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005689 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005690 return 0;
5691}
5692
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005693/*
5694 *
5695 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005696 * Class TXN
5697 *
5698 *
5699 */
5700
5701/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005702 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005703 */
5704__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5705{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005706 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005707}
5708
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005709__LJMP static int hlua_set_var(lua_State *L)
5710{
5711 struct hlua_txn *htxn;
5712 const char *name;
5713 size_t len;
5714 struct sample smp;
5715
5716 MAY_LJMP(check_args(L, 3, "set_var"));
5717
5718 /* It is useles to retrieve the stream, but this function
5719 * runs only in a stream context.
5720 */
5721 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5722 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5723
5724 /* Converts the third argument in a sample. */
5725 hlua_lua2smp(L, 3, &smp);
5726
5727 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005728 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005729 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005730 return 0;
5731}
5732
Christopher Faulet85d79c92016-11-09 16:54:56 +01005733__LJMP static int hlua_unset_var(lua_State *L)
5734{
5735 struct hlua_txn *htxn;
5736 const char *name;
5737 size_t len;
5738 struct sample smp;
5739
5740 MAY_LJMP(check_args(L, 2, "unset_var"));
5741
5742 /* It is useles to retrieve the stream, but this function
5743 * runs only in a stream context.
5744 */
5745 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5746 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5747
5748 /* Unset the variable. */
5749 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5750 vars_unset_by_name(name, len, &smp);
5751 return 0;
5752}
5753
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005754__LJMP static int hlua_get_var(lua_State *L)
5755{
5756 struct hlua_txn *htxn;
5757 const char *name;
5758 size_t len;
5759 struct sample smp;
5760
5761 MAY_LJMP(check_args(L, 2, "get_var"));
5762
5763 /* It is useles to retrieve the stream, but this function
5764 * runs only in a stream context.
5765 */
5766 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5767 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5768
Willy Tarreau7560dd42016-03-10 16:28:58 +01005769 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005770 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005771 lua_pushnil(L);
5772 return 1;
5773 }
5774
5775 return hlua_smp2lua(L, &smp);
5776}
5777
Willy Tarreau59551662015-03-10 14:23:13 +01005778__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005779{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005780 struct hlua *hlua;
5781
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005782 MAY_LJMP(check_args(L, 2, "set_priv"));
5783
Willy Tarreau87b09662015-04-03 00:22:06 +02005784 /* It is useles to retrieve the stream, but this function
5785 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005786 */
5787 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005788 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005789
5790 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005791 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005792
5793 /* Get and store new value. */
5794 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5795 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5796
5797 return 0;
5798}
5799
Willy Tarreau59551662015-03-10 14:23:13 +01005800__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005801{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005802 struct hlua *hlua;
5803
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005804 MAY_LJMP(check_args(L, 1, "get_priv"));
5805
Willy Tarreau87b09662015-04-03 00:22:06 +02005806 /* It is useles to retrieve the stream, but this function
5807 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005808 */
5809 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005810 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005811
5812 /* Push configuration index in the stack. */
5813 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5814
5815 return 1;
5816}
5817
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005818/* Create stack entry containing a class TXN. This function
5819 * return 0 if the stack does not contains free slots,
5820 * otherwise it returns 1.
5821 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005822static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005823{
Willy Tarreaude491382015-04-06 11:04:28 +02005824 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005825
5826 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005827 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005828 return 0;
5829
5830 /* NOTE: The allocation never fails. The failure
5831 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005832 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005833 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005834 /* Create the object: obj[0] = userdata. */
5835 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005836 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005837 lua_rawseti(L, -2, 0);
5838
Willy Tarreaude491382015-04-06 11:04:28 +02005839 htxn->s = s;
5840 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005841 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005842 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005843
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005844 /* Create the "f" field that contains a list of fetches. */
5845 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005846 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005847 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005848 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005849
5850 /* Create the "sf" field that contains a list of stringsafe fetches. */
5851 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005852 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005853 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005854 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005855
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005856 /* Create the "c" field that contains a list of converters. */
5857 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005858 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005859 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005860 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005861
5862 /* Create the "sc" field that contains a list of stringsafe converters. */
5863 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005864 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005865 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005866 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005867
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005868 /* Create the "req" field that contains the request channel object. */
5869 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005870 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005871 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005872 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005873
5874 /* Create the "res" field that contains the response channel object. */
5875 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005876 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005877 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005878 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005879
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005880 /* Creates the HTTP object is the current proxy allows http. */
5881 lua_pushstring(L, "http");
5882 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005883 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005884 return 0;
5885 }
5886 else
5887 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005888 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005889
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005890 /* Pop a class sesison metatable and affect it to the userdata. */
5891 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5892 lua_setmetatable(L, -2);
5893
5894 return 1;
5895}
5896
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005897__LJMP static int hlua_txn_deflog(lua_State *L)
5898{
5899 const char *msg;
5900 struct hlua_txn *htxn;
5901
5902 MAY_LJMP(check_args(L, 2, "deflog"));
5903 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5904 msg = MAY_LJMP(luaL_checkstring(L, 2));
5905
5906 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5907 return 0;
5908}
5909
5910__LJMP static int hlua_txn_log(lua_State *L)
5911{
5912 int level;
5913 const char *msg;
5914 struct hlua_txn *htxn;
5915
5916 MAY_LJMP(check_args(L, 3, "log"));
5917 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5918 level = MAY_LJMP(luaL_checkinteger(L, 2));
5919 msg = MAY_LJMP(luaL_checkstring(L, 3));
5920
5921 if (level < 0 || level >= NB_LOG_LEVELS)
5922 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5923
5924 hlua_sendlog(htxn->s->be, level, msg);
5925 return 0;
5926}
5927
5928__LJMP static int hlua_txn_log_debug(lua_State *L)
5929{
5930 const char *msg;
5931 struct hlua_txn *htxn;
5932
5933 MAY_LJMP(check_args(L, 2, "Debug"));
5934 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5935 msg = MAY_LJMP(luaL_checkstring(L, 2));
5936 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5937 return 0;
5938}
5939
5940__LJMP static int hlua_txn_log_info(lua_State *L)
5941{
5942 const char *msg;
5943 struct hlua_txn *htxn;
5944
5945 MAY_LJMP(check_args(L, 2, "Info"));
5946 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5947 msg = MAY_LJMP(luaL_checkstring(L, 2));
5948 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5949 return 0;
5950}
5951
5952__LJMP static int hlua_txn_log_warning(lua_State *L)
5953{
5954 const char *msg;
5955 struct hlua_txn *htxn;
5956
5957 MAY_LJMP(check_args(L, 2, "Warning"));
5958 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5959 msg = MAY_LJMP(luaL_checkstring(L, 2));
5960 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5961 return 0;
5962}
5963
5964__LJMP static int hlua_txn_log_alert(lua_State *L)
5965{
5966 const char *msg;
5967 struct hlua_txn *htxn;
5968
5969 MAY_LJMP(check_args(L, 2, "Alert"));
5970 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5971 msg = MAY_LJMP(luaL_checkstring(L, 2));
5972 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5973 return 0;
5974}
5975
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005976__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5977{
5978 struct hlua_txn *htxn;
5979 int ll;
5980
5981 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5982 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5983 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5984
5985 if (ll < 0 || ll > 7)
5986 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5987
5988 htxn->s->logs.level = ll;
5989 return 0;
5990}
5991
5992__LJMP static int hlua_txn_set_tos(lua_State *L)
5993{
5994 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005995 int tos;
5996
5997 MAY_LJMP(check_args(L, 2, "set_tos"));
5998 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5999 tos = MAY_LJMP(luaL_checkinteger(L, 2));
6000
Willy Tarreau1a18b542018-12-11 16:37:42 +01006001 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006002 return 0;
6003}
6004
6005__LJMP static int hlua_txn_set_mark(lua_State *L)
6006{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006007 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006008 int mark;
6009
6010 MAY_LJMP(check_args(L, 2, "set_mark"));
6011 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6012 mark = MAY_LJMP(luaL_checkinteger(L, 2));
6013
Willy Tarreau1a18b542018-12-11 16:37:42 +01006014 conn_set_tos(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01006015 return 0;
6016}
6017
Patrick Hemmer268a7072018-05-11 12:52:31 -04006018__LJMP static int hlua_txn_set_priority_class(lua_State *L)
6019{
6020 struct hlua_txn *htxn;
6021
6022 MAY_LJMP(check_args(L, 2, "set_priority_class"));
6023 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6024 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
6025 return 0;
6026}
6027
6028__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
6029{
6030 struct hlua_txn *htxn;
6031
6032 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
6033 htxn = MAY_LJMP(hlua_checktxn(L, 1));
6034 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
6035 return 0;
6036}
6037
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006038/* This function is an Lua binding that send pending data
6039 * to the client, and close the stream interface.
6040 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006041__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006042{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006043 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006044 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01006045 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006046
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006047 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006048 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006049 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006050
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006051 /* If the flags NOTERM is set, we cannot terminate the http
6052 * session, so we just end the execution of the current
6053 * lua code.
6054 */
6055 if (htxn->flags & HLUA_TXN_NOTERM) {
6056 WILL_LJMP(hlua_done(L));
6057 return 0;
6058 }
6059
Willy Tarreaub2ccb562015-04-06 11:11:15 +02006060 ic = &htxn->s->req;
6061 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01006062
Willy Tarreau630ef452015-08-28 10:06:15 +02006063 if (htxn->s->txn) {
6064 /* HTTP mode, let's stay in sync with the stream */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02006065 b_del(&ic->buf, htxn->s->txn->req.sov);
Willy Tarreau630ef452015-08-28 10:06:15 +02006066 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
6067 htxn->s->txn->req.sov = 0;
6068 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
6069 oc->analysers = AN_RES_HTTP_XFER_BODY;
6070 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
6071 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
6072
Willy Tarreau630ef452015-08-28 10:06:15 +02006073 /* Note that if we want to support keep-alive, we need
6074 * to bypass the close/shutr_now calls below, but that
6075 * may only be done if the HTTP request was already
6076 * processed and the connection header is known (ie
6077 * not during TCP rules).
6078 */
6079 }
6080
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006081 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01006082 channel_abort(ic);
6083 channel_auto_close(ic);
6084 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02006085
6086 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01006087 channel_auto_read(oc);
6088 channel_auto_close(oc);
6089 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006090
Willy Tarreau0458b082015-08-28 09:40:04 +02006091 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006092
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006093 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02006094 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006095 return 0;
6096}
6097
6098__LJMP static int hlua_log(lua_State *L)
6099{
6100 int level;
6101 const char *msg;
6102
6103 MAY_LJMP(check_args(L, 2, "log"));
6104 level = MAY_LJMP(luaL_checkinteger(L, 1));
6105 msg = MAY_LJMP(luaL_checkstring(L, 2));
6106
6107 if (level < 0 || level >= NB_LOG_LEVELS)
6108 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
6109
6110 hlua_sendlog(NULL, level, msg);
6111 return 0;
6112}
6113
6114__LJMP static int hlua_log_debug(lua_State *L)
6115{
6116 const char *msg;
6117
6118 MAY_LJMP(check_args(L, 1, "debug"));
6119 msg = MAY_LJMP(luaL_checkstring(L, 1));
6120 hlua_sendlog(NULL, LOG_DEBUG, msg);
6121 return 0;
6122}
6123
6124__LJMP static int hlua_log_info(lua_State *L)
6125{
6126 const char *msg;
6127
6128 MAY_LJMP(check_args(L, 1, "info"));
6129 msg = MAY_LJMP(luaL_checkstring(L, 1));
6130 hlua_sendlog(NULL, LOG_INFO, msg);
6131 return 0;
6132}
6133
6134__LJMP static int hlua_log_warning(lua_State *L)
6135{
6136 const char *msg;
6137
6138 MAY_LJMP(check_args(L, 1, "warning"));
6139 msg = MAY_LJMP(luaL_checkstring(L, 1));
6140 hlua_sendlog(NULL, LOG_WARNING, msg);
6141 return 0;
6142}
6143
6144__LJMP static int hlua_log_alert(lua_State *L)
6145{
6146 const char *msg;
6147
6148 MAY_LJMP(check_args(L, 1, "alert"));
6149 msg = MAY_LJMP(luaL_checkstring(L, 1));
6150 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006151 return 0;
6152}
6153
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006154__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006155{
6156 int wakeup_ms = lua_tointeger(L, -1);
6157 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02006158 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006159 return 0;
6160}
6161
6162__LJMP static int hlua_sleep(lua_State *L)
6163{
6164 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006165 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006166
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006167 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006168
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006169 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006170 wakeup_ms = tick_add(now_ms, delay);
6171 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006172
Willy Tarreau9635e032018-10-16 17:52:55 +02006173 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006174 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006175}
6176
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006177__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006178{
6179 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006180 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006181
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006182 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006183
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006184 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006185 wakeup_ms = tick_add(now_ms, delay);
6186 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006187
Willy Tarreau9635e032018-10-16 17:52:55 +02006188 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006189 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006190}
6191
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006192/* This functionis an LUA binding. it permits to give back
6193 * the hand at the HAProxy scheduler. It is used when the
6194 * LUA processing consumes a lot of time.
6195 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006196__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006197{
6198 return 0;
6199}
6200
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006201__LJMP static int hlua_yield(lua_State *L)
6202{
Willy Tarreau9635e032018-10-16 17:52:55 +02006203 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006204 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006205}
6206
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006207/* This function change the nice of the currently executed
6208 * task. It is used set low or high priority at the current
6209 * task.
6210 */
Willy Tarreau59551662015-03-10 14:23:13 +01006211__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006212{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006213 struct hlua *hlua;
6214 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006215
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006216 MAY_LJMP(check_args(L, 1, "set_nice"));
6217 hlua = hlua_gethlua(L);
6218 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006219
6220 /* If he task is not set, I'm in a start mode. */
6221 if (!hlua || !hlua->task)
6222 return 0;
6223
6224 if (nice < -1024)
6225 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006226 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006227 nice = 1024;
6228
6229 hlua->task->nice = nice;
6230 return 0;
6231}
6232
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006233/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006234 * HAProxy task subsystem when the task is awaked. The LUA runtime can
6235 * return an E_AGAIN signal, the emmiter of this signal must set a
6236 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006237 *
6238 * Task wrapper are longjmp safe because the only one Lua code
6239 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006240 */
Olivier Houchard9f6af332018-05-25 14:04:04 +02006241static struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006242{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006243 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006244 enum hlua_exec status;
6245
Christopher Faulet5bc99722018-04-25 10:34:45 +02006246 if (task->thread_mask == MAX_THREADS_MASK)
6247 task_set_affinity(task, tid_bit);
6248
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006249 /* If it is the first call to the task, we must initialize the
6250 * execution timeouts.
6251 */
6252 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006253 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006254
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006255 /* Execute the Lua code. */
6256 status = hlua_ctx_resume(hlua, 1);
6257
6258 switch (status) {
6259 /* finished or yield */
6260 case HLUA_E_OK:
6261 hlua_ctx_destroy(hlua);
6262 task_delete(task);
6263 task_free(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006264 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006265 break;
6266
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006267 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006268 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006269 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006270 break;
6271
6272 /* finished with error. */
6273 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006274 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006275 hlua_ctx_destroy(hlua);
6276 task_delete(task);
6277 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006278 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006279 break;
6280
6281 case HLUA_E_ERR:
6282 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006283 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006284 hlua_ctx_destroy(hlua);
6285 task_delete(task);
6286 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006287 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006288 break;
6289 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006290 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006291}
6292
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006293/* This function is an LUA binding that register LUA function to be
6294 * executed after the HAProxy configuration parsing and before the
6295 * HAProxy scheduler starts. This function expect only one LUA
6296 * argument that is a function. This function returns nothing, but
6297 * throws if an error is encountered.
6298 */
6299__LJMP static int hlua_register_init(lua_State *L)
6300{
6301 struct hlua_init_function *init;
6302 int ref;
6303
6304 MAY_LJMP(check_args(L, 1, "register_init"));
6305
6306 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6307
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006308 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006309 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006310 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006311
6312 init->function_ref = ref;
6313 LIST_ADDQ(&hlua_init_functions, &init->l);
6314 return 0;
6315}
6316
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006317/* This functio is an LUA binding. It permits to register a task
6318 * executed in parallel of the main HAroxy activity. The task is
6319 * created and it is set in the HAProxy scheduler. It can be called
6320 * from the "init" section, "post init" or during the runtime.
6321 *
6322 * Lua prototype:
6323 *
6324 * <none> core.register_task(<function>)
6325 */
6326static int hlua_register_task(lua_State *L)
6327{
6328 struct hlua *hlua;
6329 struct task *task;
6330 int ref;
6331
6332 MAY_LJMP(check_args(L, 1, "register_task"));
6333
6334 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6335
Willy Tarreaubafbe012017-11-24 17:34:44 +01006336 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006337 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006338 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006339
Emeric Brunc60def82017-09-27 14:59:38 +02006340 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006341 if (!task)
6342 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6343
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006344 task->context = hlua;
6345 task->process = hlua_process_task;
6346
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006347 if (!hlua_ctx_init(hlua, task, 1))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006348 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006349
6350 /* Restore the function in the stack. */
6351 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6352 hlua->nargs = 0;
6353
6354 /* Schedule task. */
6355 task_schedule(task, now_ms);
6356
6357 return 0;
6358}
6359
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006360/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6361 * doesn't allow "yield" functions because the HAProxy engine cannot
6362 * resume converters.
6363 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006364static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006365{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006366 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006367 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006368 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006369
Willy Tarreaube508f12016-03-10 11:47:01 +01006370 if (!stream)
6371 return 0;
6372
Willy Tarreau87b09662015-04-03 00:22:06 +02006373 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006374 * Lua context can be not initialized. This behavior
6375 * permits to save performances because a systematic
6376 * Lua initialization cause 5% performances loss.
6377 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006378 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006379 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006380 if (!stream->hlua) {
6381 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6382 return 0;
6383 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006384 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006385 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6386 return 0;
6387 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006388 }
6389
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006390 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006391 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006392
6393 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006394 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6395 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6396 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006397 else
6398 error = "critical error";
6399 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006400 return 0;
6401 }
6402
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006403 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006404 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006405 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006406 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006407 return 0;
6408 }
6409
6410 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006411 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006412
6413 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006414 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006415 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006416 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006417 return 0;
6418 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006419 hlua_smp2lua(stream->hlua->T, smp);
6420 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006421
6422 /* push keywords in the stack. */
6423 if (arg_p) {
6424 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006425 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006426 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006427 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006428 return 0;
6429 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006430 hlua_arg2lua(stream->hlua->T, arg_p);
6431 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006432 }
6433 }
6434
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006435 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006436 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006437
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006438 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006439 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006440 }
6441
6442 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006443 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006444 /* finished. */
6445 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006446 /* If the stack is empty, the function fails. */
6447 if (lua_gettop(stream->hlua->T) <= 0)
6448 return 0;
6449
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006450 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006451 hlua_lua2smp(stream->hlua->T, -1, smp);
6452 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006453 return 1;
6454
6455 /* yield. */
6456 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006457 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006458 return 0;
6459
6460 /* finished with error. */
6461 case HLUA_E_ERRMSG:
6462 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006463 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006464 fcn->name, lua_tostring(stream->hlua->T, -1));
6465 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006466 return 0;
6467
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006468 case HLUA_E_ETMOUT:
6469 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6470 return 0;
6471
6472 case HLUA_E_NOMEM:
6473 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6474 return 0;
6475
6476 case HLUA_E_YIELD:
6477 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6478 return 0;
6479
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006480 case HLUA_E_ERR:
6481 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006482 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006483
6484 default:
6485 return 0;
6486 }
6487}
6488
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006489/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6490 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006491 * resume sample-fetches. This function will be called by the sample
6492 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006493 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006494static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6495 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006496{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006497 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006498 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006499 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006500 const struct buffer msg = { };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006501
Willy Tarreaube508f12016-03-10 11:47:01 +01006502 if (!stream)
6503 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006504
Willy Tarreau87b09662015-04-03 00:22:06 +02006505 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006506 * Lua context can be not initialized. This behavior
6507 * permits to save performances because a systematic
6508 * Lua initialization cause 5% performances loss.
6509 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006510 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006511 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006512 if (!stream->hlua) {
6513 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6514 return 0;
6515 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006516 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006517 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6518 return 0;
6519 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006520 }
6521
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006522 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006523
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006524 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006525 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006526
6527 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006528 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6529 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6530 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006531 else
6532 error = "critical error";
6533 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006534 return 0;
6535 }
6536
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006537 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006538 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006539 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006540 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006541 return 0;
6542 }
6543
6544 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006545 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006546
6547 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006548 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02006549 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006550 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006551 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006552 return 0;
6553 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006554 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006555
6556 /* push keywords in the stack. */
6557 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6558 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006559 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006560 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006561 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006562 return 0;
6563 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006564 hlua_arg2lua(stream->hlua->T, arg_p);
6565 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006566 }
6567
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006568 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006569 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006570
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006571 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006572 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006573 }
6574
6575 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006576 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006577 /* finished. */
6578 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006579 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006580 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006581 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006582 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006583 /* If the stack is empty, the function fails. */
6584 if (lua_gettop(stream->hlua->T) <= 0)
6585 return 0;
6586
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006587 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006588 hlua_lua2smp(stream->hlua->T, -1, smp);
6589 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006590
6591 /* Set the end of execution flag. */
6592 smp->flags &= ~SMP_F_MAY_CHANGE;
6593 return 1;
6594
6595 /* yield. */
6596 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006597 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006598 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006599 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006600 return 0;
6601
6602 /* finished with error. */
6603 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006604 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006605 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006606 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006607 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006608 fcn->name, lua_tostring(stream->hlua->T, -1));
6609 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006610 return 0;
6611
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006612 case HLUA_E_ETMOUT:
6613 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006614 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006615 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6616 return 0;
6617
6618 case HLUA_E_NOMEM:
6619 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006620 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006621 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6622 return 0;
6623
6624 case HLUA_E_YIELD:
6625 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006626 si_retnclose(&stream->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006627 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6628 return 0;
6629
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006630 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006631 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006632 si_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006633 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006634 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006635
6636 default:
6637 return 0;
6638 }
6639}
6640
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006641/* This function is an LUA binding used for registering
6642 * "sample-conv" functions. It expects a converter name used
6643 * in the haproxy configuration file, and an LUA function.
6644 */
6645__LJMP static int hlua_register_converters(lua_State *L)
6646{
6647 struct sample_conv_kw_list *sck;
6648 const char *name;
6649 int ref;
6650 int len;
6651 struct hlua_function *fcn;
6652
6653 MAY_LJMP(check_args(L, 2, "register_converters"));
6654
6655 /* First argument : converter name. */
6656 name = MAY_LJMP(luaL_checkstring(L, 1));
6657
6658 /* Second argument : lua function. */
6659 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6660
6661 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006662 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006663 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006664 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006665 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006666 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006667 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006668
6669 /* Fill fcn. */
6670 fcn->name = strdup(name);
6671 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006672 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006673 fcn->function_ref = ref;
6674
6675 /* List head */
6676 sck->list.n = sck->list.p = NULL;
6677
6678 /* converter keyword. */
6679 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006680 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006681 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006682 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006683
6684 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6685 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006686 sck->kw[0].arg_mask = ARG12(0,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006687 sck->kw[0].val_args = NULL;
6688 sck->kw[0].in_type = SMP_T_STR;
6689 sck->kw[0].out_type = SMP_T_STR;
6690 sck->kw[0].private = fcn;
6691
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006692 /* Register this new converter */
6693 sample_register_convs(sck);
6694
6695 return 0;
6696}
6697
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006698/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006699 * "sample-fetch" functions. It expects a converter name used
6700 * in the haproxy configuration file, and an LUA function.
6701 */
6702__LJMP static int hlua_register_fetches(lua_State *L)
6703{
6704 const char *name;
6705 int ref;
6706 int len;
6707 struct sample_fetch_kw_list *sfk;
6708 struct hlua_function *fcn;
6709
6710 MAY_LJMP(check_args(L, 2, "register_fetches"));
6711
6712 /* First argument : sample-fetch name. */
6713 name = MAY_LJMP(luaL_checkstring(L, 1));
6714
6715 /* Second argument : lua function. */
6716 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6717
6718 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006719 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006720 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006721 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006722 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006723 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006724 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006725
6726 /* Fill fcn. */
6727 fcn->name = strdup(name);
6728 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006729 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006730 fcn->function_ref = ref;
6731
6732 /* List head */
6733 sfk->list.n = sfk->list.p = NULL;
6734
6735 /* sample-fetch keyword. */
6736 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006737 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006738 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006739 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006740
6741 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6742 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006743 sfk->kw[0].arg_mask = ARG12(0,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR,STR);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006744 sfk->kw[0].val_args = NULL;
6745 sfk->kw[0].out_type = SMP_T_STR;
6746 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6747 sfk->kw[0].val = 0;
6748 sfk->kw[0].private = fcn;
6749
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006750 /* Register this new fetch. */
6751 sample_register_fetches(sfk);
6752
6753 return 0;
6754}
6755
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006756/* This function is a wrapper to execute each LUA function declared
6757 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006758 * return ACT_RET_CONT if the processing is finished (with or without
6759 * error) and return ACT_RET_YIELD if the function must be called again
6760 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006761 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006762static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006763 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006764{
6765 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006766 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006767 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006768 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006769 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006770
6771 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006772 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6773 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6774 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6775 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006776 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006777 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006778 return ACT_RET_CONT;
6779 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006780
Willy Tarreau87b09662015-04-03 00:22:06 +02006781 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006782 * Lua context can be not initialized. This behavior
6783 * permits to save performances because a systematic
6784 * Lua initialization cause 5% performances loss.
6785 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006786 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006787 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006788 if (!s->hlua) {
6789 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6790 rule->arg.hlua_rule->fcn.name);
6791 return ACT_RET_CONT;
6792 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006793 if (!hlua_ctx_init(s->hlua, s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006794 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6795 rule->arg.hlua_rule->fcn.name);
6796 return ACT_RET_CONT;
6797 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006798 }
6799
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006800 consistency_set(s, dir, &s->hlua->cons);
6801
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006802 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006803 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006804
6805 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006806 if (!SET_SAFE_LJMP(s->hlua->T)) {
6807 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6808 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006809 else
6810 error = "critical error";
6811 SEND_ERR(px, "Lua function '%s': %s.\n",
6812 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006813 return ACT_RET_CONT;
6814 }
6815
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006816 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006817 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006818 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006819 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006820 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006821 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006822 }
6823
6824 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006825 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006826
Willy Tarreau87b09662015-04-03 00:22:06 +02006827 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006828 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006829 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006830 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006831 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006832 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006833 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006834 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006835
6836 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006837 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006838 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006839 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006840 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006841 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006842 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006843 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006844 lua_pushstring(s->hlua->T, *arg);
6845 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006846 }
6847
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006848 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006849 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006850
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006851 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006852 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006853 }
6854
6855 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006856 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006857 /* finished. */
6858 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006859 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006860 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006861 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006862 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006863 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006864 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006865 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006866
6867 /* yield. */
6868 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006869 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006870 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006871 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006872 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006873 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006874 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006875 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006876 /* Some actions can be wake up when a "write" event
6877 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006878 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006879 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006880 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006881 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006882 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006883 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006884 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006885 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006886 s->req.flags |= CF_WAKE_WRITE;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006887 /* We can quit the function without consistency check
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006888 * because HAProxy is not able to manipulate data, it
6889 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006890 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006891
6892 /* finished with error. */
6893 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006894 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006895 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006896 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006897 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006898 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006899 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006900 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6901 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006902 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006903
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006904 case HLUA_E_ETMOUT:
6905 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006906 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006907 return ACT_RET_ERR;
6908 }
6909 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6910 return 0;
6911
6912 case HLUA_E_NOMEM:
6913 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006914 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006915 return ACT_RET_ERR;
6916 }
6917 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6918 return 0;
6919
6920 case HLUA_E_YIELD:
6921 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006922 si_retnclose(&s->si[0], &msg);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006923 return ACT_RET_ERR;
6924 }
6925 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6926 rule->arg.hlua_rule->fcn.name);
6927 return 0;
6928
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006929 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006930 if (!consistency_check(s, dir, &s->hlua->cons)) {
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01006931 si_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006932 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006933 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006934 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006935 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006936 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006937
6938 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006939 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006940 }
6941}
6942
Olivier Houchard9f6af332018-05-25 14:04:04 +02006943struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006944{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006945 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006946
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006947 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006948 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006949 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006950}
6951
6952static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6953{
6954 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006955 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006956 struct task *task;
6957 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006958 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006959
Willy Tarreaubafbe012017-11-24 17:34:44 +01006960 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006961 if (!hlua) {
6962 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6963 ctx->rule->arg.hlua_rule->fcn.name);
6964 return 0;
6965 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006966 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006967 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006968 ctx->ctx.hlua_apptcp.flags = 0;
6969
6970 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006971 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006972 if (!task) {
6973 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6974 ctx->rule->arg.hlua_rule->fcn.name);
6975 return 0;
6976 }
6977 task->nice = 0;
6978 task->context = ctx;
6979 task->process = hlua_applet_wakeup;
6980 ctx->ctx.hlua_apptcp.task = task;
6981
6982 /* In the execution wrappers linked with a stream, the
6983 * Lua context can be not initialized. This behavior
6984 * permits to save performances because a systematic
6985 * Lua initialization cause 5% performances loss.
6986 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006987 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006988 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6989 ctx->rule->arg.hlua_rule->fcn.name);
6990 return 0;
6991 }
6992
6993 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006994 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006995
6996 /* The following Lua calls can fail. */
6997 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006998 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6999 error = lua_tostring(hlua->T, -1);
7000 else
7001 error = "critical error";
7002 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7003 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007004 return 0;
7005 }
7006
7007 /* Check stack available size. */
7008 if (!lua_checkstack(hlua->T, 1)) {
7009 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7010 ctx->rule->arg.hlua_rule->fcn.name);
7011 RESET_SAFE_LJMP(hlua->T);
7012 return 0;
7013 }
7014
7015 /* Restore the function in the stack. */
7016 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7017
7018 /* Create and and push object stream in the stack. */
7019 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
7020 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7021 ctx->rule->arg.hlua_rule->fcn.name);
7022 RESET_SAFE_LJMP(hlua->T);
7023 return 0;
7024 }
7025 hlua->nargs = 1;
7026
7027 /* push keywords in the stack. */
7028 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7029 if (!lua_checkstack(hlua->T, 1)) {
7030 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
7031 ctx->rule->arg.hlua_rule->fcn.name);
7032 RESET_SAFE_LJMP(hlua->T);
7033 return 0;
7034 }
7035 lua_pushstring(hlua->T, *arg);
7036 hlua->nargs++;
7037 }
7038
7039 RESET_SAFE_LJMP(hlua->T);
7040
7041 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007042 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01007043 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007044
7045 return 1;
7046}
7047
7048static void hlua_applet_tcp_fct(struct appctx *ctx)
7049{
7050 struct stream_interface *si = ctx->owner;
7051 struct stream *strm = si_strm(si);
7052 struct channel *res = si_ic(si);
7053 struct act_rule *rule = ctx->rule;
7054 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007055 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007056
7057 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02007058 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
7059 /* eat the whole request */
7060 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007061 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02007062 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007063
7064 /* If the stream is disconnect or closed, ldo nothing. */
7065 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7066 return;
7067
7068 /* Execute the function. */
7069 switch (hlua_ctx_resume(hlua, 1)) {
7070 /* finished. */
7071 case HLUA_E_OK:
7072 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7073
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007074 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007075 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007076 res->flags |= CF_READ_NULL;
7077 si_shutr(si);
7078 return;
7079
7080 /* yield. */
7081 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007082 if (hlua->wake_time != TICK_ETERNITY)
7083 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007084 return;
7085
7086 /* finished with error. */
7087 case HLUA_E_ERRMSG:
7088 /* Display log. */
7089 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
7090 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7091 lua_pop(hlua->T, 1);
7092 goto error;
7093
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007094 case HLUA_E_ETMOUT:
7095 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
7096 rule->arg.hlua_rule->fcn.name);
7097 goto error;
7098
7099 case HLUA_E_NOMEM:
7100 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
7101 rule->arg.hlua_rule->fcn.name);
7102 goto error;
7103
7104 case HLUA_E_YIELD: /* unexpected */
7105 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
7106 rule->arg.hlua_rule->fcn.name);
7107 goto error;
7108
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007109 case HLUA_E_ERR:
7110 /* Display log. */
7111 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
7112 rule->arg.hlua_rule->fcn.name);
7113 goto error;
7114
7115 default:
7116 goto error;
7117 }
7118
7119error:
7120
7121 /* For all other cases, just close the stream. */
7122 si_shutw(si);
7123 si_shutr(si);
7124 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7125}
7126
7127static void hlua_applet_tcp_release(struct appctx *ctx)
7128{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02007129 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007130 task_free(ctx->ctx.hlua_apptcp.task);
7131 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007132 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007133 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007134}
7135
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007136/* The function returns 1 if the initialisation is complete, 0 if
7137 * an errors occurs and -1 if more data are required for initializing
7138 * the applet.
7139 */
7140static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7141{
7142 struct stream_interface *si = ctx->owner;
7143 struct channel *req = si_oc(si);
7144 struct http_msg *msg;
7145 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007146 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007147 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007148 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007149 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007150
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007151 txn = strm->txn;
7152 msg = &txn->req;
7153
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007154 /* We want two things in HTTP mode :
7155 * - enforce server-close mode if we were in keep-alive, so that the
7156 * applet is released after each response ;
7157 * - enable request body transfer to the applet in order to resync
7158 * with the response body.
7159 */
7160 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
7161 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02007162
Willy Tarreaubafbe012017-11-24 17:34:44 +01007163 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007164 if (!hlua) {
7165 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7166 ctx->rule->arg.hlua_rule->fcn.name);
7167 return 0;
7168 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007169 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007170 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007171 ctx->ctx.hlua_apphttp.left_bytes = -1;
7172 ctx->ctx.hlua_apphttp.flags = 0;
7173
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01007174 if (txn->req.flags & HTTP_MSGF_VER_11)
7175 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
7176
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007177 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007178 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007179 if (!task) {
7180 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
7181 ctx->rule->arg.hlua_rule->fcn.name);
7182 return 0;
7183 }
7184 task->nice = 0;
7185 task->context = ctx;
7186 task->process = hlua_applet_wakeup;
7187 ctx->ctx.hlua_apphttp.task = task;
7188
7189 /* In the execution wrappers linked with a stream, the
7190 * Lua context can be not initialized. This behavior
7191 * permits to save performances because a systematic
7192 * Lua initialization cause 5% performances loss.
7193 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007194 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007195 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
7196 ctx->rule->arg.hlua_rule->fcn.name);
7197 return 0;
7198 }
7199
7200 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007201 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007202
7203 /* The following Lua calls can fail. */
7204 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007205 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7206 error = lua_tostring(hlua->T, -1);
7207 else
7208 error = "critical error";
7209 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7210 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007211 return 0;
7212 }
7213
7214 /* Check stack available size. */
7215 if (!lua_checkstack(hlua->T, 1)) {
7216 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7217 ctx->rule->arg.hlua_rule->fcn.name);
7218 RESET_SAFE_LJMP(hlua->T);
7219 return 0;
7220 }
7221
7222 /* Restore the function in the stack. */
7223 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
7224
7225 /* Create and and push object stream in the stack. */
7226 if (!hlua_applet_http_new(hlua->T, ctx)) {
7227 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7228 ctx->rule->arg.hlua_rule->fcn.name);
7229 RESET_SAFE_LJMP(hlua->T);
7230 return 0;
7231 }
7232 hlua->nargs = 1;
7233
7234 /* Look for a 100-continue expected. */
7235 if (msg->flags & HTTP_MSGF_VER_11) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007236 if (IS_HTX_STRM(si_strm(si))) {
7237 /* HTX version */
7238 struct htx *htx = htxbuf(&req->buf);
7239 struct ist hdr = { .ptr = "Expect", .len = 6 };
7240 struct http_hdr_ctx hdr_ctx;
7241
7242 hdr_ctx.blk = NULL;
7243 /* Expect is allowed in 1.1, look for it */
7244 if (http_find_header(htx, hdr, &hdr_ctx, 0) &&
7245 unlikely(isteqi(hdr_ctx.value, ist2("100-continue", 12))))
7246 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
7247 }
7248 else {
7249 /* Legacy HTTP version */
7250 struct hdr_ctx hdr;
7251
7252 hdr.idx = 0;
7253 if (http_find_header2("Expect", 6, ci_head(req), &txn->hdr_idx, &hdr) &&
7254 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
7255 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
7256 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007257 }
7258
7259 /* push keywords in the stack. */
7260 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7261 if (!lua_checkstack(hlua->T, 1)) {
7262 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
7263 ctx->rule->arg.hlua_rule->fcn.name);
7264 RESET_SAFE_LJMP(hlua->T);
7265 return 0;
7266 }
7267 lua_pushstring(hlua->T, *arg);
7268 hlua->nargs++;
7269 }
7270
7271 RESET_SAFE_LJMP(hlua->T);
7272
7273 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007274 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007275
7276 return 1;
7277}
7278
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007279static void hlua_applet_htx_fct(struct appctx *ctx)
7280{
7281 struct stream_interface *si = ctx->owner;
7282 struct stream *strm = si_strm(si);
7283 struct channel *req = si_oc(si);
7284 struct channel *res = si_ic(si);
7285 struct act_rule *rule = ctx->rule;
7286 struct proxy *px = strm->be;
7287 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
7288 struct htx *req_htx, *res_htx;
7289
7290 res_htx = htx_from_buf(&res->buf);
7291
7292 /* If the stream is disconnect or closed, ldo nothing. */
7293 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7294 goto out;
7295
7296 /* Check if the input buffer is avalaible. */
7297 if (!b_size(&res->buf)) {
7298 si_rx_room_blk(si);
7299 goto out;
7300 }
7301 /* check that the output is not closed */
7302 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW))
7303 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7304
7305 /* Set the currently running flag. */
7306 if (!HLUA_IS_RUNNING(hlua) &&
7307 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7308 struct htx_blk *blk;
7309 size_t count = co_data(req);
7310
7311 if (!count) {
7312 si_cant_get(si);
7313 goto out;
7314 }
7315
7316 /* We need to flush the request header. This left the body for
7317 * the Lua.
7318 */
7319 req_htx = htx_from_buf(&req->buf);
7320 blk = htx_get_head_blk(req_htx);
7321 while (count && blk) {
7322 enum htx_blk_type type = htx_get_blk_type(blk);
7323 uint32_t sz = htx_get_blksz(blk);
7324
7325 if (sz > count) {
7326 si_cant_get(si);
7327 goto out;
7328 }
7329
7330 count -= sz;
7331 co_set_data(req, co_data(req) - sz);
7332 blk = htx_remove_blk(req_htx, blk);
7333
7334 if (type == HTX_BLK_EOH)
7335 break;
7336 }
7337 }
7338
7339 /* Executes The applet if it is not done. */
7340 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7341
7342 /* Execute the function. */
7343 switch (hlua_ctx_resume(hlua, 1)) {
7344 /* finished. */
7345 case HLUA_E_OK:
7346 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7347 break;
7348
7349 /* yield. */
7350 case HLUA_E_AGAIN:
7351 if (hlua->wake_time != TICK_ETERNITY)
7352 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
7353 return;
7354
7355 /* finished with error. */
7356 case HLUA_E_ERRMSG:
7357 /* Display log. */
7358 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7359 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7360 lua_pop(hlua->T, 1);
7361 goto error;
7362
7363 case HLUA_E_ETMOUT:
7364 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7365 rule->arg.hlua_rule->fcn.name);
7366 goto error;
7367
7368 case HLUA_E_NOMEM:
7369 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7370 rule->arg.hlua_rule->fcn.name);
7371 goto error;
7372
7373 case HLUA_E_YIELD: /* unexpected */
7374 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7375 rule->arg.hlua_rule->fcn.name);
7376 goto error;
7377
7378 case HLUA_E_ERR:
7379 /* Display log. */
7380 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7381 rule->arg.hlua_rule->fcn.name);
7382 goto error;
7383
7384 default:
7385 goto error;
7386 }
7387 }
7388
7389 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7390 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7391 goto error;
7392
7393 /* Don't add EOD and TLR because mux-h1 will take care of it */
7394 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
7395 si_rx_room_blk(si);
7396 goto out;
7397 }
7398 res->total++;
7399 res->flags |= CF_READ_PARTIAL;
7400 }
7401
7402 done:
7403 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7404 /* eat the whole request */
7405 req_htx = htxbuf(&req->buf);
7406 htx_reset(req_htx);
7407 htx_to_buf(req_htx, &req->buf);
7408 co_set_data(req, 0);
7409 res->flags |= CF_READ_NULL;
7410 si_shutr(si);
7411 }
7412
7413 if ((res->flags & CF_SHUTR) && (si->state == SI_ST_EST))
7414 si_shutw(si);
7415
7416 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
7417 if ((req->flags & CF_SHUTW) && (si->state == SI_ST_EST)) {
7418 si_shutr(si);
7419 res->flags |= CF_READ_NULL;
7420 }
7421 }
7422
7423 out:
7424 /* we have left the request in the buffer for the case where we
7425 * process a POST, and this automatically re-enables activity on
7426 * read. It's better to indicate that we want to stop reading when
7427 * we're sending, so that we know there's at most one direction
7428 * deciding to wake the applet up. It saves it from looping when
7429 * emitting large blocks into small TCP windows.
7430 */
7431 htx_to_buf(res_htx, &res->buf);
7432 if (!channel_is_empty(res))
7433 si_stop_get(si);
7434 return;
7435
7436 error:
7437
7438 /* If we are in HTTP mode, and we are not send any
7439 * data, return a 500 server error in best effort:
7440 * if there is no room available in the buffer,
7441 * just close the connection.
7442 */
7443 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
7444 struct buffer *err = &htx_err_chunks[HTTP_ERR_500];
7445
7446 channel_erase(res);
7447 res->buf.data = b_data(err);
7448 memcpy(res->buf.area, b_head(err), b_data(err));
7449 res_htx = htx_from_buf(&res->buf);
7450
7451 res->total += res_htx->data;
7452 res->flags |= CF_READ_PARTIAL;
7453 }
7454 if (!(strm->flags & SF_ERR_MASK))
7455 strm->flags |= SF_ERR_RESOURCE;
7456 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7457 goto done;
7458}
7459
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007460static void hlua_applet_http_fct(struct appctx *ctx)
7461{
7462 struct stream_interface *si = ctx->owner;
7463 struct stream *strm = si_strm(si);
7464 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007465 struct act_rule *rule = ctx->rule;
7466 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007467 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02007468 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007469 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02007470 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02007471 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007472 int ret;
7473
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007474 if (IS_HTX_STRM(strm))
7475 return hlua_applet_htx_fct(ctx);
7476
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007477 /* If the stream is disconnect or closed, ldo nothing. */
7478 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7479 return;
7480
7481 /* Set the currently running flag. */
7482 if (!HLUA_IS_RUNNING(hlua) &&
7483 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007484 /* Store the max amount of bytes that we can read. */
7485 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
7486
7487 /* We need to flush the request header. This left the body
7488 * for the Lua.
7489 */
7490
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007491 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007492 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007493 if (ret == -1)
7494 return;
7495
7496 /* No data available, ask for more data. */
7497 if (ret == 1)
7498 len2 = 0;
7499 if (ret == 0)
7500 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02007501 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007502 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007503 return;
7504 }
7505
7506 /* skip the requests bytes. */
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02007507 co_skip(si_oc(si), strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007508 }
7509
7510 /* Executes The applet if it is not done. */
7511 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7512
7513 /* Execute the function. */
7514 switch (hlua_ctx_resume(hlua, 1)) {
7515 /* finished. */
7516 case HLUA_E_OK:
7517 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7518 break;
7519
7520 /* yield. */
7521 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007522 if (hlua->wake_time != TICK_ETERNITY)
7523 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007524 return;
7525
7526 /* finished with error. */
7527 case HLUA_E_ERRMSG:
7528 /* Display log. */
7529 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7530 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7531 lua_pop(hlua->T, 1);
7532 goto error;
7533
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007534 case HLUA_E_ETMOUT:
7535 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7536 rule->arg.hlua_rule->fcn.name);
7537 goto error;
7538
7539 case HLUA_E_NOMEM:
7540 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7541 rule->arg.hlua_rule->fcn.name);
7542 goto error;
7543
7544 case HLUA_E_YIELD: /* unexpected */
7545 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7546 rule->arg.hlua_rule->fcn.name);
7547 goto error;
7548
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007549 case HLUA_E_ERR:
7550 /* Display log. */
7551 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7552 rule->arg.hlua_rule->fcn.name);
7553 goto error;
7554
7555 default:
7556 goto error;
7557 }
7558 }
7559
7560 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Fauletcc26b132018-12-18 21:20:57 +01007561 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7562 goto error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007563
7564 /* We must send the final chunk. */
7565 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
7566 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
7567
7568 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007569 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007570
7571 /* critical error. */
7572 if (ret == -2 || ret == -3) {
7573 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
7574 rule->arg.hlua_rule->fcn.name);
7575 goto error;
7576 }
7577
7578 /* no enough space error. */
7579 if (ret == -1) {
Willy Tarreaudb398432018-11-15 11:08:52 +01007580 si_rx_room_blk(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007581 return;
7582 }
7583
7584 /* set the last chunk sent. */
7585 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
7586 }
7587
7588 /* close the connection. */
7589
Frédéric Lécaille83ed5d52018-07-18 14:25:26 +02007590 /* status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007591 strm->txn->status = ctx->ctx.hlua_apphttp.status;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007592
7593 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007594 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007595 res->flags |= CF_READ_NULL;
7596 si_shutr(si);
7597
7598 return;
7599 }
7600
7601error:
7602
7603 /* If we are in HTTP mode, and we are not send any
7604 * data, return a 500 server error in best effort:
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007605 * if there is no room available in the buffer,
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007606 * just close the connection.
7607 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02007608 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007609 if (!(strm->flags & SF_ERR_MASK))
7610 strm->flags |= SF_ERR_RESOURCE;
7611 si_shutw(si);
7612 si_shutr(si);
7613 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7614}
7615
7616static void hlua_applet_http_release(struct appctx *ctx)
7617{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02007618 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007619 task_free(ctx->ctx.hlua_apphttp.task);
7620 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007621 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007622 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007623}
7624
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007625/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
7626 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007627 *
7628 * This function can fail with an abort() due to an Lua critical error.
7629 * We are in the configuration parsing process of HAProxy, this abort() is
7630 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007631 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007632static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7633 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007634{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007635 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007636 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007637
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007638 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007639 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007640 if (!rule->arg.hlua_rule) {
7641 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007642 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007643 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007644
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007645 /* Memory for arguments. */
7646 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
7647 if (!rule->arg.hlua_rule->args) {
7648 memprintf(err, "out of memory error");
7649 return ACT_RET_PRS_ERR;
7650 }
7651
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007652 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007653 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007654
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007655 /* Expect some arguments */
7656 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007657 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007658 memprintf(err, "expect %d arguments", fcn->nargs);
7659 return ACT_RET_PRS_ERR;
7660 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007661 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007662 if (!rule->arg.hlua_rule->args[i]) {
7663 memprintf(err, "out of memory error");
7664 return ACT_RET_PRS_ERR;
7665 }
7666 (*cur_arg)++;
7667 }
7668 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007669
Thierry FOURNIER42148732015-09-02 17:17:33 +02007670 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007671 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007672 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007673}
7674
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007675static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7676 struct act_rule *rule, char **err)
7677{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007678 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007679
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007680 /* HTTP applets are forbidden in tcp-request rules.
7681 * HTTP applet request requires everything initilized by
7682 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
7683 * The applet will be immediately initilized, but its before
7684 * the call of this analyzer.
7685 */
7686 if (rule->from != ACT_F_HTTP_REQ) {
7687 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7688 return ACT_RET_PRS_ERR;
7689 }
7690
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007691 /* Memory for the rule. */
7692 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7693 if (!rule->arg.hlua_rule) {
7694 memprintf(err, "out of memory error");
7695 return ACT_RET_PRS_ERR;
7696 }
7697
7698 /* Reference the Lua function and store the reference. */
7699 rule->arg.hlua_rule->fcn = *fcn;
7700
7701 /* TODO: later accept arguments. */
7702 rule->arg.hlua_rule->args = NULL;
7703
7704 /* Add applet pointer in the rule. */
7705 rule->applet.obj_type = OBJ_TYPE_APPLET;
7706 rule->applet.name = fcn->name;
7707 rule->applet.init = hlua_applet_http_init;
7708 rule->applet.fct = hlua_applet_http_fct;
7709 rule->applet.release = hlua_applet_http_release;
7710 rule->applet.timeout = hlua_timeout_applet;
7711
7712 return ACT_RET_PRS_OK;
7713}
7714
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007715/* This function is an LUA binding used for registering
7716 * "sample-conv" functions. It expects a converter name used
7717 * in the haproxy configuration file, and an LUA function.
7718 */
7719__LJMP static int hlua_register_action(lua_State *L)
7720{
7721 struct action_kw_list *akl;
7722 const char *name;
7723 int ref;
7724 int len;
7725 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007726 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007727
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007728 /* Initialise the number of expected arguments at 0. */
7729 nargs = 0;
7730
7731 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7732 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007733
7734 /* First argument : converter name. */
7735 name = MAY_LJMP(luaL_checkstring(L, 1));
7736
7737 /* Second argument : environment. */
7738 if (lua_type(L, 2) != LUA_TTABLE)
7739 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7740
7741 /* Third argument : lua function. */
7742 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7743
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007744 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007745 if (lua_gettop(L) >= 4)
7746 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7747
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007748 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007749 lua_pushnil(L);
7750 while (lua_next(L, 2) != 0) {
7751 if (lua_type(L, -1) != LUA_TSTRING)
7752 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7753
7754 /* Check required environment. Only accepted "http" or "tcp". */
7755 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007756 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007757 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007758 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007759 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007760 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007761 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007762
7763 /* Fill fcn. */
7764 fcn->name = strdup(name);
7765 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007766 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007767 fcn->function_ref = ref;
7768
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007769 /* Set the expected number od arguments. */
7770 fcn->nargs = nargs;
7771
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007772 /* List head */
7773 akl->list.n = akl->list.p = NULL;
7774
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007775 /* action keyword. */
7776 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007777 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007778 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007779 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007780
7781 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7782
7783 akl->kw[0].match_pfx = 0;
7784 akl->kw[0].private = fcn;
7785 akl->kw[0].parse = action_register_lua;
7786
7787 /* select the action registering point. */
7788 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7789 tcp_req_cont_keywords_register(akl);
7790 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7791 tcp_res_cont_keywords_register(akl);
7792 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7793 http_req_keywords_register(akl);
7794 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7795 http_res_keywords_register(akl);
7796 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007797 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007798 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7799 "are expected.", lua_tostring(L, -1)));
7800
7801 /* pop the environment string. */
7802 lua_pop(L, 1);
7803 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007804 return ACT_RET_PRS_OK;
7805}
7806
7807static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7808 struct act_rule *rule, char **err)
7809{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007810 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007811
Christopher Fauletafd8f102018-11-08 11:34:21 +01007812 if (px->options2 & PR_O2_USE_HTX) {
7813 memprintf(err, "Lua services cannot be used when the HTX internal representation is enabled");
7814 return ACT_RET_PRS_ERR;
7815 }
7816
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007817 /* Memory for the rule. */
7818 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7819 if (!rule->arg.hlua_rule) {
7820 memprintf(err, "out of memory error");
7821 return ACT_RET_PRS_ERR;
7822 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007823
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007824 /* Reference the Lua function and store the reference. */
7825 rule->arg.hlua_rule->fcn = *fcn;
7826
7827 /* TODO: later accept arguments. */
7828 rule->arg.hlua_rule->args = NULL;
7829
7830 /* Add applet pointer in the rule. */
7831 rule->applet.obj_type = OBJ_TYPE_APPLET;
7832 rule->applet.name = fcn->name;
7833 rule->applet.init = hlua_applet_tcp_init;
7834 rule->applet.fct = hlua_applet_tcp_fct;
7835 rule->applet.release = hlua_applet_tcp_release;
7836 rule->applet.timeout = hlua_timeout_applet;
7837
7838 return 0;
7839}
7840
7841/* This function is an LUA binding used for registering
7842 * "sample-conv" functions. It expects a converter name used
7843 * in the haproxy configuration file, and an LUA function.
7844 */
7845__LJMP static int hlua_register_service(lua_State *L)
7846{
7847 struct action_kw_list *akl;
7848 const char *name;
7849 const char *env;
7850 int ref;
7851 int len;
7852 struct hlua_function *fcn;
7853
7854 MAY_LJMP(check_args(L, 3, "register_service"));
7855
7856 /* First argument : converter name. */
7857 name = MAY_LJMP(luaL_checkstring(L, 1));
7858
7859 /* Second argument : environment. */
7860 env = MAY_LJMP(luaL_checkstring(L, 2));
7861
7862 /* Third argument : lua function. */
7863 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7864
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007865 /* Allocate and fill the sample fetch keyword struct. */
7866 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7867 if (!akl)
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 fcn = calloc(1, sizeof(*fcn));
7870 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007871 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007872
7873 /* Fill fcn. */
7874 len = strlen("<lua.>") + strlen(name) + 1;
7875 fcn->name = calloc(1, len);
7876 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007877 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007878 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7879 fcn->function_ref = ref;
7880
7881 /* List head */
7882 akl->list.n = akl->list.p = NULL;
7883
7884 /* converter keyword. */
7885 len = strlen("lua.") + strlen(name) + 1;
7886 akl->kw[0].kw = calloc(1, len);
7887 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007888 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007889
7890 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7891
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007892 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007893 if (strcmp(env, "tcp") == 0)
7894 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007895 else if (strcmp(env, "http") == 0)
7896 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007897 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007898 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007899 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007900
7901 akl->kw[0].match_pfx = 0;
7902 akl->kw[0].private = fcn;
7903
7904 /* End of array. */
7905 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7906
7907 /* Register this new converter */
7908 service_keywords_register(akl);
7909
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007910 return 0;
7911}
7912
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007913/* This function initialises Lua cli handler. It copies the
7914 * arguments in the Lua stack and create channel IO objects.
7915 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007916static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007917{
7918 struct hlua *hlua;
7919 struct hlua_function *fcn;
7920 int i;
7921 const char *error;
7922
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007923 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007924 appctx->ctx.hlua_cli.fcn = private;
7925
Willy Tarreaubafbe012017-11-24 17:34:44 +01007926 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007927 if (!hlua) {
7928 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007929 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007930 }
7931 HLUA_INIT(hlua);
7932 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007933
7934 /* Create task used by signal to wakeup applets.
7935 * We use the same wakeup fonction than the Lua applet_tcp and
7936 * applet_http. It is absolutely compatible.
7937 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007938 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007939 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007940 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007941 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007942 }
7943 appctx->ctx.hlua_cli.task->nice = 0;
7944 appctx->ctx.hlua_cli.task->context = appctx;
7945 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7946
7947 /* Initialises the Lua context */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007948 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007949 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007950 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007951 }
7952
7953 /* The following Lua calls can fail. */
7954 if (!SET_SAFE_LJMP(hlua->T)) {
7955 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7956 error = lua_tostring(hlua->T, -1);
7957 else
7958 error = "critical error";
7959 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7960 goto error;
7961 }
7962
7963 /* Check stack available size. */
7964 if (!lua_checkstack(hlua->T, 2)) {
7965 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7966 goto error;
7967 }
7968
7969 /* Restore the function in the stack. */
7970 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7971
7972 /* Once the arguments parsed, the CLI is like an AppletTCP,
7973 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007974 */
7975 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7976 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7977 goto error;
7978 }
7979 hlua->nargs = 1;
7980
7981 /* push keywords in the stack. */
7982 for (i = 0; *args[i]; i++) {
7983 /* Check stack available size. */
7984 if (!lua_checkstack(hlua->T, 1)) {
7985 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7986 goto error;
7987 }
7988 lua_pushstring(hlua->T, args[i]);
7989 hlua->nargs++;
7990 }
7991
7992 /* We must initialize the execution timeouts. */
7993 hlua->max_time = hlua_timeout_session;
7994
7995 /* At this point the execution is safe. */
7996 RESET_SAFE_LJMP(hlua->T);
7997
7998 /* It's ok */
7999 return 0;
8000
8001 /* It's not ok. */
8002error:
8003 RESET_SAFE_LJMP(hlua->T);
8004 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01008005 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008006 return 1;
8007}
8008
8009static int hlua_cli_io_handler_fct(struct appctx *appctx)
8010{
8011 struct hlua *hlua;
8012 struct stream_interface *si;
8013 struct hlua_function *fcn;
8014
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008015 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008016 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01008017 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008018
8019 /* If the stream is disconnect or closed, ldo nothing. */
8020 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8021 return 1;
8022
8023 /* Execute the function. */
8024 switch (hlua_ctx_resume(hlua, 1)) {
8025
8026 /* finished. */
8027 case HLUA_E_OK:
8028 return 1;
8029
8030 /* yield. */
8031 case HLUA_E_AGAIN:
8032 /* We want write. */
8033 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01008034 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008035 /* Set the timeout. */
8036 if (hlua->wake_time != TICK_ETERNITY)
8037 task_schedule(hlua->task, hlua->wake_time);
8038 return 0;
8039
8040 /* finished with error. */
8041 case HLUA_E_ERRMSG:
8042 /* Display log. */
8043 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
8044 fcn->name, lua_tostring(hlua->T, -1));
8045 lua_pop(hlua->T, 1);
8046 return 1;
8047
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008048 case HLUA_E_ETMOUT:
8049 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
8050 fcn->name);
8051 return 1;
8052
8053 case HLUA_E_NOMEM:
8054 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
8055 fcn->name);
8056 return 1;
8057
8058 case HLUA_E_YIELD: /* unexpected */
8059 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
8060 fcn->name);
8061 return 1;
8062
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008063 case HLUA_E_ERR:
8064 /* Display log. */
8065 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
8066 fcn->name);
8067 return 1;
8068
8069 default:
8070 return 1;
8071 }
8072
8073 return 1;
8074}
8075
8076static void hlua_cli_io_release_fct(struct appctx *appctx)
8077{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008078 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008079 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008080}
8081
8082/* This function is an LUA binding used for registering
8083 * new keywords in the cli. It expects a list of keywords
8084 * which are the "path". It is limited to 5 keywords. A
8085 * description of the command, a function to be executed
8086 * for the parsing and a function for io handlers.
8087 */
8088__LJMP static int hlua_register_cli(lua_State *L)
8089{
8090 struct cli_kw_list *cli_kws;
8091 const char *message;
8092 int ref_io;
8093 int len;
8094 struct hlua_function *fcn;
8095 int index;
8096 int i;
8097
8098 MAY_LJMP(check_args(L, 3, "register_cli"));
8099
8100 /* First argument : an array of maximum 5 keywords. */
8101 if (!lua_istable(L, 1))
8102 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
8103
8104 /* Second argument : string with contextual message. */
8105 message = MAY_LJMP(luaL_checkstring(L, 2));
8106
8107 /* Third and fourth argument : lua function. */
8108 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
8109
8110 /* Allocate and fill the sample fetch keyword struct. */
8111 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
8112 if (!cli_kws)
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 fcn = calloc(1, sizeof(*fcn));
8115 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008116 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008117
8118 /* Fill path. */
8119 index = 0;
8120 lua_pushnil(L);
8121 while(lua_next(L, 1) != 0) {
8122 if (index >= 5)
8123 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8124 if (lua_type(L, -1) != LUA_TSTRING)
8125 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8126 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
8127 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008128 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008129 index++;
8130 lua_pop(L, 1);
8131 }
8132
8133 /* Copy help message. */
8134 cli_kws->kw[0].usage = strdup(message);
8135 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008136 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008137
8138 /* Fill fcn io handler. */
8139 len = strlen("<lua.cli>") + 1;
8140 for (i = 0; i < index; i++)
8141 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
8142 fcn->name = calloc(1, len);
8143 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008144 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008145 strncat((char *)fcn->name, "<lua.cli", len);
8146 for (i = 0; i < index; i++) {
8147 strncat((char *)fcn->name, ".", len);
8148 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
8149 }
8150 strncat((char *)fcn->name, ">", len);
8151 fcn->function_ref = ref_io;
8152
8153 /* Fill last entries. */
8154 cli_kws->kw[0].private = fcn;
8155 cli_kws->kw[0].parse = hlua_cli_parse_fct;
8156 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
8157 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
8158
8159 /* Register this new converter */
8160 cli_register_kw(cli_kws);
8161
8162 return 0;
8163}
8164
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008165static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
8166 struct proxy *defpx, const char *file, int line,
8167 char **err, unsigned int *timeout)
8168{
8169 const char *error;
8170
8171 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
8172 if (error && *error != '\0') {
8173 memprintf(err, "%s: invalid timeout", args[0]);
8174 return -1;
8175 }
8176 return 0;
8177}
8178
8179static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
8180 struct proxy *defpx, const char *file, int line,
8181 char **err)
8182{
8183 return hlua_read_timeout(args, section_type, curpx, defpx,
8184 file, line, err, &hlua_timeout_session);
8185}
8186
8187static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
8188 struct proxy *defpx, const char *file, int line,
8189 char **err)
8190{
8191 return hlua_read_timeout(args, section_type, curpx, defpx,
8192 file, line, err, &hlua_timeout_task);
8193}
8194
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008195static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
8196 struct proxy *defpx, const char *file, int line,
8197 char **err)
8198{
8199 return hlua_read_timeout(args, section_type, curpx, defpx,
8200 file, line, err, &hlua_timeout_applet);
8201}
8202
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008203static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
8204 struct proxy *defpx, const char *file, int line,
8205 char **err)
8206{
8207 char *error;
8208
8209 hlua_nb_instruction = strtoll(args[1], &error, 10);
8210 if (*error != '\0') {
8211 memprintf(err, "%s: invalid number", args[0]);
8212 return -1;
8213 }
8214 return 0;
8215}
8216
Willy Tarreau32f61e22015-03-18 17:54:59 +01008217static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
8218 struct proxy *defpx, const char *file, int line,
8219 char **err)
8220{
8221 char *error;
8222
8223 if (*(args[1]) == 0) {
8224 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
8225 return -1;
8226 }
8227 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
8228 if (*error != '\0') {
8229 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
8230 return -1;
8231 }
8232 return 0;
8233}
8234
8235
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008236/* This function is called by the main configuration key "lua-load". It loads and
8237 * execute an lua file during the parsing of the HAProxy configuration file. It is
8238 * the main lua entry point.
8239 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008240 * This function runs with the HAProxy keywords API. It returns -1 if an error
8241 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008242 *
8243 * In some error case, LUA set an error message in top of the stack. This function
8244 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008245 *
8246 * This function can fail with an abort() due to an Lua critical error.
8247 * We are in the configuration parsing process of HAProxy, this abort() is
8248 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008249 */
8250static int hlua_load(char **args, int section_type, struct proxy *curpx,
8251 struct proxy *defpx, const char *file, int line,
8252 char **err)
8253{
8254 int error;
8255
8256 /* Just load and compile the file. */
8257 error = luaL_loadfile(gL.T, args[1]);
8258 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008259 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008260 lua_pop(gL.T, 1);
8261 return -1;
8262 }
8263
8264 /* If no syntax error where detected, execute the code. */
8265 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
8266 switch (error) {
8267 case LUA_OK:
8268 break;
8269 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008270 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008271 lua_pop(gL.T, 1);
8272 return -1;
8273 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008274 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008275 return -1;
8276 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008277 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008278 lua_pop(gL.T, 1);
8279 return -1;
8280 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008281 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008282 lua_pop(gL.T, 1);
8283 return -1;
8284 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008285 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008286 lua_pop(gL.T, 1);
8287 return -1;
8288 }
8289
8290 return 0;
8291}
8292
8293/* configuration keywords declaration */
8294static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008295 { CFG_GLOBAL, "lua-load", hlua_load },
8296 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
8297 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02008298 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008299 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01008300 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008301 { 0, NULL, NULL },
8302}};
8303
Willy Tarreau0108d902018-11-25 19:14:37 +01008304INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
8305
Christopher Fauletafd8f102018-11-08 11:34:21 +01008306
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008307/* This function can fail with an abort() due to an Lua critical error.
8308 * We are in the initialisation process of HAProxy, this abort() is
8309 * tolerated.
8310 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008311int hlua_post_init()
8312{
8313 struct hlua_init_function *init;
8314 const char *msg;
8315 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008316 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008317
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008318 /* Call post initialisation function in safe environement. */
8319 if (!SET_SAFE_LJMP(gL.T)) {
8320 if (lua_type(gL.T, -1) == LUA_TSTRING)
8321 error = lua_tostring(gL.T, -1);
8322 else
8323 error = "critical error";
8324 fprintf(stderr, "Lua post-init: %s.\n", error);
8325 exit(1);
8326 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02008327
8328#if USE_OPENSSL
8329 /* Initialize SSL server. */
8330 if (socket_ssl.xprt->prepare_srv) {
8331 int saved_used_backed = global.ssl_used_backend;
8332 // don't affect maxconn automatic computation
8333 socket_ssl.xprt->prepare_srv(&socket_ssl);
8334 global.ssl_used_backend = saved_used_backed;
8335 }
8336#endif
8337
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008338 hlua_fcn_post_init(gL.T);
8339 RESET_SAFE_LJMP(gL.T);
8340
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008341 list_for_each_entry(init, &hlua_init_functions, l) {
8342 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
8343 ret = hlua_ctx_resume(&gL, 0);
8344 switch (ret) {
8345 case HLUA_E_OK:
8346 lua_pop(gL.T, -1);
8347 return 1;
8348 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008349 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008350 return 0;
8351 case HLUA_E_ERRMSG:
8352 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01008353 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008354 return 0;
8355 case HLUA_E_ERR:
8356 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008357 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008358 return 0;
8359 }
8360 }
8361 return 1;
8362}
8363
Willy Tarreau32f61e22015-03-18 17:54:59 +01008364/* The memory allocator used by the Lua stack. <ud> is a pointer to the
8365 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
8366 * is the previously allocated size or the kind of object in case of a new
8367 * allocation. <nsize> is the requested new size.
8368 */
8369static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
8370{
8371 struct hlua_mem_allocator *zone = ud;
8372
8373 if (nsize == 0) {
8374 /* it's a free */
8375 if (ptr)
8376 zone->allocated -= osize;
8377 free(ptr);
8378 return NULL;
8379 }
8380
8381 if (!ptr) {
8382 /* it's a new allocation */
8383 if (zone->limit && zone->allocated + nsize > zone->limit)
8384 return NULL;
8385
8386 ptr = malloc(nsize);
8387 if (ptr)
8388 zone->allocated += nsize;
8389 return ptr;
8390 }
8391
8392 /* it's a realloc */
8393 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
8394 return NULL;
8395
8396 ptr = realloc(ptr, nsize);
8397 if (ptr)
8398 zone->allocated += nsize - osize;
8399 return ptr;
8400}
8401
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008402/* Ithis function can fail with an abort() due to an Lua critical error.
8403 * We are in the initialisation process of HAProxy, this abort() is
8404 * tolerated.
8405 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008406void hlua_init(void)
8407{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008408 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008409 int idx;
8410 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008411 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008412 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008413 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008414#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008415 struct srv_kw *kw;
8416 int tmp_error;
8417 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008418 char *args[] = { /* SSL client configuration. */
8419 "ssl",
8420 "verify",
8421 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008422 NULL
8423 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008424#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008425
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008426 /* Init main lua stack. */
8427 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01008428 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01008429 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02008430 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008431 hlua_sethlua(&gL);
8432 gL.Tref = LUA_REFNIL;
8433 gL.task = NULL;
8434
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008435 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008436 * the Lua function can fail with an abort. We are in the initialisation
8437 * process of HAProxy, this abort() is tolerated.
8438 */
8439
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008440 /* Initialise lua. */
8441 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008442
Thierry Fournier75933d42016-01-21 09:30:18 +01008443 /* Set safe environment for the initialisation. */
8444 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008445 if (lua_type(gL.T, -1) == LUA_TSTRING)
8446 error_msg = lua_tostring(gL.T, -1);
8447 else
8448 error_msg = "critical error";
8449 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01008450 exit(1);
8451 }
8452
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008453 /*
8454 *
8455 * Create "core" object.
8456 *
8457 */
8458
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008459 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008460 lua_newtable(gL.T);
8461
8462 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008463 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008464 hlua_class_const_int(gL.T, log_levels[i], i);
8465
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008466 /* Register special functions. */
8467 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008468 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008469 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008470 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008471 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008472 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008473 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008474 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01008475 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008476 hlua_class_function(gL.T, "sleep", hlua_sleep);
8477 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01008478 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
8479 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
8480 hlua_class_function(gL.T, "set_map", hlua_set_map);
8481 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008482 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008483 hlua_class_function(gL.T, "log", hlua_log);
8484 hlua_class_function(gL.T, "Debug", hlua_log_debug);
8485 hlua_class_function(gL.T, "Info", hlua_log_info);
8486 hlua_class_function(gL.T, "Warning", hlua_log_warning);
8487 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02008488 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01008489 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008490
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008491 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008492
8493 /*
8494 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008495 * Register class Map
8496 *
8497 */
8498
8499 /* This table entry is the object "Map" base. */
8500 lua_newtable(gL.T);
8501
8502 /* register pattern types. */
8503 for (i=0; i<PAT_MATCH_NUM; i++)
8504 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008505 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008506 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
8507 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008508 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008509
8510 /* register constructor. */
8511 hlua_class_function(gL.T, "new", hlua_map_new);
8512
8513 /* Create and fill the metatable. */
8514 lua_newtable(gL.T);
8515
8516 /* Create and fille the __index entry. */
8517 lua_pushstring(gL.T, "__index");
8518 lua_newtable(gL.T);
8519
8520 /* Register . */
8521 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
8522 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
8523
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008524 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008525
Thierry Fournier45e78d72016-02-19 18:34:46 +01008526 /* Register previous table in the registry with reference and named entry.
8527 * The function hlua_register_metatable() pops the stack, so we
8528 * previously create a copy of the table.
8529 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008530 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008531 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008532
8533 /* Assign the metatable to the mai Map object. */
8534 lua_setmetatable(gL.T, -2);
8535
8536 /* Set a name to the table. */
8537 lua_setglobal(gL.T, "Map");
8538
8539 /*
8540 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008541 * Register class Channel
8542 *
8543 */
8544
8545 /* Create and fill the metatable. */
8546 lua_newtable(gL.T);
8547
8548 /* Create and fille the __index entry. */
8549 lua_pushstring(gL.T, "__index");
8550 lua_newtable(gL.T);
8551
8552 /* Register . */
8553 hlua_class_function(gL.T, "get", hlua_channel_get);
8554 hlua_class_function(gL.T, "dup", hlua_channel_dup);
8555 hlua_class_function(gL.T, "getline", hlua_channel_getline);
8556 hlua_class_function(gL.T, "set", hlua_channel_set);
8557 hlua_class_function(gL.T, "append", hlua_channel_append);
8558 hlua_class_function(gL.T, "send", hlua_channel_send);
8559 hlua_class_function(gL.T, "forward", hlua_channel_forward);
8560 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
8561 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01008562 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008563
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008564 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008565
8566 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008567 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008568
8569 /*
8570 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008571 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008572 *
8573 */
8574
8575 /* Create and fill the metatable. */
8576 lua_newtable(gL.T);
8577
8578 /* Create and fille the __index entry. */
8579 lua_pushstring(gL.T, "__index");
8580 lua_newtable(gL.T);
8581
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008582 /* Browse existing fetches and create the associated
8583 * object method.
8584 */
8585 sf = NULL;
8586 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
8587
8588 /* Dont register the keywork if the arguments check function are
8589 * not safe during the runtime.
8590 */
8591 if ((sf->val_args != NULL) &&
8592 (sf->val_args != val_payload_lv) &&
8593 (sf->val_args != val_hdr))
8594 continue;
8595
8596 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8597 * by an underscore.
8598 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008599 strncpy(trash.area, sf->kw, trash.size);
8600 trash.area[trash.size - 1] = '\0';
8601 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008602 if (*p == '.' || *p == '-' || *p == '+')
8603 *p = '_';
8604
8605 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008606 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01008607 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008608 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008609 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008610 }
8611
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008612 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008613
8614 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008615 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008616
8617 /*
8618 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008619 * Register class Converters
8620 *
8621 */
8622
8623 /* Create and fill the metatable. */
8624 lua_newtable(gL.T);
8625
8626 /* Create and fill the __index entry. */
8627 lua_pushstring(gL.T, "__index");
8628 lua_newtable(gL.T);
8629
8630 /* Browse existing converters and create the associated
8631 * object method.
8632 */
8633 sc = NULL;
8634 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
8635 /* Dont register the keywork if the arguments check function are
8636 * not safe during the runtime.
8637 */
8638 if (sc->val_args != NULL)
8639 continue;
8640
8641 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8642 * by an underscore.
8643 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008644 strncpy(trash.area, sc->kw, trash.size);
8645 trash.area[trash.size - 1] = '\0';
8646 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008647 if (*p == '.' || *p == '-' || *p == '+')
8648 *p = '_';
8649
8650 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008651 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008652 lua_pushlightuserdata(gL.T, sc);
8653 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008654 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008655 }
8656
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008657 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008658
8659 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008660 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008661
8662 /*
8663 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008664 * Register class HTTP
8665 *
8666 */
8667
8668 /* Create and fill the metatable. */
8669 lua_newtable(gL.T);
8670
8671 /* Create and fille the __index entry. */
8672 lua_pushstring(gL.T, "__index");
8673 lua_newtable(gL.T);
8674
8675 /* Register Lua functions. */
8676 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
8677 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
8678 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
8679 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
8680 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
8681 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
8682 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
8683 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
8684 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
8685 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
8686
8687 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
8688 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
8689 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
8690 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
8691 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
8692 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02008693 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008694
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008695 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008696
8697 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008698 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008699
8700 /*
8701 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008702 * Register class AppletTCP
8703 *
8704 */
8705
8706 /* Create and fill the metatable. */
8707 lua_newtable(gL.T);
8708
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008709 /* Create and fille the __index entry. */
8710 lua_pushstring(gL.T, "__index");
8711 lua_newtable(gL.T);
8712
8713 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01008714 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
8715 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
8716 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
8717 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
8718 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008719 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
8720 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
8721 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008722
8723 lua_settable(gL.T, -3);
8724
8725 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008726 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008727
8728 /*
8729 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008730 * Register class AppletHTTP
8731 *
8732 */
8733
8734 /* Create and fill the metatable. */
8735 lua_newtable(gL.T);
8736
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008737 /* Create and fille the __index entry. */
8738 lua_pushstring(gL.T, "__index");
8739 lua_newtable(gL.T);
8740
8741 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01008742 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
8743 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008744 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
8745 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
8746 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008747 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
8748 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
8749 hlua_class_function(gL.T, "send", hlua_applet_http_send);
8750 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
8751 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
8752 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
8753
8754 lua_settable(gL.T, -3);
8755
8756 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008757 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008758
8759 /*
8760 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008761 * Register class TXN
8762 *
8763 */
8764
8765 /* Create and fill the metatable. */
8766 lua_newtable(gL.T);
8767
8768 /* Create and fille the __index entry. */
8769 lua_pushstring(gL.T, "__index");
8770 lua_newtable(gL.T);
8771
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008772 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04008773 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
8774 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
8775 hlua_class_function(gL.T, "set_var", hlua_set_var);
8776 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
8777 hlua_class_function(gL.T, "get_var", hlua_get_var);
8778 hlua_class_function(gL.T, "done", hlua_txn_done);
8779 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
8780 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
8781 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
8782 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
8783 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
8784 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
8785 hlua_class_function(gL.T, "log", hlua_txn_log);
8786 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
8787 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
8788 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
8789 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008790
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008791 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008792
8793 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008794 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008795
8796 /*
8797 *
8798 * Register class Socket
8799 *
8800 */
8801
8802 /* Create and fill the metatable. */
8803 lua_newtable(gL.T);
8804
8805 /* Create and fille the __index entry. */
8806 lua_pushstring(gL.T, "__index");
8807 lua_newtable(gL.T);
8808
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008809#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008810 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008811#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008812 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8813 hlua_class_function(gL.T, "send", hlua_socket_send);
8814 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8815 hlua_class_function(gL.T, "close", hlua_socket_close);
8816 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8817 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8818 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8819 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8820
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008821 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008822
8823 /* Register the garbage collector entry. */
8824 lua_pushstring(gL.T, "__gc");
8825 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008826 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008827
8828 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008829 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008830
8831 /* Proxy and server configuration initialisation. */
8832 memset(&socket_proxy, 0, sizeof(socket_proxy));
8833 init_new_proxy(&socket_proxy);
8834 socket_proxy.parent = NULL;
8835 socket_proxy.last_change = now.tv_sec;
8836 socket_proxy.id = "LUA-SOCKET";
8837 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8838 socket_proxy.maxconn = 0;
8839 socket_proxy.accept = NULL;
8840 socket_proxy.options2 |= PR_O2_INDEPSTR;
8841 socket_proxy.srv = NULL;
8842 socket_proxy.conn_retries = 0;
8843 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8844
8845 /* Init TCP server: unchanged parameters */
8846 memset(&socket_tcp, 0, sizeof(socket_tcp));
8847 socket_tcp.next = NULL;
8848 socket_tcp.proxy = &socket_proxy;
8849 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8850 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008851 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008852 socket_tcp.priv_conns = NULL;
8853 socket_tcp.idle_conns = NULL;
8854 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008855 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008856 socket_tcp.last_change = 0;
8857 socket_tcp.id = "LUA-TCP-CONN";
8858 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8859 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8860 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8861
8862 /* XXX: Copy default parameter from default server,
8863 * but the default server is not initialized.
8864 */
8865 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8866 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8867 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8868 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8869 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8870 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8871 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8872 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8873 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8874 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8875
8876 socket_tcp.check.status = HCHK_STATUS_INI;
8877 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8878 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8879 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8880 socket_tcp.check.server = &socket_tcp;
8881
8882 socket_tcp.agent.status = HCHK_STATUS_INI;
8883 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8884 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8885 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8886 socket_tcp.agent.server = &socket_tcp;
8887
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008888 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008889
8890#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008891 /* Init TCP server: unchanged parameters */
8892 memset(&socket_ssl, 0, sizeof(socket_ssl));
8893 socket_ssl.next = NULL;
8894 socket_ssl.proxy = &socket_proxy;
8895 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8896 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008897 socket_ssl.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008898 socket_tcp.priv_conns = NULL;
8899 socket_tcp.idle_conns = NULL;
8900 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008901 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008902 socket_ssl.last_change = 0;
8903 socket_ssl.id = "LUA-SSL-CONN";
8904 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8905 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8906 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8907
8908 /* XXX: Copy default parameter from default server,
8909 * but the default server is not initialized.
8910 */
8911 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8912 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8913 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8914 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8915 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8916 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8917 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8918 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8919 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8920 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8921
8922 socket_ssl.check.status = HCHK_STATUS_INI;
8923 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8924 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8925 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8926 socket_ssl.check.server = &socket_ssl;
8927
8928 socket_ssl.agent.status = HCHK_STATUS_INI;
8929 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8930 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8931 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8932 socket_ssl.agent.server = &socket_ssl;
8933
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008934 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008935 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008936
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008937 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008938 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8939 /*
8940 *
8941 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008942 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008943 * features like client certificates and ssl_verify.
8944 *
8945 */
8946 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8947 if (tmp_error != 0) {
8948 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8949 abort(); /* This must be never arrives because the command line
8950 not editable by the user. */
8951 }
8952 idx += kw->skip;
8953 }
8954 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008955#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008956
8957 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008958}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008959
Willy Tarreau80713382018-11-26 10:19:54 +01008960static void hlua_register_build_options(void)
8961{
Willy Tarreaubb57d942016-12-21 19:04:56 +01008962 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01008963
Willy Tarreaubb57d942016-12-21 19:04:56 +01008964 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8965 hap_register_build_opts(ptr, 1);
8966}
Willy Tarreau80713382018-11-26 10:19:54 +01008967
8968INITCALL0(STG_REGISTER, hlua_register_build_options);