blob: 4c5598d8e2c5e5f4890b8c89d4dd053ea042c625 [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 FOURNIERa097fdf2015-03-03 15:17:35 +010045#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010046#include <proto/hlua_fcn.h>
Willy Tarreau79e57332018-10-02 16:01:16 +020047#include <proto/http_fetch.h>
Christopher Faulet724a12c2018-12-13 22:12:15 +010048#include <proto/http_htx.h>
Willy Tarreau61c112a2018-10-02 16:43:32 +020049#include <proto/http_rules.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020050#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010051#include <proto/obj_type.h>
Patrick Hemmer268a7072018-05-11 12:52:31 -040052#include <proto/queue.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010053#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010054#include <proto/payload.h>
Christopher Fauletfc9cfe42019-07-16 14:54:53 +020055#include <proto/http_ana.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010056#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010057#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020058#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020059#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010060#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010061#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010062#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020063#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010064
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010065/* Lua uses longjmp to perform yield or throwing errors. This
66 * macro is used only for identifying the function that can
67 * not return because a longjmp is executed.
68 * __LJMP marks a prototype of hlua file that can use longjmp.
69 * WILL_LJMP() marks an lua function that will use longjmp.
70 * MAY_LJMP() marks an lua function that may use longjmp.
71 */
72#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020073#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010074#define MAY_LJMP(func) func
75
Thierry FOURNIERbabae282015-09-17 11:36:37 +020076/* This couple of function executes securely some Lua calls outside of
77 * the lua runtime environment. Each Lua call can return a longjmp
78 * if it encounter a memory error.
79 *
80 * Lua documentation extract:
81 *
82 * If an error happens outside any protected environment, Lua calls
83 * a panic function (see lua_atpanic) and then calls abort, thus
84 * exiting the host application. Your panic function can avoid this
85 * exit by never returning (e.g., doing a long jump to your own
86 * recovery point outside Lua).
87 *
88 * The panic function runs as if it were a message handler (see
89 * §2.3); in particular, the error message is at the top of the
90 * stack. However, there is no guarantee about stack space. To push
91 * anything on the stack, the panic function must first check the
92 * available space (see §4.2).
93 *
94 * We must check all the Lua entry point. This includes:
95 * - The include/proto/hlua.h exported functions
96 * - the task wrapper function
97 * - The action wrapper function
98 * - The converters wrapper function
99 * - The sample-fetch wrapper functions
100 *
101 * It is tolerated that the initilisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800102 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200103 *
104 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
105 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
106 * because they must be exists in the program stack when the longjmp
107 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200108 *
109 * Note that the Lua processing is not really thread safe. It provides
110 * heavy system which consists to add our own lock function in the Lua
111 * code and recompile the library. This system will probably not accepted
112 * by maintainers of various distribs.
113 *
114 * Our main excution point of the Lua is the function lua_resume(). A
115 * quick looking on the Lua sources displays a lua_lock() a the start
116 * of function and a lua_unlock() at the end of the function. So I
117 * conclude that the Lua thread safe mode just perform a mutex around
118 * all execution. So I prefer to do this in the HAProxy code, it will be
119 * easier for distro maintainers.
120 *
121 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
122 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
123 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200124 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100125__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200126THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200127static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau9d6bb5a2020-02-06 15:55:41 +0100128static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200129
130#define SET_SAFE_LJMP(__L) \
131 ({ \
132 int ret; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100133 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200134 if (setjmp(safe_ljmp_env) != 0) { \
135 lua_atpanic(__L, hlua_panic_safe); \
136 ret = 0; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100137 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200138 } else { \
139 lua_atpanic(__L, hlua_panic_ljmp); \
140 ret = 1; \
141 } \
142 ret; \
143 })
144
145/* If we are the last function catching Lua errors, we
146 * must reset the panic function.
147 */
148#define RESET_SAFE_LJMP(__L) \
149 do { \
150 lua_atpanic(__L, hlua_panic_safe); \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100151 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200152 } while(0)
153
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200154/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200155#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100156/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200157#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200158/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100159#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100160#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200161
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100162/* The main Lua execution context. */
163struct hlua gL;
164
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100165/* This is the memory pool containing struct lua for applets
166 * (including cli).
167 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100168DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100169
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100170/* Used for Socket connection. */
171static struct proxy socket_proxy;
172static struct server socket_tcp;
173#ifdef USE_OPENSSL
174static struct server socket_ssl;
175#endif
176
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100177/* List head of the function called at the initialisation time. */
178struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
179
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100180/* The following variables contains the reference of the different
181 * Lua classes. These references are useful for identify metadata
182 * associated with an object.
183 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100184static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100185static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100186static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100187static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100188static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100189static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200190static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200191static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200192static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100193static int class_txn_reply_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 FOURNIER55da1652015-01-23 11:36:30 +0100241/* These functions converts types between HAProxy internal args or
242 * sample and LUA types. Another function permits to check if the
243 * LUA stack contains arguments according with an required ARG_T
244 * format.
245 */
246static int hlua_arg2lua(lua_State *L, const struct arg *arg);
247static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100248__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100249 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100250static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100251static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100252static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
253
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200254__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
255
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200256#define SEND_ERR(__be, __fmt, __args...) \
257 do { \
258 send_log(__be, LOG_ERR, __fmt, ## __args); \
259 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100260 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200261 } while (0)
262
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100263/* Used to check an Lua function type in the stack. It creates and
264 * returns a reference of the function. This function throws an
265 * error if the rgument is not a "function".
266 */
267__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
268{
269 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100270 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100271 WILL_LJMP(luaL_argerror(L, argno, msg));
272 }
273 lua_pushvalue(L, argno);
274 return luaL_ref(L, LUA_REGISTRYINDEX);
275}
276
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200277/* Return the string that is of the top of the stack. */
278const char *hlua_get_top_error_string(lua_State *L)
279{
280 if (lua_gettop(L) < 1)
281 return "unknown error";
282 if (lua_type(L, -1) != LUA_TSTRING)
283 return "unknown error";
284 return lua_tostring(L, -1);
285}
286
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200287__LJMP static const char *hlua_traceback(lua_State *L)
288{
289 lua_Debug ar;
290 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200291 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200292 int filled = 0;
293
294 while (lua_getstack(L, level++, &ar)) {
295
296 /* Add separator */
297 if (filled)
298 chunk_appendf(msg, ", ");
299 filled = 1;
300
301 /* Fill fields:
302 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
303 * 'l': fills in the field currentline;
304 * 'n': fills in the field name and namewhat;
305 * 't': fills in the field istailcall;
306 */
307 lua_getinfo(L, "Slnt", &ar);
308
309 /* Append code localisation */
310 if (ar.currentline > 0)
311 chunk_appendf(msg, "%s:%d ", ar.short_src, ar.currentline);
312 else
313 chunk_appendf(msg, "%s ", ar.short_src);
314
315 /*
316 * Get function name
317 *
318 * if namewhat is no empty, name is defined.
319 * what contains "Lua" for Lua function, "C" for C function,
320 * or "main" for main code.
321 */
322 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
323 chunk_appendf(msg, "%s '%s'", ar.namewhat, ar.name); /* use it */
324
325 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
326 chunk_appendf(msg, "main chunk");
327
328 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
329 chunk_appendf(msg, "C function line %d", ar.linedefined);
330
331 else /* nothing left... */
332 chunk_appendf(msg, "?");
333
334
335 /* Display tailed call */
336 if (ar.istailcall)
337 chunk_appendf(msg, " ...");
338 }
339
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200340 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200341}
342
343
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100344/* This function check the number of arguments available in the
345 * stack. If the number of arguments available is not the same
346 * then <nb> an error is throwed.
347 */
348__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
349{
350 if (lua_gettop(L) == nb)
351 return;
352 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
353}
354
Mark Lakes22154b42018-01-29 14:38:40 -0800355/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100356 * and the line number where the error is encountered.
357 */
358static int hlua_pusherror(lua_State *L, const char *fmt, ...)
359{
360 va_list argp;
361 va_start(argp, fmt);
362 luaL_where(L, 1);
363 lua_pushvfstring(L, fmt, argp);
364 va_end(argp);
365 lua_concat(L, 2);
366 return 1;
367}
368
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100369/* This functions is used with sample fetch and converters. It
370 * converts the HAProxy configuration argument in a lua stack
371 * values.
372 *
373 * It takes an array of "arg", and each entry of the array is
374 * converted and pushed in the LUA stack.
375 */
376static int hlua_arg2lua(lua_State *L, const struct arg *arg)
377{
378 switch (arg->type) {
379 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100380 case ARGT_TIME:
381 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100382 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100383 break;
384
385 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200386 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100387 break;
388
389 case ARGT_IPV4:
390 case ARGT_IPV6:
391 case ARGT_MSK4:
392 case ARGT_MSK6:
393 case ARGT_FE:
394 case ARGT_BE:
395 case ARGT_TAB:
396 case ARGT_SRV:
397 case ARGT_USR:
398 case ARGT_MAP:
399 default:
400 lua_pushnil(L);
401 break;
402 }
403 return 1;
404}
405
406/* This function take one entrie in an LUA stack at the index "ud",
407 * and try to convert it in an HAProxy argument entry. This is useful
408 * with sample fetch wrappers. The input arguments are gived to the
409 * lua wrapper and converted as arg list by thi function.
410 */
411static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
412{
413 switch (lua_type(L, ud)) {
414
415 case LUA_TNUMBER:
416 case LUA_TBOOLEAN:
417 arg->type = ARGT_SINT;
418 arg->data.sint = lua_tointeger(L, ud);
419 break;
420
421 case LUA_TSTRING:
422 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200423 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200424 /* We don't know the actual size of the underlying allocation, so be conservative. */
425 arg->data.str.size = arg->data.str.data;
426 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100427 break;
428
429 case LUA_TUSERDATA:
430 case LUA_TNIL:
431 case LUA_TTABLE:
432 case LUA_TFUNCTION:
433 case LUA_TTHREAD:
434 case LUA_TLIGHTUSERDATA:
435 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200436 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100437 break;
438 }
439 return 1;
440}
441
442/* the following functions are used to convert a struct sample
443 * in Lua type. This useful to convert the return of the
444 * fetchs or converters.
445 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100446static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100447{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200448 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100449 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100450 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200451 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100452 break;
453
454 case SMP_T_BIN:
455 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200456 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100457 break;
458
459 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200460 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100461 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
462 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
463 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
464 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
465 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
466 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
467 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
468 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
469 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200470 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100471 break;
472 default:
473 lua_pushnil(L);
474 break;
475 }
476 break;
477
478 case SMP_T_IPV4:
479 case SMP_T_IPV6:
480 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200481 if (sample_casts[smp->data.type][SMP_T_STR] &&
482 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200483 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100484 else
485 lua_pushnil(L);
486 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100487 default:
488 lua_pushnil(L);
489 break;
490 }
491 return 1;
492}
493
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100494/* the following functions are used to convert a struct sample
495 * in Lua strings. This is useful to convert the return of the
496 * fetchs or converters.
497 */
498static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
499{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200500 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100501
502 case SMP_T_BIN:
503 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200504 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100505 break;
506
507 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200508 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100509 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
510 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
511 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
512 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
513 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
514 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
515 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
516 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
517 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200518 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100519 break;
520 default:
521 lua_pushstring(L, "");
522 break;
523 }
524 break;
525
526 case SMP_T_SINT:
527 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100528 case SMP_T_IPV4:
529 case SMP_T_IPV6:
530 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200531 if (sample_casts[smp->data.type][SMP_T_STR] &&
532 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200533 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100534 else
535 lua_pushstring(L, "");
536 break;
537 default:
538 lua_pushstring(L, "");
539 break;
540 }
541 return 1;
542}
543
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100544/* the following functions are used to convert an Lua type in a
545 * struct sample. This is useful to provide data from a converter
546 * to the LUA code.
547 */
548static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
549{
550 switch (lua_type(L, ud)) {
551
552 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200553 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200554 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100555 break;
556
557
558 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200559 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200560 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100561 break;
562
563 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200564 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100565 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200566 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200567 /* We don't know the actual size of the underlying allocation, so be conservative. */
568 smp->data.u.str.size = smp->data.u.str.data;
569 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100570 break;
571
572 case LUA_TUSERDATA:
573 case LUA_TNIL:
574 case LUA_TTABLE:
575 case LUA_TFUNCTION:
576 case LUA_TTHREAD:
577 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200578 case LUA_TNONE:
579 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200580 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200581 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100582 break;
583 }
584 return 1;
585}
586
587/* This function check the "argp" builded by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800588 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100589 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100590 *
591 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
592 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100593 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100594__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100595 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100596{
597 int min_arg;
598 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100599 struct proxy *px;
600 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100601
602 idx = 0;
603 min_arg = ARGM(mask);
604 mask >>= ARGM_BITS;
605
606 while (1) {
607
608 /* Check oversize. */
609 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100610 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100611 }
612
613 /* Check for mandatory arguments. */
614 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100615 if (idx < min_arg) {
616
617 /* If miss other argument than the first one, we return an error. */
618 if (idx > 0)
619 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
620
621 /* If first argument have a certain type, some default values
622 * may be used. See the function smp_resolve_args().
623 */
624 switch (mask & ARGT_MASK) {
625
626 case ARGT_FE:
627 if (!(p->cap & PR_CAP_FE))
628 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
629 argp[idx].data.prx = p;
630 argp[idx].type = ARGT_FE;
631 argp[idx+1].type = ARGT_STOP;
632 break;
633
634 case ARGT_BE:
635 if (!(p->cap & PR_CAP_BE))
636 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
637 argp[idx].data.prx = p;
638 argp[idx].type = ARGT_BE;
639 argp[idx+1].type = ARGT_STOP;
640 break;
641
642 case ARGT_TAB:
643 argp[idx].data.prx = p;
644 argp[idx].type = ARGT_TAB;
645 argp[idx+1].type = ARGT_STOP;
646 break;
647
648 default:
649 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
650 break;
651 }
652 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100653 return 0;
654 }
655
656 /* Check for exceed the number of requiered argument. */
657 if ((mask & ARGT_MASK) == ARGT_STOP &&
658 argp[idx].type != ARGT_STOP) {
659 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
660 }
661
662 if ((mask & ARGT_MASK) == ARGT_STOP &&
663 argp[idx].type == ARGT_STOP) {
664 return 0;
665 }
666
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100667 /* Convert some argument types. */
668 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100669 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100670 if (argp[idx].type != ARGT_SINT)
671 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
672 argp[idx].type = ARGT_SINT;
673 break;
674
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100675 case ARGT_TIME:
676 if (argp[idx].type != ARGT_SINT)
677 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200678 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100679 break;
680
681 case ARGT_SIZE:
682 if (argp[idx].type != ARGT_SINT)
683 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200684 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100685 break;
686
687 case ARGT_FE:
688 if (argp[idx].type != ARGT_STR)
689 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200690 memcpy(trash.area, argp[idx].data.str.area,
691 argp[idx].data.str.data);
692 trash.area[argp[idx].data.str.data] = 0;
693 argp[idx].data.prx = proxy_fe_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100694 if (!argp[idx].data.prx)
695 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
696 argp[idx].type = ARGT_FE;
697 break;
698
699 case ARGT_BE:
700 if (argp[idx].type != ARGT_STR)
701 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200702 memcpy(trash.area, argp[idx].data.str.area,
703 argp[idx].data.str.data);
704 trash.area[argp[idx].data.str.data] = 0;
705 argp[idx].data.prx = proxy_be_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100706 if (!argp[idx].data.prx)
707 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
708 argp[idx].type = ARGT_BE;
709 break;
710
711 case ARGT_TAB:
712 if (argp[idx].type != ARGT_STR)
713 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200714 memcpy(trash.area, argp[idx].data.str.area,
715 argp[idx].data.str.data);
716 trash.area[argp[idx].data.str.data] = 0;
Tim Duesterhus9fe7c632019-09-29 23:03:09 +0200717 argp[idx].data.t = stktable_find_by_name(trash.area);
718 if (!argp[idx].data.t)
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100719 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
720 argp[idx].type = ARGT_TAB;
721 break;
722
723 case ARGT_SRV:
724 if (argp[idx].type != ARGT_STR)
725 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200726 memcpy(trash.area, argp[idx].data.str.area,
727 argp[idx].data.str.data);
728 trash.area[argp[idx].data.str.data] = 0;
729 sname = strrchr(trash.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100730 if (sname) {
731 *sname++ = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200732 pname = trash.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200733 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100734 if (!px)
735 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
736 }
737 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200738 sname = trash.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100739 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100740 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100741 argp[idx].data.srv = findserver(px, sname);
742 if (!argp[idx].data.srv)
743 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
744 argp[idx].type = ARGT_SRV;
745 break;
746
747 case ARGT_IPV4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200748 memcpy(trash.area, argp[idx].data.str.area,
749 argp[idx].data.str.data);
750 trash.area[argp[idx].data.str.data] = 0;
751 if (inet_pton(AF_INET, trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100752 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
753 argp[idx].type = ARGT_IPV4;
754 break;
755
756 case ARGT_MSK4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200757 memcpy(trash.area, argp[idx].data.str.area,
758 argp[idx].data.str.data);
759 trash.area[argp[idx].data.str.data] = 0;
760 if (!str2mask(trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100761 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
762 argp[idx].type = ARGT_MSK4;
763 break;
764
765 case ARGT_IPV6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200766 memcpy(trash.area, argp[idx].data.str.area,
767 argp[idx].data.str.data);
768 trash.area[argp[idx].data.str.data] = 0;
769 if (inet_pton(AF_INET6, trash.area, &argp[idx].data.ipv6))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100770 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
771 argp[idx].type = ARGT_IPV6;
772 break;
773
774 case ARGT_MSK6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200775 memcpy(trash.area, argp[idx].data.str.area,
776 argp[idx].data.str.data);
777 trash.area[argp[idx].data.str.data] = 0;
778 if (!str2mask6(trash.area, &argp[idx].data.ipv6))
Tim Duesterhusb814da62018-01-25 16:24:50 +0100779 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 mask"));
780 argp[idx].type = ARGT_MSK6;
781 break;
782
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100783 case ARGT_MAP:
784 case ARGT_REG:
785 case ARGT_USR:
786 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100787 break;
788 }
789
790 /* Check for type of argument. */
791 if ((mask & ARGT_MASK) != argp[idx].type) {
792 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
793 arg_type_names[(mask & ARGT_MASK)],
794 arg_type_names[argp[idx].type & ARGT_MASK]);
795 WILL_LJMP(luaL_argerror(L, first + idx, msg));
796 }
797
798 /* Next argument. */
799 mask >>= ARGT_BITS;
800 idx++;
801 }
802}
803
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100804/*
805 * The following functions are used to make correspondance between the the
806 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100807 *
808 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100809 * - hlua_sethlua : create the association between hlua context and lua_state.
810 */
811static inline struct hlua *hlua_gethlua(lua_State *L)
812{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100813 struct hlua **hlua = lua_getextraspace(L);
814 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100815}
816static inline void hlua_sethlua(struct hlua *hlua)
817{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100818 struct hlua **hlua_store = lua_getextraspace(hlua->T);
819 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100820}
821
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100822/* This function is used to send logs. It try to send on screen (stderr)
823 * and on the default syslog server.
824 */
825static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
826{
827 struct tm tm;
828 char *p;
829
830 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200831 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100832 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200833 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200834 /* Break the message if exceed the buffer size. */
835 *(p-4) = ' ';
836 *(p-3) = '.';
837 *(p-2) = '.';
838 *(p-1) = '.';
839 break;
840 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100841 if (isprint(*msg))
842 *p = *msg;
843 else
844 *p = '.';
845 }
846 *p = '\0';
847
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200848 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100849 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200850 get_localtime(date.tv_sec, &tm);
851 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100852 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200853 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100854 fflush(stderr);
855 }
856}
857
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100858/* This function just ensure that the yield will be always
859 * returned with a timeout and permit to set some flags
860 */
861__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100862 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100863{
864 struct hlua *hlua = hlua_gethlua(L);
865
866 /* Set the wake timeout. If timeout is required, we set
867 * the expiration time.
868 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200869 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100870
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100871 hlua->flags |= flags;
872
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100873 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +0200874 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100875}
876
Willy Tarreau87b09662015-04-03 00:22:06 +0200877/* This function initialises the Lua environment stored in the stream.
878 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100879 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200880 *
881 * This function is particular. it initialises a new Lua thread. If the
882 * initialisation fails (example: out of memory error), the lua function
883 * throws an error (longjmp).
884 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100885 * In some case (at least one), this function can be called from safe
886 * environement, so we must not initialise it. While the support of
887 * threads appear, the safe environment set a lock to ensure only one
888 * Lua execution at a time. If we initialize safe environment in another
889 * safe environmenet, we have a dead lock.
890 *
891 * set "already_safe" true if the context is initialized form safe
892 * Lua fonction.
893 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800894 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200895 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800896 * MUST NOT manipulate the created thread stack state, because it is not
897 * proctected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100898 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100899int hlua_ctx_init(struct hlua *lua, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100900{
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100901 if (!already_safe) {
902 if (!SET_SAFE_LJMP(gL.T)) {
903 lua->Tref = LUA_REFNIL;
904 return 0;
905 }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200906 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100907 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100908 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +0100909 lua->gc_count = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100910 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100911 lua->T = lua_newthread(gL.T);
912 if (!lua->T) {
913 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100914 if (!already_safe)
915 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100916 return 0;
917 }
918 hlua_sethlua(lua);
919 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
920 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +0100921 if (!already_safe)
922 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100923 return 1;
924}
925
Willy Tarreau87b09662015-04-03 00:22:06 +0200926/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100927 * is destroyed. The destroy also the memory context. The struct "lua"
928 * is not freed.
929 */
930void hlua_ctx_destroy(struct hlua *lua)
931{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100932 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100933 return;
934
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100935 if (!lua->T)
936 goto end;
937
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100938 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200939 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100940
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200941 if (!SET_SAFE_LJMP(lua->T))
942 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100943 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200944 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200945
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200946 if (!SET_SAFE_LJMP(gL.T))
947 return;
948 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
949 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200950 /* Forces a garbage collecting process. If the Lua program is finished
951 * without error, we run the GC on the thread pointer. Its freed all
952 * the unused memory.
953 * If the thread is finnish with an error or is currently yielded,
954 * it seems that the GC applied on the thread doesn't clean anything,
955 * so e run the GC on the main thread.
956 * NOTE: maybe this action locks all the Lua threads untiml the en of
957 * the garbage collection.
958 */
Willy Tarreauf31af932020-01-14 09:59:38 +0100959 if (lua->gc_count) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200960 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200961 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200962 lua_gc(gL.T, LUA_GCCOLLECT, 0);
963 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200964 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200965
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200966 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100967
968end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100969 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100970}
971
972/* This function is used to restore the Lua context when a coroutine
973 * fails. This function copy the common memory between old coroutine
974 * and the new coroutine. The old coroutine is destroyed, and its
975 * replaced by the new coroutine.
976 * If the flag "keep_msg" is set, the last entry of the old is assumed
977 * as string error message and it is copied in the new stack.
978 */
979static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
980{
981 lua_State *T;
982 int new_ref;
983
984 /* Renew the main LUA stack doesn't have sense. */
985 if (lua == &gL)
986 return 0;
987
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100988 /* New Lua coroutine. */
989 T = lua_newthread(gL.T);
990 if (!T)
991 return 0;
992
993 /* Copy last error message. */
994 if (keep_msg)
995 lua_xmove(lua->T, T, 1);
996
997 /* Copy data between the coroutines. */
998 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
999 lua_xmove(lua->T, T, 1);
1000 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
1001
1002 /* Destroy old data. */
1003 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1004
1005 /* The thread is garbage collected by Lua. */
1006 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
1007
1008 /* Fill the struct with the new coroutine values. */
1009 lua->Mref = new_ref;
1010 lua->T = T;
1011 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
1012
1013 /* Set context. */
1014 hlua_sethlua(lua);
1015
1016 return 1;
1017}
1018
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001019void hlua_hook(lua_State *L, lua_Debug *ar)
1020{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001021 struct hlua *hlua = hlua_gethlua(L);
1022
1023 /* Lua cannot yield when its returning from a function,
1024 * so, we can fix the interrupt hook to 1 instruction,
1025 * expecting that the function is finnished.
1026 */
1027 if (lua_gethookmask(L) & LUA_MASKRET) {
1028 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1029 return;
1030 }
1031
1032 /* restore the interrupt condition. */
1033 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1034
1035 /* If we interrupt the Lua processing in yieldable state, we yield.
1036 * If the state is not yieldable, trying yield causes an error.
1037 */
1038 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001039 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001040
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001041 /* If we cannot yield, update the clock and check the timeout. */
1042 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001043 hlua->run_time += now_ms - hlua->start_time;
1044 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001045 lua_pushfstring(L, "execution timeout");
1046 WILL_LJMP(lua_error(L));
1047 }
1048
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001049 /* Update the start time. */
1050 hlua->start_time = now_ms;
1051
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001052 /* Try to interrupt the process at the end of the current
1053 * unyieldable function.
1054 */
1055 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001056}
1057
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001058/* This function start or resumes the Lua stack execution. If the flag
1059 * "yield_allowed" if no set and the LUA stack execution returns a yield
1060 * The function return an error.
1061 *
1062 * The function can returns 4 values:
1063 * - HLUA_E_OK : The execution is terminated without any errors.
1064 * - HLUA_E_AGAIN : The execution must continue at the next associated
1065 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001066 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001067 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001068 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001069 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001070 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001071 * LUA code.
1072 */
1073static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1074{
1075 int ret;
1076 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001077 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001078
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001079 /* Initialise run time counter. */
1080 if (!HLUA_IS_RUNNING(lua))
1081 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001082
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001083 /* Lock the whole Lua execution. This lock must be before the
1084 * label "resume_execution".
1085 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001086 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001087
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001088resume_execution:
1089
1090 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1091 * instructions. it is used for preventing infinite loops.
1092 */
1093 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1094
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001095 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001096 HLUA_SET_RUN(lua);
1097 HLUA_CLR_CTRLYIELD(lua);
1098 HLUA_CLR_WAKERESWR(lua);
1099 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001100
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001101 /* Update the start time. */
1102 lua->start_time = now_ms;
1103
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001104 /* Call the function. */
1105 ret = lua_resume(lua->T, gL.T, lua->nargs);
1106 switch (ret) {
1107
1108 case LUA_OK:
1109 ret = HLUA_E_OK;
1110 break;
1111
1112 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001113 /* Check if the execution timeout is expired. It it is the case, we
1114 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001115 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001116 tv_update_date(0, 1);
1117 lua->run_time += now_ms - lua->start_time;
1118 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001119 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001120 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001121 break;
1122 }
1123 /* Process the forced yield. if the general yield is not allowed or
1124 * if no task were associated this the current Lua execution
1125 * coroutine, we resume the execution. Else we want to return in the
1126 * scheduler and we want to be waked up again, to continue the
1127 * current Lua execution. So we schedule our own task.
1128 */
1129 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001130 if (!yield_allowed || !lua->task)
1131 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001132 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001133 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001134 if (!yield_allowed) {
1135 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001136 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001137 break;
1138 }
1139 ret = HLUA_E_AGAIN;
1140 break;
1141
1142 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001143
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001144 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001145 * because the errors ares the only one mean to return immediately
1146 * from and lua execution.
1147 */
1148 if (lua->flags & HLUA_EXIT) {
1149 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001150 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001151 break;
1152 }
1153
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001154 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001155 if (!lua_checkstack(lua->T, 1)) {
1156 ret = HLUA_E_ERR;
1157 break;
1158 }
1159 msg = lua_tostring(lua->T, -1);
1160 lua_settop(lua->T, 0); /* Empty the stack. */
1161 lua_pop(lua->T, 1);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001162 trace = hlua_traceback(lua->T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001163 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001164 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001165 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001166 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001167 ret = HLUA_E_ERRMSG;
1168 break;
1169
1170 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001171 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001172 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001173 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001174 break;
1175
1176 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001177 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001178 if (!lua_checkstack(lua->T, 1)) {
1179 ret = HLUA_E_ERR;
1180 break;
1181 }
1182 msg = lua_tostring(lua->T, -1);
1183 lua_settop(lua->T, 0); /* Empty the stack. */
1184 lua_pop(lua->T, 1);
1185 if (msg)
1186 lua_pushfstring(lua->T, "message handler error: %s", msg);
1187 else
1188 lua_pushfstring(lua->T, "message handler error");
1189 ret = HLUA_E_ERRMSG;
1190 break;
1191
1192 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001193 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001194 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001195 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001196 break;
1197 }
1198
1199 switch (ret) {
1200 case HLUA_E_AGAIN:
1201 break;
1202
1203 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001204 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001205 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001206 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001207 break;
1208
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001209 case HLUA_E_ETMOUT:
1210 case HLUA_E_NOMEM:
1211 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001212 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001213 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001214 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001215 hlua_ctx_renew(lua, 0);
1216 break;
1217
1218 case HLUA_E_OK:
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 break;
1222 }
1223
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001224 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001225 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001226
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001227 return ret;
1228}
1229
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001230/* This function exit the current code. */
1231__LJMP static int hlua_done(lua_State *L)
1232{
1233 struct hlua *hlua = hlua_gethlua(L);
1234
1235 hlua->flags |= HLUA_EXIT;
1236 WILL_LJMP(lua_error(L));
1237
1238 return 0;
1239}
1240
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001241/* This function is an LUA binding. It provides a function
1242 * for deleting ACL from a referenced ACL file.
1243 */
1244__LJMP static int hlua_del_acl(lua_State *L)
1245{
1246 const char *name;
1247 const char *key;
1248 struct pat_ref *ref;
1249
1250 MAY_LJMP(check_args(L, 2, "del_acl"));
1251
1252 name = MAY_LJMP(luaL_checkstring(L, 1));
1253 key = MAY_LJMP(luaL_checkstring(L, 2));
1254
1255 ref = pat_ref_lookup(name);
1256 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001257 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001258
1259 pat_ref_delete(ref, key);
1260 return 0;
1261}
1262
1263/* This function is an LUA binding. It provides a function
1264 * for deleting map entry from a referenced map file.
1265 */
1266static int hlua_del_map(lua_State *L)
1267{
1268 const char *name;
1269 const char *key;
1270 struct pat_ref *ref;
1271
1272 MAY_LJMP(check_args(L, 2, "del_map"));
1273
1274 name = MAY_LJMP(luaL_checkstring(L, 1));
1275 key = MAY_LJMP(luaL_checkstring(L, 2));
1276
1277 ref = pat_ref_lookup(name);
1278 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001279 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001280
1281 pat_ref_delete(ref, key);
1282 return 0;
1283}
1284
1285/* This function is an LUA binding. It provides a function
1286 * for adding ACL pattern from a referenced ACL file.
1287 */
1288static int hlua_add_acl(lua_State *L)
1289{
1290 const char *name;
1291 const char *key;
1292 struct pat_ref *ref;
1293
1294 MAY_LJMP(check_args(L, 2, "add_acl"));
1295
1296 name = MAY_LJMP(luaL_checkstring(L, 1));
1297 key = MAY_LJMP(luaL_checkstring(L, 2));
1298
1299 ref = pat_ref_lookup(name);
1300 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001301 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001302
1303 if (pat_ref_find_elt(ref, key) == NULL)
1304 pat_ref_add(ref, key, NULL, NULL);
1305 return 0;
1306}
1307
1308/* This function is an LUA binding. It provides a function
1309 * for setting map pattern and sample from a referenced map
1310 * file.
1311 */
1312static int hlua_set_map(lua_State *L)
1313{
1314 const char *name;
1315 const char *key;
1316 const char *value;
1317 struct pat_ref *ref;
1318
1319 MAY_LJMP(check_args(L, 3, "set_map"));
1320
1321 name = MAY_LJMP(luaL_checkstring(L, 1));
1322 key = MAY_LJMP(luaL_checkstring(L, 2));
1323 value = MAY_LJMP(luaL_checkstring(L, 3));
1324
1325 ref = pat_ref_lookup(name);
1326 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001327 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001328
1329 if (pat_ref_find_elt(ref, key) != NULL)
1330 pat_ref_set(ref, key, value, NULL);
1331 else
1332 pat_ref_add(ref, key, value, NULL);
1333 return 0;
1334}
1335
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001336/* A class is a lot of memory that contain data. This data can be a table,
1337 * an integer or user data. This data is associated with a metatable. This
1338 * metatable have an original version registred in the global context with
1339 * the name of the object (_G[<name>] = <metable> ).
1340 *
1341 * A metable is a table that modify the standard behavior of a standard
1342 * access to the associated data. The entries of this new metatable are
1343 * defined as is:
1344 *
1345 * http://lua-users.org/wiki/MetatableEvents
1346 *
1347 * __index
1348 *
1349 * we access an absent field in a table, the result is nil. This is
1350 * true, but it is not the whole truth. Actually, such access triggers
1351 * the interpreter to look for an __index metamethod: If there is no
1352 * such method, as usually happens, then the access results in nil;
1353 * otherwise, the metamethod will provide the result.
1354 *
1355 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1356 * the key does not appear in the table, but the metatable has an __index
1357 * property:
1358 *
1359 * - if the value is a function, the function is called, passing in the
1360 * table and the key; the return value of that function is returned as
1361 * the result.
1362 *
1363 * - if the value is another table, the value of the key in that table is
1364 * asked for and returned (and if it doesn't exist in that table, but that
1365 * table's metatable has an __index property, then it continues on up)
1366 *
1367 * - Use "rawget(myTable,key)" to skip this metamethod.
1368 *
1369 * http://www.lua.org/pil/13.4.1.html
1370 *
1371 * __newindex
1372 *
1373 * Like __index, but control property assignment.
1374 *
1375 * __mode - Control weak references. A string value with one or both
1376 * of the characters 'k' and 'v' which specifies that the the
1377 * keys and/or values in the table are weak references.
1378 *
1379 * __call - Treat a table like a function. When a table is followed by
1380 * parenthesis such as "myTable( 'foo' )" and the metatable has
1381 * a __call key pointing to a function, that function is invoked
1382 * (passing any specified arguments) and the return value is
1383 * returned.
1384 *
1385 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1386 * called, if the metatable for myTable has a __metatable
1387 * key, the value of that key is returned instead of the
1388 * actual metatable.
1389 *
1390 * __tostring - Control string representation. When the builtin
1391 * "tostring( myTable )" function is called, if the metatable
1392 * for myTable has a __tostring property set to a function,
1393 * that function is invoked (passing myTable to it) and the
1394 * return value is used as the string representation.
1395 *
1396 * __len - Control table length. When the table length is requested using
1397 * the length operator ( '#' ), if the metatable for myTable has
1398 * a __len key pointing to a function, that function is invoked
1399 * (passing myTable to it) and the return value used as the value
1400 * of "#myTable".
1401 *
1402 * __gc - Userdata finalizer code. When userdata is set to be garbage
1403 * collected, if the metatable has a __gc field pointing to a
1404 * function, that function is first invoked, passing the userdata
1405 * to it. The __gc metamethod is not called for tables.
1406 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1407 *
1408 * Special metamethods for redefining standard operators:
1409 * http://www.lua.org/pil/13.1.html
1410 *
1411 * __add "+"
1412 * __sub "-"
1413 * __mul "*"
1414 * __div "/"
1415 * __unm "!"
1416 * __pow "^"
1417 * __concat ".."
1418 *
1419 * Special methods for redfining standar relations
1420 * http://www.lua.org/pil/13.2.html
1421 *
1422 * __eq "=="
1423 * __lt "<"
1424 * __le "<="
1425 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001426
1427/*
1428 *
1429 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001430 * Class Map
1431 *
1432 *
1433 */
1434
1435/* Returns a struct hlua_map if the stack entry "ud" is
1436 * a class session, otherwise it throws an error.
1437 */
1438__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1439{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001440 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001441}
1442
1443/* This function is the map constructor. It don't need
1444 * the class Map object. It creates and return a new Map
1445 * object. It must be called only during "body" or "init"
1446 * context because it process some filesystem accesses.
1447 */
1448__LJMP static int hlua_map_new(struct lua_State *L)
1449{
1450 const char *fn;
1451 int match = PAT_MATCH_STR;
1452 struct sample_conv conv;
1453 const char *file = "";
1454 int line = 0;
1455 lua_Debug ar;
1456 char *err = NULL;
1457 struct arg args[2];
1458
1459 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1460 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1461
1462 fn = MAY_LJMP(luaL_checkstring(L, 1));
1463
1464 if (lua_gettop(L) >= 2) {
1465 match = MAY_LJMP(luaL_checkinteger(L, 2));
1466 if (match < 0 || match >= PAT_MATCH_NUM)
1467 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1468 }
1469
1470 /* Get Lua filename and line number. */
1471 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1472 lua_getinfo(L, "Sl", &ar); /* get info about it */
1473 if (ar.currentline > 0) { /* is there info? */
1474 file = ar.short_src;
1475 line = ar.currentline;
1476 }
1477 }
1478
1479 /* fill fake sample_conv struct. */
1480 conv.kw = ""; /* unused. */
1481 conv.process = NULL; /* unused. */
1482 conv.arg_mask = 0; /* unused. */
1483 conv.val_args = NULL; /* unused. */
1484 conv.out_type = SMP_T_STR;
1485 conv.private = (void *)(long)match;
1486 switch (match) {
1487 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1488 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1489 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1490 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1491 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1492 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1493 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001494 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001495 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1496 default:
1497 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1498 }
1499
1500 /* fill fake args. */
1501 args[0].type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001502 args[0].data.str.area = (char *)fn;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001503 args[1].type = ARGT_STOP;
1504
1505 /* load the map. */
1506 if (!sample_load_map(args, &conv, file, line, &err)) {
1507 /* error case: we cant use luaL_error because we must
1508 * free the err variable.
1509 */
1510 luaL_where(L, 1);
1511 lua_pushfstring(L, "'new': %s.", err);
1512 lua_concat(L, 2);
1513 free(err);
1514 WILL_LJMP(lua_error(L));
1515 }
1516
1517 /* create the lua object. */
1518 lua_newtable(L);
1519 lua_pushlightuserdata(L, args[0].data.map);
1520 lua_rawseti(L, -2, 0);
1521
1522 /* Pop a class Map metatable and affect it to the userdata. */
1523 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1524 lua_setmetatable(L, -2);
1525
1526
1527 return 1;
1528}
1529
1530__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1531{
1532 struct map_descriptor *desc;
1533 struct pattern *pat;
1534 struct sample smp;
1535
1536 MAY_LJMP(check_args(L, 2, "lookup"));
1537 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001538 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001539 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001540 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001541 }
1542 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001543 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001544 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001545 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 +02001546 }
1547
1548 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001549 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001550 if (str)
1551 lua_pushstring(L, "");
1552 else
1553 lua_pushnil(L);
1554 return 1;
1555 }
1556
1557 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001558 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001559 return 1;
1560}
1561
1562__LJMP static int hlua_map_lookup(struct lua_State *L)
1563{
1564 return _hlua_map_lookup(L, 0);
1565}
1566
1567__LJMP static int hlua_map_slookup(struct lua_State *L)
1568{
1569 return _hlua_map_lookup(L, 1);
1570}
1571
1572/*
1573 *
1574 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001575 * Class Socket
1576 *
1577 *
1578 */
1579
1580__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1581{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001582 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001583}
1584
1585/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001586 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001587 * received.
1588 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001589static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001590{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001591 struct stream_interface *si = appctx->owner;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001592
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001593 if (appctx->ctx.hlua_cosocket.die) {
1594 si_shutw(si);
1595 si_shutr(si);
1596 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001597 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1598 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001599 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1600 }
1601
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001602 /* If we cant write, wakeup the pending write signals. */
1603 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001604 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001605
1606 /* If we cant read, wakeup the pending read signals. */
1607 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001608 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001609
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001610 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001611 * to be notified whenever the connection completes.
1612 */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001613 if (si_opposite(si)->state < SI_ST_EST) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001614 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001615 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001616 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001617 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001618 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001619
1620 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001621 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001622
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001623 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001624 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001625 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001626
1627 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001628 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001629 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001630
1631 /* Some data were injected in the buffer, notify the stream
1632 * interface.
1633 */
1634 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001635 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001636
1637 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001638 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001639 */
1640 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001641 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001642}
1643
Willy Tarreau87b09662015-04-03 00:22:06 +02001644/* This function is called when the "struct stream" is destroyed.
1645 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001646 * Wake all the pending signals.
1647 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001648static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001649{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001650 struct xref *peer;
1651
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001652 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001653 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1654 if (peer)
1655 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001656
1657 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001658 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1659 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001660}
1661
1662/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001663 * uses this object. If the stream does not exists, just quit.
1664 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001665 * pending signal can rest in the read and write lists. destroy
1666 * it.
1667 */
1668__LJMP static int hlua_socket_gc(lua_State *L)
1669{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001670 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001671 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001672 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001673
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001674 MAY_LJMP(check_args(L, 1, "__gc"));
1675
1676 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001677 peer = xref_get_peer_and_lock(&socket->xref);
1678 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001679 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001680 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001681
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001682 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001683 appctx->ctx.hlua_cosocket.die = 1;
1684 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001685
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001686 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001687 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001688 return 0;
1689}
1690
1691/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001692 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001693 */
sada05ed3302018-05-11 11:48:18 -07001694__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001695{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001696 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001697 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001698 struct xref *peer;
Willy Tarreauf31af932020-01-14 09:59:38 +01001699 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001700
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001701 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001702
1703 /* Check if we run on the same thread than the xreator thread.
1704 * We cannot access to the socket if the thread is different.
1705 */
1706 if (socket->tid != tid)
1707 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1708
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001709 peer = xref_get_peer_and_lock(&socket->xref);
1710 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001711 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001712
1713 hlua->gc_count--;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001714 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001715
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001716 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001717 appctx->ctx.hlua_cosocket.die = 1;
1718 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001719
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001720 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001721 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001722 return 0;
1723}
1724
sada05ed3302018-05-11 11:48:18 -07001725/* The close function calls close_helper.
1726 */
1727__LJMP static int hlua_socket_close(lua_State *L)
1728{
1729 MAY_LJMP(check_args(L, 1, "close"));
1730 return hlua_socket_close_helper(L);
1731}
1732
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001733/* This Lua function assumes that the stack contain three parameters.
1734 * 1 - USERDATA containing a struct socket
1735 * 2 - INTEGER with values of the macro defined below
1736 * If the integer is -1, we must read at most one line.
1737 * If the integer is -2, we ust read all the data until the
1738 * end of the stream.
1739 * If the integer is positive value, we must read a number of
1740 * bytes corresponding to this value.
1741 */
1742#define HLSR_READ_LINE (-1)
1743#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001744__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001745{
1746 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1747 int wanted = lua_tointeger(L, 2);
1748 struct hlua *hlua = hlua_gethlua(L);
1749 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001750 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001751 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001752 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001753 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001754 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001755 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001756 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001757 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001758 struct stream_interface *si;
1759 struct stream *s;
1760 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001761 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001762
1763 /* Check if this lua stack is schedulable. */
1764 if (!hlua || !hlua->task)
1765 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1766 "'frontend', 'backend' or 'task'"));
1767
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001768 /* Check if we run on the same thread than the xreator thread.
1769 * We cannot access to the socket if the thread is different.
1770 */
1771 if (socket->tid != tid)
1772 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1773
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001774 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001775 peer = xref_get_peer_and_lock(&socket->xref);
1776 if (!peer)
1777 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001778 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1779 si = appctx->owner;
1780 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001781
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001782 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001783 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001784 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001785 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001786 if (nblk < 0) /* Connection close. */
1787 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001788 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001789 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001790
1791 /* remove final \r\n. */
1792 if (nblk == 1) {
1793 if (blk1[len1-1] == '\n') {
1794 len1--;
1795 skip_at_end++;
1796 if (blk1[len1-1] == '\r') {
1797 len1--;
1798 skip_at_end++;
1799 }
1800 }
1801 }
1802 else {
1803 if (blk2[len2-1] == '\n') {
1804 len2--;
1805 skip_at_end++;
1806 if (blk2[len2-1] == '\r') {
1807 len2--;
1808 skip_at_end++;
1809 }
1810 }
1811 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001812 }
1813
1814 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001815 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001816 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001817 if (nblk < 0) /* Connection close. */
1818 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001819 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001820 goto connection_empty;
1821 }
1822
1823 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001824 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001825 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001826 if (nblk < 0) /* Connection close. */
1827 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001828 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001829 goto connection_empty;
1830
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001831 missing_bytes = wanted - socket->b.n;
1832 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001833 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001834 len1 = missing_bytes;
1835 } if (nblk == 2 && len1 + len2 > missing_bytes)
1836 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001837 }
1838
1839 len = len1;
1840
1841 luaL_addlstring(&socket->b, blk1, len1);
1842 if (nblk == 2) {
1843 len += len2;
1844 luaL_addlstring(&socket->b, blk2, len2);
1845 }
1846
1847 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001848 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001849
1850 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001851 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001852
1853 /* If the pattern reclaim to read all the data
1854 * in the connection, got out.
1855 */
1856 if (wanted == HLSR_READ_ALL)
1857 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001858 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001859 goto connection_empty;
1860
1861 /* Return result. */
1862 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001863 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001864 return 1;
1865
1866connection_closed:
1867
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001868 xref_unlock(&socket->xref, peer);
1869
1870no_peer:
1871
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001872 /* If the buffer containds data. */
1873 if (socket->b.n > 0) {
1874 luaL_pushresult(&socket->b);
1875 return 1;
1876 }
1877 lua_pushnil(L);
1878 lua_pushstring(L, "connection closed.");
1879 return 2;
1880
1881connection_empty:
1882
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001883 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1884 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001885 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001886 }
1887 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02001888 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001889 return 0;
1890}
1891
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001892/* This Lua function gets two parameters. The first one can be string
1893 * or a number. If the string is "*l", the user requires one line. If
1894 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001895 * If the value is a number, the user require a number of bytes equal
1896 * to the value. The default value is "*l" (a line).
1897 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001898 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001899 * integer takes this values:
1900 * -1 : read a line
1901 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001902 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001903 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001904 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001905 * concatenated with the read data.
1906 */
1907__LJMP static int hlua_socket_receive(struct lua_State *L)
1908{
1909 int wanted = HLSR_READ_LINE;
1910 const char *pattern;
1911 int type;
1912 char *error;
1913 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001914 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001915
1916 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1917 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1918
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001919 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001920
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001921 /* Check if we run on the same thread than the xreator thread.
1922 * We cannot access to the socket if the thread is different.
1923 */
1924 if (socket->tid != tid)
1925 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1926
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001927 /* check for pattern. */
1928 if (lua_gettop(L) >= 2) {
1929 type = lua_type(L, 2);
1930 if (type == LUA_TSTRING) {
1931 pattern = lua_tostring(L, 2);
1932 if (strcmp(pattern, "*a") == 0)
1933 wanted = HLSR_READ_ALL;
1934 else if (strcmp(pattern, "*l") == 0)
1935 wanted = HLSR_READ_LINE;
1936 else {
1937 wanted = strtoll(pattern, &error, 10);
1938 if (*error != '\0')
1939 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1940 }
1941 }
1942 else if (type == LUA_TNUMBER) {
1943 wanted = lua_tointeger(L, 2);
1944 if (wanted < 0)
1945 WILL_LJMP(luaL_error(L, "Unsupported size."));
1946 }
1947 }
1948
1949 /* Set pattern. */
1950 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001951
1952 /* Check if we would replace the top by itself. */
1953 if (lua_gettop(L) != 2)
1954 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001955
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001956 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001957 luaL_buffinit(L, &socket->b);
1958
1959 /* Check prefix. */
1960 if (lua_gettop(L) >= 3) {
1961 if (lua_type(L, 3) != LUA_TSTRING)
1962 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1963 pattern = lua_tolstring(L, 3, &len);
1964 luaL_addlstring(&socket->b, pattern, len);
1965 }
1966
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001967 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001968}
1969
1970/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001971 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001972 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001973static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001974{
1975 struct hlua_socket *socket;
1976 struct hlua *hlua = hlua_gethlua(L);
1977 struct appctx *appctx;
1978 size_t buf_len;
1979 const char *buf;
1980 int len;
1981 int send_len;
1982 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001983 struct xref *peer;
1984 struct stream_interface *si;
1985 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001986
1987 /* Check if this lua stack is schedulable. */
1988 if (!hlua || !hlua->task)
1989 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1990 "'frontend', 'backend' or 'task'"));
1991
1992 /* Get object */
1993 socket = MAY_LJMP(hlua_checksocket(L, 1));
1994 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001995 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001996
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001997 /* Check if we run on the same thread than the xreator thread.
1998 * We cannot access to the socket if the thread is different.
1999 */
2000 if (socket->tid != tid)
2001 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2002
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002003 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002004 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002005 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002006 lua_pushinteger(L, -1);
2007 return 1;
2008 }
2009 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2010 si = appctx->owner;
2011 s = si_strm(si);
2012
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002013 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002014 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002015 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002016 lua_pushinteger(L, -1);
2017 return 1;
2018 }
2019
2020 /* Update the input buffer data. */
2021 buf += sent;
2022 send_len = buf_len - sent;
2023
2024 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002025 if (sent >= buf_len) {
2026 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002027 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002028 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002029
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002030 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002031 * the request buffer if its not required.
2032 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002033 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002034 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002035 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002036 }
2037
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002038 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002039 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002040 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002041 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002042 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002043
2044 /* send data */
2045 if (len < send_len)
2046 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002047 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002048
2049 /* "Not enough space" (-1), "Buffer too little to contain
2050 * the data" (-2) are not expected because the available length
2051 * is tested.
2052 * Other unknown error are also not expected.
2053 */
2054 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002055 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002056 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002057
sada05ed3302018-05-11 11:48:18 -07002058 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002059 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002060 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002061 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002062 return 1;
2063 }
2064
2065 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002066 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002067
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002068 s->req.rex = TICK_ETERNITY;
2069 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002070
2071 /* Update length sent. */
2072 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002073 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002074
2075 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002076 if (sent + len >= buf_len) {
2077 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002078 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002079 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080
2081hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002082 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2083 xref_unlock(&socket->xref, peer);
2084 WILL_LJMP(luaL_error(L, "out of memory"));
2085 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002086 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002087 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002088 return 0;
2089}
2090
2091/* This function initiate the send of data. It just check the input
2092 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002093 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002094 * "hlua_socket_write_yield" that can yield.
2095 *
2096 * The Lua function gets between 3 and 4 parameters. The first one is
2097 * the associated object. The second is a string buffer. The third is
2098 * a facultative integer that represents where is the buffer position
2099 * of the start of the data that can send. The first byte is the
2100 * position "1". The default value is "1". The fourth argument is a
2101 * facultative integer that represents where is the buffer position
2102 * of the end of the data that can send. The default is the last byte.
2103 */
2104static int hlua_socket_send(struct lua_State *L)
2105{
2106 int i;
2107 int j;
2108 const char *buf;
2109 size_t buf_len;
2110
2111 /* Check number of arguments. */
2112 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2113 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2114
2115 /* Get the string. */
2116 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2117
2118 /* Get and check j. */
2119 if (lua_gettop(L) == 4) {
2120 j = MAY_LJMP(luaL_checkinteger(L, 4));
2121 if (j < 0)
2122 j = buf_len + j + 1;
2123 if (j > buf_len)
2124 j = buf_len + 1;
2125 lua_pop(L, 1);
2126 }
2127 else
2128 j = buf_len;
2129
2130 /* Get and check i. */
2131 if (lua_gettop(L) == 3) {
2132 i = MAY_LJMP(luaL_checkinteger(L, 3));
2133 if (i < 0)
2134 i = buf_len + i + 1;
2135 if (i > buf_len)
2136 i = buf_len + 1;
2137 lua_pop(L, 1);
2138 } else
2139 i = 1;
2140
2141 /* Check bth i and j. */
2142 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002143 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002144 return 1;
2145 }
2146 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002147 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002148 return 1;
2149 }
2150 if (i == 0)
2151 i = 1;
2152 if (j == 0)
2153 j = 1;
2154
2155 /* Pop the string. */
2156 lua_pop(L, 1);
2157
2158 /* Update the buffer length. */
2159 buf += i - 1;
2160 buf_len = j - i + 1;
2161 lua_pushlstring(L, buf, buf_len);
2162
2163 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002164 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002166 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002167}
2168
Willy Tarreau22b0a682015-06-17 19:43:49 +02002169#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002170__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2171{
2172 static char buffer[SOCKET_INFO_MAX_LEN];
2173 int ret;
2174 int len;
2175 char *p;
2176
2177 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2178 if (ret <= 0) {
2179 lua_pushnil(L);
2180 return 1;
2181 }
2182
2183 if (ret == AF_UNIX) {
2184 lua_pushstring(L, buffer+1);
2185 return 1;
2186 }
2187 else if (ret == AF_INET6) {
2188 buffer[0] = '[';
2189 len = strlen(buffer);
2190 buffer[len] = ']';
2191 len++;
2192 buffer[len] = ':';
2193 len++;
2194 p = buffer;
2195 }
2196 else if (ret == AF_INET) {
2197 p = buffer + 1;
2198 len = strlen(p);
2199 p[len] = ':';
2200 len++;
2201 }
2202 else {
2203 lua_pushnil(L);
2204 return 1;
2205 }
2206
2207 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2208 lua_pushnil(L);
2209 return 1;
2210 }
2211
2212 lua_pushstring(L, p);
2213 return 1;
2214}
2215
2216/* Returns information about the peer of the connection. */
2217__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2218{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002219 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002220 struct xref *peer;
2221 struct appctx *appctx;
2222 struct stream_interface *si;
2223 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002224 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002225
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 MAY_LJMP(check_args(L, 1, "getpeername"));
2227
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002228 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002229
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002230 /* Check if we run on the same thread than the xreator thread.
2231 * We cannot access to the socket if the thread is different.
2232 */
2233 if (socket->tid != tid)
2234 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2235
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002236 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002237 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002238 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002239 lua_pushnil(L);
2240 return 1;
2241 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002242 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2243 si = appctx->owner;
2244 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002246 if (!s->target_addr) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002247 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002248 lua_pushnil(L);
2249 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002250 }
2251
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002252 ret = MAY_LJMP(hlua_socket_info(L, s->target_addr));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002253 xref_unlock(&socket->xref, peer);
2254 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002255}
2256
2257/* Returns information about my connection side. */
2258static int hlua_socket_getsockname(struct lua_State *L)
2259{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002260 struct hlua_socket *socket;
2261 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002262 struct appctx *appctx;
2263 struct xref *peer;
2264 struct stream_interface *si;
2265 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002266 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002267
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002268 MAY_LJMP(check_args(L, 1, "getsockname"));
2269
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002270 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002271
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002272 /* Check if we run on the same thread than the xreator thread.
2273 * We cannot access to the socket if the thread is different.
2274 */
2275 if (socket->tid != tid)
2276 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2277
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002278 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002279 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002280 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002281 lua_pushnil(L);
2282 return 1;
2283 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002284 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2285 si = appctx->owner;
2286 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002287
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002288 conn = cs_conn(objt_cs(s->si[1].end));
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002289 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002290 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002291 lua_pushnil(L);
2292 return 1;
2293 }
2294
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002295 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002296 xref_unlock(&socket->xref, peer);
2297 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002298}
2299
2300/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002301static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302 .obj_type = OBJ_TYPE_APPLET,
2303 .name = "<LUA_TCP>",
2304 .fct = hlua_socket_handler,
2305 .release = hlua_socket_release,
2306};
2307
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002308__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002309{
2310 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2311 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002312 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002314 struct stream_interface *si;
2315 struct stream *s;
2316
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002317 /* Check if we run on the same thread than the xreator thread.
2318 * We cannot access to the socket if the thread is different.
2319 */
2320 if (socket->tid != tid)
2321 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2322
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002323 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002324 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002325 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002326 lua_pushnil(L);
2327 lua_pushstring(L, "Can't connect");
2328 return 2;
2329 }
2330 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2331 si = appctx->owner;
2332 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002333
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002334 /* Check if we run on the same thread than the xreator thread.
2335 * We cannot access to the socket if the thread is different.
2336 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002337 if (socket->tid != tid) {
2338 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002339 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002340 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002341
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002342 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002343 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002344 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345 lua_pushnil(L);
2346 lua_pushstring(L, "Can't connect");
2347 return 2;
2348 }
2349
Willy Tarreaue09101e2018-10-16 17:37:12 +02002350 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002351
2352 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002353 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002354 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002355 lua_pushinteger(L, 1);
2356 return 1;
2357 }
2358
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002359 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2360 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002361 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002362 }
2363 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002364 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365 return 0;
2366}
2367
2368/* This function fail or initite the connection. */
2369__LJMP static int hlua_socket_connect(struct lua_State *L)
2370{
2371 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002372 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002374 struct hlua *hlua;
2375 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002376 int low, high;
2377 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002378 struct xref *peer;
2379 struct stream_interface *si;
2380 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002381
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002382 if (lua_gettop(L) < 2)
2383 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002384
2385 /* Get args. */
2386 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002387
2388 /* Check if we run on the same thread than the xreator thread.
2389 * We cannot access to the socket if the thread is different.
2390 */
2391 if (socket->tid != tid)
2392 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2393
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002394 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002395 if (lua_gettop(L) >= 3) {
2396 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002397 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002398
Tim Duesterhus6edab862018-01-06 19:04:45 +01002399 /* Force the ip to end with a colon, to support IPv6 addresses
2400 * that are not enclosed within square brackets.
2401 */
2402 if (port > 0) {
2403 luaL_buffinit(L, &b);
2404 luaL_addstring(&b, ip);
2405 luaL_addchar(&b, ':');
2406 luaL_pushresult(&b);
2407 ip = lua_tolstring(L, lua_gettop(L), NULL);
2408 }
2409 }
2410
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002411 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002412 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002413 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002414 lua_pushnil(L);
2415 return 1;
2416 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002417
2418 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002419 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002420 if (!addr) {
2421 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002422 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002423 }
2424 if (low != high) {
2425 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002426 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002427 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002428
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002429 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002430 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002431 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002432 if (port == -1) {
2433 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002434 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002435 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002436 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2437 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002438 if (port == -1) {
2439 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002440 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002441 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002442 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002443 }
2444 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002445
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002446 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2447 si = appctx->owner;
2448 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002449
2450 if (!sockaddr_alloc(&s->target_addr)) {
2451 xref_unlock(&socket->xref, peer);
2452 WILL_LJMP(luaL_error(L, "connect: internal error"));
2453 }
2454 *s->target_addr = *addr;
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002455 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002456
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002457 hlua = hlua_gethlua(L);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002458
2459 /* inform the stream that we want to be notified whenever the
2460 * connection completes.
2461 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002462 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002463 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002464 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002465
Willy Tarreauf31af932020-01-14 09:59:38 +01002466 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002467
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002468 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2469 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002470 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002471 }
2472 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002473
2474 task_wakeup(s->task, TASK_WOKEN_INIT);
2475 /* Return yield waiting for connection. */
2476
Willy Tarreau9635e032018-10-16 17:52:55 +02002477 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002478
2479 return 0;
2480}
2481
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002482#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002483__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2484{
2485 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002486 struct xref *peer;
2487 struct appctx *appctx;
2488 struct stream_interface *si;
2489 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002490
2491 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2492 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002493
2494 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002495 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002496 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002497 lua_pushnil(L);
2498 return 1;
2499 }
2500 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2501 si = appctx->owner;
2502 s = si_strm(si);
2503
2504 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002505 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002506 return MAY_LJMP(hlua_socket_connect(L));
2507}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002508#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002509
2510__LJMP static int hlua_socket_setoption(struct lua_State *L)
2511{
2512 return 0;
2513}
2514
2515__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2516{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002517 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002518 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002519 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002520 struct xref *peer;
2521 struct appctx *appctx;
2522 struct stream_interface *si;
2523 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002524
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002525 MAY_LJMP(check_args(L, 2, "settimeout"));
2526
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002527 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002528
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002529 /* convert the timeout to millis */
2530 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002531
Thierry Fournier17a921b2018-03-08 09:59:02 +01002532 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002533 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002534 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2535
Mark Lakes56cc1252018-03-27 09:48:06 +02002536 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002537 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002538
2539 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002540 if (tmout == 0)
2541 tmout++; /* very small timeouts are adjusted to a minium of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002542
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002543 /* Check if we run on the same thread than the xreator thread.
2544 * We cannot access to the socket if the thread is different.
2545 */
2546 if (socket->tid != tid)
2547 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2548
Mark Lakes56cc1252018-03-27 09:48:06 +02002549 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002550 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002551 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002552 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2553 WILL_LJMP(lua_error(L));
2554 return 0;
2555 }
2556 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2557 si = appctx->owner;
2558 s = si_strm(si);
2559
Cyril Bonté7bb63452018-08-17 23:51:02 +02002560 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002561 s->req.rto = tmout;
2562 s->req.wto = tmout;
2563 s->res.rto = tmout;
2564 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002565 s->req.rex = tick_add_ifset(now_ms, tmout);
2566 s->req.wex = tick_add_ifset(now_ms, tmout);
2567 s->res.rex = tick_add_ifset(now_ms, tmout);
2568 s->res.wex = tick_add_ifset(now_ms, tmout);
2569
2570 s->task->expire = tick_add_ifset(now_ms, tmout);
2571 task_queue(s->task);
2572
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002573 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002574
Thierry Fourniere9636f12018-03-08 09:54:32 +01002575 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002576 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002577}
2578
2579__LJMP static int hlua_socket_new(lua_State *L)
2580{
2581 struct hlua_socket *socket;
2582 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002583 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002584 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002585
2586 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002587 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002588 hlua_pusherror(L, "socket: full stack");
2589 goto out_fail_conf;
2590 }
2591
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002592 /* Create the object: obj[0] = userdata. */
2593 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002594 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002595 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002596 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002597 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002598
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002599 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002600 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002601 hlua_pusherror(L, "socket: uninitialized pools.");
2602 goto out_fail_conf;
2603 }
2604
Willy Tarreau87b09662015-04-03 00:22:06 +02002605 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002606 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2607 lua_setmetatable(L, -2);
2608
Willy Tarreaud420a972015-04-06 00:39:18 +02002609 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002610 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002611 if (!appctx) {
2612 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002613 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002614 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002615
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002616 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002617 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002618 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2619 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002620
Willy Tarreaud420a972015-04-06 00:39:18 +02002621 /* Now create a session, task and stream for this applet */
2622 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2623 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002624 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002625 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002626 }
2627
Willy Tarreau87787ac2017-08-28 16:22:54 +02002628 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002629 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002630 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002631 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002632 }
2633
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002634 /* Initialise cross reference between stream and Lua socket object. */
2635 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002636
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002637 /* Configure "right" stream interface. this "si" is used to connect
2638 * and retrieve data from the server. The connection is initialized
2639 * with the "struct server".
2640 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002641 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002642
2643 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002644 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002645 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002646
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002647 return 1;
2648
Willy Tarreaud420a972015-04-06 00:39:18 +02002649 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002650 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002651 out_fail_sess:
2652 appctx_free(appctx);
2653 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002654 WILL_LJMP(lua_error(L));
2655 return 0;
2656}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002657
2658/*
2659 *
2660 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002661 * Class Channel
2662 *
2663 *
2664 */
2665
2666/* Returns the struct hlua_channel join to the class channel in the
2667 * stack entry "ud" or throws an argument error.
2668 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002669__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002670{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002671 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002672}
2673
Willy Tarreau47860ed2015-03-10 14:07:50 +01002674/* Pushes the channel onto the top of the stack. If the stask does not have a
2675 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002676 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002677static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002678{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002679 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002680 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002681 return 0;
2682
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002683 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002684 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002685 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002686
2687 /* Pop a class sesison metatable and affect it to the userdata. */
2688 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2689 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002690 return 1;
2691}
2692
2693/* Duplicate all the data present in the input channel and put it
2694 * in a string LUA variables. Returns -1 and push a nil value in
2695 * the stack if the channel is closed and all the data are consumed,
2696 * returns 0 if no data are available, otherwise it returns the length
2697 * of the builded string.
2698 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002699static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002700{
2701 char *blk1;
2702 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002703 size_t len1;
2704 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002705 int ret;
2706 luaL_Buffer b;
2707
Willy Tarreau06d80a92017-10-19 14:32:15 +02002708 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002709 if (unlikely(ret == 0))
2710 return 0;
2711
2712 if (unlikely(ret < 0)) {
2713 lua_pushnil(L);
2714 return -1;
2715 }
2716
2717 luaL_buffinit(L, &b);
2718 luaL_addlstring(&b, blk1, len1);
2719 if (unlikely(ret == 2))
2720 luaL_addlstring(&b, blk2, len2);
2721 luaL_pushresult(&b);
2722
2723 if (unlikely(ret == 2))
2724 return len1 + len2;
2725 return len1;
2726}
2727
2728/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2729 * a yield. This function keep the data in the buffer.
2730 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002731__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002732{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002733 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002734
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002735 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2736
Christopher Faulet3f829a42018-12-13 21:56:45 +01002737 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2738 WILL_LJMP(lua_error(L));
2739
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002740 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002741 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002742 return 1;
2743}
2744
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002745/* Check arguments for the function "hlua_channel_dup_yield". */
2746__LJMP static int hlua_channel_dup(lua_State *L)
2747{
2748 MAY_LJMP(check_args(L, 1, "dup"));
2749 MAY_LJMP(hlua_checkchannel(L, 1));
2750 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2751}
2752
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002753/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2754 * a yield. This function consumes the data in the buffer. It returns
2755 * a string containing the data or a nil pointer if no data are available
2756 * and the channel is closed.
2757 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002758__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002759{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002760 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002761 int ret;
2762
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002763 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002764
Christopher Faulet3f829a42018-12-13 21:56:45 +01002765 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2766 WILL_LJMP(lua_error(L));
2767
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002768 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002769 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02002770 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002771
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002772 if (unlikely(ret == -1))
2773 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002774
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002775 b_sub(&chn->buf, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002776 return 1;
2777}
2778
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002779/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002780__LJMP static int hlua_channel_get(lua_State *L)
2781{
2782 MAY_LJMP(check_args(L, 1, "get"));
2783 MAY_LJMP(hlua_checkchannel(L, 1));
2784 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2785}
2786
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002787/* This functions consumes and returns one line. If the channel is closed,
2788 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002789 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002790 * value.
2791 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002792__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002793{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002794 char *blk1;
2795 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002796 size_t len1;
2797 size_t len2;
2798 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002799 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002800 int ret;
2801 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002802
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002803 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2804
Christopher Faulet3f829a42018-12-13 21:56:45 +01002805 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2806 WILL_LJMP(lua_error(L));
2807
Willy Tarreau06d80a92017-10-19 14:32:15 +02002808 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002809 if (ret == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002810 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002811
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002812 if (ret == -1) {
2813 lua_pushnil(L);
2814 return 1;
2815 }
2816
2817 luaL_buffinit(L, &b);
2818 luaL_addlstring(&b, blk1, len1);
2819 len = len1;
2820 if (unlikely(ret == 2)) {
2821 luaL_addlstring(&b, blk2, len2);
2822 len += len2;
2823 }
2824 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002825 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002826 return 1;
2827}
2828
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002829/* Check arguments for the function "hlua_channel_getline_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002830__LJMP static int hlua_channel_getline(lua_State *L)
2831{
2832 MAY_LJMP(check_args(L, 1, "getline"));
2833 MAY_LJMP(hlua_checkchannel(L, 1));
2834 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2835}
2836
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002837/* This function takes a string as input, and append it at the
2838 * input side of channel. If the data is too big, but a space
2839 * is probably available after sending some data, the function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002840 * yields. If the data is bigger than the buffer, or if the
2841 * channel is closed, it returns -1. Otherwise, it returns the
2842 * amount of data written.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002843 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002844__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002845{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002846 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002847 size_t len;
2848 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2849 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2850 int ret;
2851 int max;
2852
Christopher Faulet3f829a42018-12-13 21:56:45 +01002853 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2854 WILL_LJMP(lua_error(L));
2855
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002856 /* Check if the buffer is available because HAProxy doesn't allocate
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002857 * the request buffer if its not required.
2858 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002859 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002860 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002861 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002862 }
2863
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002864 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002865 if (max > len - l)
2866 max = len - l;
2867
Willy Tarreau06d80a92017-10-19 14:32:15 +02002868 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002869 if (ret == -2 || ret == -3) {
2870 lua_pushinteger(L, -1);
2871 return 1;
2872 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002873 if (ret == -1) {
2874 chn->flags |= CF_WAKE_WRITE;
Willy Tarreau9635e032018-10-16 17:52:55 +02002875 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002876 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002877 l += ret;
2878 lua_pop(L, 1);
2879 lua_pushinteger(L, l);
2880
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002881 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02002882 if (max == 0 && co_data(chn) == 0) {
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002883 /* There are no space available, and the output buffer is empty.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002884 * in this case, we cannot add more data, so we cannot yield,
2885 * we return the amount of copyied data.
2886 */
2887 return 1;
2888 }
2889 if (l < len)
Willy Tarreau9635e032018-10-16 17:52:55 +02002890 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002891 return 1;
2892}
2893
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002894/* Just a wrapper of "hlua_channel_append_yield". It returns the length
2895 * of the written string, or -1 if the channel is closed or if the
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002896 * buffer size is too little for the data.
2897 */
2898__LJMP static int hlua_channel_append(lua_State *L)
2899{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002900 size_t len;
2901
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002902 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002903 MAY_LJMP(hlua_checkchannel(L, 1));
2904 MAY_LJMP(luaL_checklstring(L, 2, &len));
2905 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002906 lua_pushinteger(L, 0);
2907
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002908 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002909}
2910
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002911/* Just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002912 * his process by cleaning the buffer. The result is a replacement
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002913 * of the current data. It returns the length of the written string,
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002914 * or -1 if the channel is closed or if the buffer size is too
2915 * little for the data.
2916 */
2917__LJMP static int hlua_channel_set(lua_State *L)
2918{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002919 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002920
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002921 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002922 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002923 lua_pushinteger(L, 0);
2924
Christopher Faulet3f829a42018-12-13 21:56:45 +01002925 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2926 WILL_LJMP(lua_error(L));
2927
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002928 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002929
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002930 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002931}
2932
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002933/* Append data in the output side of the buffer. This data is immediately
2934 * sent. The function returns the amount of data written. If the buffer
2935 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002936 * if the channel is closed.
2937 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002938__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002939{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002940 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002941 size_t len;
2942 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2943 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2944 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002945 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002946
Christopher Faulet3f829a42018-12-13 21:56:45 +01002947 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
2948 WILL_LJMP(lua_error(L));
2949
Willy Tarreau47860ed2015-03-10 14:07:50 +01002950 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002951 lua_pushinteger(L, -1);
2952 return 1;
2953 }
2954
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002955 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002956 * the request buffer if its not required.
2957 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002958 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01002959 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02002960 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002961 }
2962
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002963 /* The written data will be immediately sent, so we can check
2964 * the available space without taking in account the reserve.
2965 * The reserve is guaranteed for the processing of incoming
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002966 * data, because the buffer will be flushed.
2967 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002968 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002969
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002970 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002971 * in this case, we cannot add more data, so we cannot yield,
2972 * we return the amount of copyied data.
2973 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02002974 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002975 return 1;
2976
2977 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002978 if (max > len - l)
2979 max = len - l;
2980
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002981 /* The buffer available size may be not contiguous. This test
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002982 * detects a non contiguous buffer and realign it.
2983 */
Willy Tarreau3f679992018-06-15 15:06:42 +02002984 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002985 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002986
2987 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002988 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002989
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002990 /* buffer replace considers that the input part is filled.
2991 * so, I must forward these new data in the output part.
2992 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02002993 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002994
2995 l += max;
2996 lua_pop(L, 1);
2997 lua_pushinteger(L, l);
2998
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002999 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003000 * in this case, we cannot add more data, so we cannot yield,
3001 * we return the amount of copyied data.
3002 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003003 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003004 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003005 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003006
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003007 if (l < len) {
3008 /* If we are waiting for space in the response buffer, we
3009 * must set the flag WAKERESWR. This flag required the task
3010 * wake up if any activity is detected on the response buffer.
3011 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003012 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003013 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003014 else
3015 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003016 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003017 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003018
3019 return 1;
3020}
3021
3022/* Just a wraper of "_hlua_channel_send". This wrapper permits
3023 * yield the LUA process, and resume it without checking the
3024 * input arguments.
3025 */
3026__LJMP static int hlua_channel_send(lua_State *L)
3027{
3028 MAY_LJMP(check_args(L, 2, "send"));
3029 lua_pushinteger(L, 0);
3030
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003031 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003032}
3033
3034/* This function forward and amount of butes. The data pass from
3035 * the input side of the buffer to the output side, and can be
3036 * forwarded. This function never fails.
3037 *
3038 * The Lua function takes an amount of bytes to be forwarded in
3039 * imput. It returns the number of bytes forwarded.
3040 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003041__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003042{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003043 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003044 int len;
3045 int l;
3046 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003047 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003048
3049 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003050
3051 if (chn_strm(chn)->be->mode == PR_MODE_HTTP)
3052 WILL_LJMP(lua_error(L));
3053
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003054 len = MAY_LJMP(luaL_checkinteger(L, 2));
3055 l = MAY_LJMP(luaL_checkinteger(L, -1));
3056
3057 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003058 if (max > ci_data(chn))
3059 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003060 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003061 l += max;
3062
3063 lua_pop(L, 1);
3064 lua_pushinteger(L, l);
3065
3066 /* Check if it miss bytes to forward. */
3067 if (l < len) {
3068 /* The the input channel or the output channel are closed, we
3069 * must return the amount of data forwarded.
3070 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003071 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003072 return 1;
3073
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003074 /* If we are waiting for space data in the response buffer, we
3075 * must set the flag WAKERESWR. This flag required the task
3076 * wake up if any activity is detected on the response buffer.
3077 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003078 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003079 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003080 else
3081 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003082
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003083 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003084 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003085 }
3086
3087 return 1;
3088}
3089
3090/* Just check the input and prepare the stack for the previous
3091 * function "hlua_channel_forward_yield"
3092 */
3093__LJMP static int hlua_channel_forward(lua_State *L)
3094{
3095 MAY_LJMP(check_args(L, 2, "forward"));
3096 MAY_LJMP(hlua_checkchannel(L, 1));
3097 MAY_LJMP(luaL_checkinteger(L, 2));
3098
3099 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003100 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003101}
3102
3103/* Just returns the number of bytes available in the input
3104 * side of the buffer. This function never fails.
3105 */
3106__LJMP static int hlua_channel_get_in_len(lua_State *L)
3107{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003108 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003109
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003110 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003111 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003112 if (IS_HTX_STRM(chn_strm(chn))) {
3113 struct htx *htx = htxbuf(&chn->buf);
3114 lua_pushinteger(L, htx->data - co_data(chn));
3115 }
3116 else
3117 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003118 return 1;
3119}
3120
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003121/* Returns true if the channel is full. */
3122__LJMP static int hlua_channel_is_full(lua_State *L)
3123{
3124 struct channel *chn;
3125 int rem;
3126
3127 MAY_LJMP(check_args(L, 1, "is_full"));
3128 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3129
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003130 if (IS_HTX_STRM(chn_strm(chn))) {
3131 struct htx *htx = htxbuf(&chn->buf);
3132
3133 rem = htx_free_data_space(htx);
3134 }
3135 else
3136 rem = b_room(&chn->buf);
3137
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003138 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3139
3140 lua_pushboolean(L, rem <= 0);
3141 return 1;
3142}
3143
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003144/* Just returns the number of bytes available in the output
3145 * side of the buffer. This function never fails.
3146 */
3147__LJMP static int hlua_channel_get_out_len(lua_State *L)
3148{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003149 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003150
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003151 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003152 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003153 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003154 return 1;
3155}
3156
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003157/*
3158 *
3159 *
3160 * Class Fetches
3161 *
3162 *
3163 */
3164
3165/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003166 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003167 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003168__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003169{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003170 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003171}
3172
3173/* This function creates and push in the stack a fetch object according
3174 * with a current TXN.
3175 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003176static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003177{
Willy Tarreau7073c472015-04-06 11:15:40 +02003178 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003179
3180 /* Check stack size. */
3181 if (!lua_checkstack(L, 3))
3182 return 0;
3183
3184 /* Create the object: obj[0] = userdata.
3185 * Note that the base of the Fetches object is the
3186 * transaction object.
3187 */
3188 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003189 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003190 lua_rawseti(L, -2, 0);
3191
Willy Tarreau7073c472015-04-06 11:15:40 +02003192 hsmp->s = txn->s;
3193 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003194 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003195 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003196
3197 /* Pop a class sesison metatable and affect it to the userdata. */
3198 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3199 lua_setmetatable(L, -2);
3200
3201 return 1;
3202}
3203
3204/* This function is an LUA binding. It is called with each sample-fetch.
3205 * It uses closure argument to store the associated sample-fetch. It
3206 * returns only one argument or throws an error. An error is thrown
3207 * only if an error is encountered during the argument parsing. If
3208 * the "sample-fetch" function fails, nil is returned.
3209 */
3210__LJMP static int hlua_run_sample_fetch(lua_State *L)
3211{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003212 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003213 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003214 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003215 int i;
3216 struct sample smp;
3217
3218 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003219 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003220
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003221 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003222 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003223
Thierry FOURNIERca988662015-12-20 18:43:03 +01003224 /* Check execution authorization. */
3225 if (f->use & SMP_USE_HTTP_ANY &&
3226 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3227 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3228 "is not available in Lua services", f->kw);
3229 WILL_LJMP(lua_error(L));
3230 }
3231
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003232 /* Get extra arguments. */
3233 for (i = 0; i < lua_gettop(L) - 1; i++) {
3234 if (i >= ARGM_NBARGS)
3235 break;
3236 hlua_lua2arg(L, i + 2, &args[i]);
3237 }
3238 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003239 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003240
3241 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003242 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003243
3244 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003245 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003246 lua_pushfstring(L, "error in arguments");
3247 WILL_LJMP(lua_error(L));
3248 }
3249
3250 /* Initialise the sample. */
3251 memset(&smp, 0, sizeof(smp));
3252
3253 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003254 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003255 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003256 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003257 lua_pushstring(L, "");
3258 else
3259 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003260 return 1;
3261 }
3262
3263 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003264 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003265 hlua_smp2lua_str(L, &smp);
3266 else
3267 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003268 return 1;
3269}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003270
3271/*
3272 *
3273 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003274 * Class Converters
3275 *
3276 *
3277 */
3278
3279/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003280 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003281 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003282__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003283{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003284 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003285}
3286
3287/* This function creates and push in the stack a Converters object
3288 * according with a current TXN.
3289 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003290static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003291{
Willy Tarreau7073c472015-04-06 11:15:40 +02003292 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003293
3294 /* Check stack size. */
3295 if (!lua_checkstack(L, 3))
3296 return 0;
3297
3298 /* Create the object: obj[0] = userdata.
3299 * Note that the base of the Converters object is the
3300 * same than the TXN object.
3301 */
3302 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003303 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003304 lua_rawseti(L, -2, 0);
3305
Willy Tarreau7073c472015-04-06 11:15:40 +02003306 hsmp->s = txn->s;
3307 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003308 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003309 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003310
Willy Tarreau87b09662015-04-03 00:22:06 +02003311 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003312 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3313 lua_setmetatable(L, -2);
3314
3315 return 1;
3316}
3317
3318/* This function is an LUA binding. It is called with each converter.
3319 * It uses closure argument to store the associated converter. It
3320 * returns only one argument or throws an error. An error is thrown
3321 * only if an error is encountered during the argument parsing. If
3322 * the converter function function fails, nil is returned.
3323 */
3324__LJMP static int hlua_run_sample_conv(lua_State *L)
3325{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003326 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003327 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003328 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003329 int i;
3330 struct sample smp;
3331
3332 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003333 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003334
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003335 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003336 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003337
3338 /* Get extra arguments. */
3339 for (i = 0; i < lua_gettop(L) - 2; i++) {
3340 if (i >= ARGM_NBARGS)
3341 break;
3342 hlua_lua2arg(L, i + 3, &args[i]);
3343 }
3344 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003345 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003346
3347 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003348 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003349
3350 /* Run the special args checker. */
3351 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3352 hlua_pusherror(L, "error in arguments");
3353 WILL_LJMP(lua_error(L));
3354 }
3355
3356 /* Initialise the sample. */
3357 if (!hlua_lua2smp(L, 2, &smp)) {
3358 hlua_pusherror(L, "error in the input argument");
3359 WILL_LJMP(lua_error(L));
3360 }
3361
Willy Tarreau1777ea62016-03-10 16:15:46 +01003362 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3363
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003364 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003365 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003366 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003367 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003368 WILL_LJMP(lua_error(L));
3369 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003370 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3371 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003372 hlua_pusherror(L, "error during the input argument casting");
3373 WILL_LJMP(lua_error(L));
3374 }
3375
3376 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003377 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003378 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003379 lua_pushstring(L, "");
3380 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003381 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003382 return 1;
3383 }
3384
3385 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003386 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003387 hlua_smp2lua_str(L, &smp);
3388 else
3389 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003390 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003391}
3392
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003393/*
3394 *
3395 *
3396 * Class AppletTCP
3397 *
3398 *
3399 */
3400
3401/* Returns a struct hlua_txn if the stack entry "ud" is
3402 * a class stream, otherwise it throws an error.
3403 */
3404__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3405{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003406 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003407}
3408
3409/* This function creates and push in the stack an Applet object
3410 * according with a current TXN.
3411 */
3412static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3413{
3414 struct hlua_appctx *appctx;
3415 struct stream_interface *si = ctx->owner;
3416 struct stream *s = si_strm(si);
3417 struct proxy *p = s->be;
3418
3419 /* Check stack size. */
3420 if (!lua_checkstack(L, 3))
3421 return 0;
3422
3423 /* Create the object: obj[0] = userdata.
3424 * Note that the base of the Converters object is the
3425 * same than the TXN object.
3426 */
3427 lua_newtable(L);
3428 appctx = lua_newuserdata(L, sizeof(*appctx));
3429 lua_rawseti(L, -2, 0);
3430 appctx->appctx = ctx;
3431 appctx->htxn.s = s;
3432 appctx->htxn.p = p;
3433
3434 /* Create the "f" field that contains a list of fetches. */
3435 lua_pushstring(L, "f");
3436 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3437 return 0;
3438 lua_settable(L, -3);
3439
3440 /* Create the "sf" field that contains a list of stringsafe fetches. */
3441 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003442 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003443 return 0;
3444 lua_settable(L, -3);
3445
3446 /* Create the "c" field that contains a list of converters. */
3447 lua_pushstring(L, "c");
3448 if (!hlua_converters_new(L, &appctx->htxn, 0))
3449 return 0;
3450 lua_settable(L, -3);
3451
3452 /* Create the "sc" field that contains a list of stringsafe converters. */
3453 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003454 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003455 return 0;
3456 lua_settable(L, -3);
3457
3458 /* Pop a class stream metatable and affect it to the table. */
3459 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3460 lua_setmetatable(L, -2);
3461
3462 return 1;
3463}
3464
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003465__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3466{
3467 struct hlua_appctx *appctx;
3468 struct stream *s;
3469 const char *name;
3470 size_t len;
3471 struct sample smp;
3472
3473 MAY_LJMP(check_args(L, 3, "set_var"));
3474
3475 /* It is useles to retrieve the stream, but this function
3476 * runs only in a stream context.
3477 */
3478 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3479 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3480 s = appctx->htxn.s;
3481
3482 /* Converts the third argument in a sample. */
3483 hlua_lua2smp(L, 3, &smp);
3484
3485 /* Store the sample in a variable. */
3486 smp_set_owner(&smp, s->be, s->sess, s, 0);
3487 vars_set_by_name(name, len, &smp);
3488 return 0;
3489}
3490
3491__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3492{
3493 struct hlua_appctx *appctx;
3494 struct stream *s;
3495 const char *name;
3496 size_t len;
3497 struct sample smp;
3498
3499 MAY_LJMP(check_args(L, 2, "unset_var"));
3500
3501 /* It is useles to retrieve the stream, but this function
3502 * runs only in a stream context.
3503 */
3504 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3505 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3506 s = appctx->htxn.s;
3507
3508 /* Unset the variable. */
3509 smp_set_owner(&smp, s->be, s->sess, s, 0);
3510 vars_unset_by_name(name, len, &smp);
3511 return 0;
3512}
3513
3514__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3515{
3516 struct hlua_appctx *appctx;
3517 struct stream *s;
3518 const char *name;
3519 size_t len;
3520 struct sample smp;
3521
3522 MAY_LJMP(check_args(L, 2, "get_var"));
3523
3524 /* It is useles to retrieve the stream, but this function
3525 * runs only in a stream context.
3526 */
3527 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3528 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3529 s = appctx->htxn.s;
3530
3531 smp_set_owner(&smp, s->be, s->sess, s, 0);
3532 if (!vars_get_by_name(name, len, &smp)) {
3533 lua_pushnil(L);
3534 return 1;
3535 }
3536
3537 return hlua_smp2lua(L, &smp);
3538}
3539
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003540__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3541{
3542 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3543 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003544 struct hlua *hlua;
3545
3546 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003547 if (!s->hlua)
3548 return 0;
3549 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003550
3551 MAY_LJMP(check_args(L, 2, "set_priv"));
3552
3553 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003554 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003555
3556 /* Get and store new value. */
3557 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3558 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3559
3560 return 0;
3561}
3562
3563__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3564{
3565 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3566 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003567 struct hlua *hlua;
3568
3569 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003570 if (!s->hlua) {
3571 lua_pushnil(L);
3572 return 1;
3573 }
3574 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003575
3576 /* Push configuration index in the stack. */
3577 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3578
3579 return 1;
3580}
3581
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003582/* If expected data not yet available, it returns a yield. This function
3583 * consumes the data in the buffer. It returns a string containing the
3584 * data. This string can be empty.
3585 */
3586__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3587{
3588 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3589 struct stream_interface *si = appctx->appctx->owner;
3590 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003591 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003592 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003593 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003594 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003595
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003596 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003597 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003598
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003599 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003600 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003601 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003602 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003603 }
3604
3605 /* End of data: commit the total strings and return. */
3606 if (ret < 0) {
3607 luaL_pushresult(&appctx->b);
3608 return 1;
3609 }
3610
3611 /* Ensure that the block 2 length is usable. */
3612 if (ret == 1)
3613 len2 = 0;
3614
3615 /* dont check the max length read and dont check. */
3616 luaL_addlstring(&appctx->b, blk1, len1);
3617 luaL_addlstring(&appctx->b, blk2, len2);
3618
3619 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003620 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003621 luaL_pushresult(&appctx->b);
3622 return 1;
3623}
3624
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003625/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003626__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3627{
3628 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3629
3630 /* Initialise the string catenation. */
3631 luaL_buffinit(L, &appctx->b);
3632
3633 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3634}
3635
3636/* If expected data not yet available, it returns a yield. This function
3637 * consumes the data in the buffer. It returns a string containing the
3638 * data. This string can be empty.
3639 */
3640__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3641{
3642 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3643 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003644 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003645 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003646 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003647 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003648 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003649 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003650
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003651 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003652 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003653
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003654 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003655 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003656 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003657 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003658 }
3659
3660 /* End of data: commit the total strings and return. */
3661 if (ret < 0) {
3662 luaL_pushresult(&appctx->b);
3663 return 1;
3664 }
3665
3666 /* Ensure that the block 2 length is usable. */
3667 if (ret == 1)
3668 len2 = 0;
3669
3670 if (len == -1) {
3671
3672 /* If len == -1, catenate all the data avalaile and
3673 * yield because we want to get all the data until
3674 * the end of data stream.
3675 */
3676 luaL_addlstring(&appctx->b, blk1, len1);
3677 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003678 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003679 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003680 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003681
3682 } else {
3683
3684 /* Copy the fisrt block caping to the length required. */
3685 if (len1 > len)
3686 len1 = len;
3687 luaL_addlstring(&appctx->b, blk1, len1);
3688 len -= len1;
3689
3690 /* Copy the second block. */
3691 if (len2 > len)
3692 len2 = len;
3693 luaL_addlstring(&appctx->b, blk2, len2);
3694 len -= len2;
3695
3696 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003697 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003698
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003699 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003700 if (len > 0) {
3701 lua_pushinteger(L, len);
3702 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003703 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003704 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003705 }
3706
3707 /* return the result. */
3708 luaL_pushresult(&appctx->b);
3709 return 1;
3710 }
3711
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003712 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003713 hlua_pusherror(L, "Lua: internal error");
3714 WILL_LJMP(lua_error(L));
3715 return 0;
3716}
3717
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003718/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003719__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3720{
3721 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3722 int len = -1;
3723
3724 if (lua_gettop(L) > 2)
3725 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3726 if (lua_gettop(L) >= 2) {
3727 len = MAY_LJMP(luaL_checkinteger(L, 2));
3728 lua_pop(L, 1);
3729 }
3730
3731 /* Confirm or set the required length */
3732 lua_pushinteger(L, len);
3733
3734 /* Initialise the string catenation. */
3735 luaL_buffinit(L, &appctx->b);
3736
3737 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3738}
3739
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003740/* Append data in the output side of the buffer. This data is immediately
3741 * sent. The function returns the amount of data written. If the buffer
3742 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003743 * if the channel is closed.
3744 */
3745__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3746{
3747 size_t len;
3748 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3749 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3750 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3751 struct stream_interface *si = appctx->appctx->owner;
3752 struct channel *chn = si_ic(si);
3753 int max;
3754
3755 /* Get the max amount of data which can write as input in the channel. */
3756 max = channel_recv_max(chn);
3757 if (max > (len - l))
3758 max = len - l;
3759
3760 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003761 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003762
3763 /* update counters. */
3764 l += max;
3765 lua_pop(L, 1);
3766 lua_pushinteger(L, l);
3767
3768 /* If some data is not send, declares the situation to the
3769 * applet, and returns a yield.
3770 */
3771 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01003772 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003773 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003774 }
3775
3776 return 1;
3777}
3778
3779/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3780 * yield the LUA process, and resume it without checking the
3781 * input arguments.
3782 */
3783__LJMP static int hlua_applet_tcp_send(lua_State *L)
3784{
3785 MAY_LJMP(check_args(L, 2, "send"));
3786 lua_pushinteger(L, 0);
3787
3788 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3789}
3790
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003791/*
3792 *
3793 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003794 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003795 *
3796 *
3797 */
3798
3799/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003800 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003801 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003802__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003803{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003804 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003805}
3806
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003807/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003808 * according with a current TXN.
3809 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003810static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003811{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003812 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003813 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003814 struct stream_interface *si = ctx->owner;
3815 struct stream *s = si_strm(si);
3816 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02003817 struct htx *htx;
3818 struct htx_blk *blk;
3819 struct htx_sl *sl;
3820 struct ist path;
3821 unsigned long long len = 0;
3822 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003823
3824 /* Check stack size. */
3825 if (!lua_checkstack(L, 3))
3826 return 0;
3827
3828 /* Create the object: obj[0] = userdata.
3829 * Note that the base of the Converters object is the
3830 * same than the TXN object.
3831 */
3832 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003833 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003834 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003835 appctx->appctx = ctx;
3836 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003837 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003838 appctx->htxn.s = s;
3839 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003840
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003841 /* Create the "f" field that contains a list of fetches. */
3842 lua_pushstring(L, "f");
3843 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3844 return 0;
3845 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003846
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003847 /* Create the "sf" field that contains a list of stringsafe fetches. */
3848 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003849 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003850 return 0;
3851 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003852
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003853 /* Create the "c" field that contains a list of converters. */
3854 lua_pushstring(L, "c");
3855 if (!hlua_converters_new(L, &appctx->htxn, 0))
3856 return 0;
3857 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003858
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003859 /* Create the "sc" field that contains a list of stringsafe converters. */
3860 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003861 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003862 return 0;
3863 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003864
Christopher Fauleta2097962019-07-15 16:25:33 +02003865 htx = htxbuf(&s->req.buf);
3866 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01003867 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02003868 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003869
Christopher Fauleta2097962019-07-15 16:25:33 +02003870 /* Stores the request method. */
3871 lua_pushstring(L, "method");
3872 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
3873 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003874
Christopher Fauleta2097962019-07-15 16:25:33 +02003875 /* Stores the http version. */
3876 lua_pushstring(L, "version");
3877 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
3878 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003879
Christopher Fauleta2097962019-07-15 16:25:33 +02003880 /* creates an array of headers. hlua_http_get_headers() crates and push
3881 * the array on the top of the stack.
3882 */
3883 lua_pushstring(L, "headers");
3884 htxn.s = s;
3885 htxn.p = px;
3886 htxn.dir = SMP_OPT_DIR_REQ;
3887 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3888 return 0;
3889 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003890
Christopher Fauleta2097962019-07-15 16:25:33 +02003891 path = http_get_path(htx_sl_req_uri(sl));
3892 if (path.ptr) {
3893 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003894
Christopher Fauleta2097962019-07-15 16:25:33 +02003895 p = path.ptr;
3896 end = path.ptr + path.len;
3897 q = p;
3898 while (q < end && *q != '?')
3899 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003900
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003901 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02003902 lua_pushstring(L, "path");
3903 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003904 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003905
Christopher Fauleta2097962019-07-15 16:25:33 +02003906 /* Stores the query string. */
3907 lua_pushstring(L, "qs");
3908 if (*q == '?')
3909 q++;
3910 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003911 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02003912 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003913
Christopher Fauleta2097962019-07-15 16:25:33 +02003914 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
3915 struct htx_blk *blk = htx_get_blk(htx, pos);
3916 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003917
Christopher Fauleta2097962019-07-15 16:25:33 +02003918 if (type == HTX_BLK_EOM || type == HTX_BLK_TLR || type == HTX_BLK_EOT)
3919 break;
3920 if (type == HTX_BLK_DATA)
3921 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01003922 }
Christopher Fauleta2097962019-07-15 16:25:33 +02003923 if (htx->extra != ULLONG_MAX)
3924 len += htx->extra;
3925
3926 /* Stores the request path. */
3927 lua_pushstring(L, "length");
3928 lua_pushinteger(L, len);
3929 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003930
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003931 /* Create an empty array of HTTP request headers. */
3932 lua_pushstring(L, "response");
3933 lua_newtable(L);
3934 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003935
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003936 /* Pop a class stream metatable and affect it to the table. */
3937 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3938 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003939
3940 return 1;
3941}
3942
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003943__LJMP static int hlua_applet_http_set_var(lua_State *L)
3944{
3945 struct hlua_appctx *appctx;
3946 struct stream *s;
3947 const char *name;
3948 size_t len;
3949 struct sample smp;
3950
3951 MAY_LJMP(check_args(L, 3, "set_var"));
3952
3953 /* It is useles to retrieve the stream, but this function
3954 * runs only in a stream context.
3955 */
3956 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3957 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3958 s = appctx->htxn.s;
3959
3960 /* Converts the third argument in a sample. */
3961 hlua_lua2smp(L, 3, &smp);
3962
3963 /* Store the sample in a variable. */
3964 smp_set_owner(&smp, s->be, s->sess, s, 0);
3965 vars_set_by_name(name, len, &smp);
3966 return 0;
3967}
3968
3969__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3970{
3971 struct hlua_appctx *appctx;
3972 struct stream *s;
3973 const char *name;
3974 size_t len;
3975 struct sample smp;
3976
3977 MAY_LJMP(check_args(L, 2, "unset_var"));
3978
3979 /* It is useles to retrieve the stream, but this function
3980 * runs only in a stream context.
3981 */
3982 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3983 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3984 s = appctx->htxn.s;
3985
3986 /* Unset the variable. */
3987 smp_set_owner(&smp, s->be, s->sess, s, 0);
3988 vars_unset_by_name(name, len, &smp);
3989 return 0;
3990}
3991
3992__LJMP static int hlua_applet_http_get_var(lua_State *L)
3993{
3994 struct hlua_appctx *appctx;
3995 struct stream *s;
3996 const char *name;
3997 size_t len;
3998 struct sample smp;
3999
4000 MAY_LJMP(check_args(L, 2, "get_var"));
4001
4002 /* It is useles to retrieve the stream, but this function
4003 * runs only in a stream context.
4004 */
4005 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4006 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4007 s = appctx->htxn.s;
4008
4009 smp_set_owner(&smp, s->be, s->sess, s, 0);
4010 if (!vars_get_by_name(name, len, &smp)) {
4011 lua_pushnil(L);
4012 return 1;
4013 }
4014
4015 return hlua_smp2lua(L, &smp);
4016}
4017
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004018__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4019{
4020 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4021 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004022 struct hlua *hlua;
4023
4024 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004025 if (!s->hlua)
4026 return 0;
4027 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004028
4029 MAY_LJMP(check_args(L, 2, "set_priv"));
4030
4031 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004032 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004033
4034 /* Get and store new value. */
4035 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4036 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4037
4038 return 0;
4039}
4040
4041__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4042{
4043 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4044 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004045 struct hlua *hlua;
4046
4047 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004048 if (!s->hlua) {
4049 lua_pushnil(L);
4050 return 1;
4051 }
4052 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004053
4054 /* Push configuration index in the stack. */
4055 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4056
4057 return 1;
4058}
4059
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004060/* If expected data not yet available, it returns a yield. This function
4061 * consumes the data in the buffer. It returns a string containing the
4062 * data. This string can be empty.
4063 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004064__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004065{
4066 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4067 struct stream_interface *si = appctx->appctx->owner;
4068 struct channel *req = si_oc(si);
4069 struct htx *htx;
4070 struct htx_blk *blk;
4071 size_t count;
4072 int stop = 0;
4073
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004074 htx = htx_from_buf(&req->buf);
4075 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004076 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004077
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004078 while (count && !stop && blk) {
4079 enum htx_blk_type type = htx_get_blk_type(blk);
4080 uint32_t sz = htx_get_blksz(blk);
4081 struct ist v;
4082 uint32_t vlen;
4083 char *nl;
4084
Christopher Faulete461e342018-12-18 16:43:35 +01004085 if (type == HTX_BLK_EOM) {
4086 stop = 1;
4087 break;
4088 }
4089
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004090 vlen = sz;
4091 if (vlen > count) {
4092 if (type != HTX_BLK_DATA)
4093 break;
4094 vlen = count;
4095 }
4096
4097 switch (type) {
4098 case HTX_BLK_UNUSED:
4099 break;
4100
4101 case HTX_BLK_DATA:
4102 v = htx_get_blk_value(htx, blk);
4103 v.len = vlen;
4104 nl = istchr(v, '\n');
4105 if (nl != NULL) {
4106 stop = 1;
4107 vlen = nl - v.ptr + 1;
4108 }
4109 luaL_addlstring(&appctx->b, v.ptr, vlen);
4110 break;
4111
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004112 case HTX_BLK_TLR:
4113 case HTX_BLK_EOM:
4114 stop = 1;
4115 break;
4116
4117 default:
4118 break;
4119 }
4120
4121 co_set_data(req, co_data(req) - vlen);
4122 count -= vlen;
4123 if (sz == vlen)
4124 blk = htx_remove_blk(htx, blk);
4125 else {
4126 htx_cut_data_blk(htx, blk, vlen);
4127 break;
4128 }
4129 }
4130
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004131 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004132 if (!stop) {
4133 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004134 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004135 }
4136
4137 /* return the result. */
4138 luaL_pushresult(&appctx->b);
4139 return 1;
4140}
4141
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004142
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004143/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004144__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004145{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004146 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004147
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004148 /* Initialise the string catenation. */
4149 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004150
Christopher Fauleta2097962019-07-15 16:25:33 +02004151 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004152}
4153
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004154/* If expected data not yet available, it returns a yield. This function
4155 * consumes the data in the buffer. It returns a string containing the
4156 * data. This string can be empty.
4157 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004158__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004159{
4160 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4161 struct stream_interface *si = appctx->appctx->owner;
4162 struct channel *req = si_oc(si);
4163 struct htx *htx;
4164 struct htx_blk *blk;
4165 size_t count;
4166 int len;
4167
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004168 htx = htx_from_buf(&req->buf);
4169 len = MAY_LJMP(luaL_checkinteger(L, 2));
4170 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02004171 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004172 while (count && len && blk) {
4173 enum htx_blk_type type = htx_get_blk_type(blk);
4174 uint32_t sz = htx_get_blksz(blk);
4175 struct ist v;
4176 uint32_t vlen;
4177
Christopher Faulete461e342018-12-18 16:43:35 +01004178 if (type == HTX_BLK_EOM) {
4179 len = 0;
4180 break;
4181 }
4182
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004183 vlen = sz;
4184 if (len > 0 && vlen > len)
4185 vlen = len;
4186 if (vlen > count) {
4187 if (type != HTX_BLK_DATA)
4188 break;
4189 vlen = count;
4190 }
4191
4192 switch (type) {
4193 case HTX_BLK_UNUSED:
4194 break;
4195
4196 case HTX_BLK_DATA:
4197 v = htx_get_blk_value(htx, blk);
4198 luaL_addlstring(&appctx->b, v.ptr, vlen);
4199 break;
4200
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004201 case HTX_BLK_TLR:
4202 case HTX_BLK_EOM:
4203 len = 0;
4204 break;
4205
4206 default:
4207 break;
4208 }
4209
4210 co_set_data(req, co_data(req) - vlen);
4211 count -= vlen;
4212 if (len > 0)
4213 len -= vlen;
4214 if (sz == vlen)
4215 blk = htx_remove_blk(htx, blk);
4216 else {
4217 htx_cut_data_blk(htx, blk, vlen);
4218 break;
4219 }
4220 }
4221
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004222 htx_to_buf(htx, &req->buf);
4223
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004224 /* If we are no other data available, yield waiting for new data. */
4225 if (len) {
4226 if (len > 0) {
4227 lua_pushinteger(L, len);
4228 lua_replace(L, 2);
4229 }
4230 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004231 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004232 }
4233
4234 /* return the result. */
4235 luaL_pushresult(&appctx->b);
4236 return 1;
4237}
4238
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004239/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004240__LJMP static int hlua_applet_http_recv(lua_State *L)
4241{
4242 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4243 int len = -1;
4244
4245 /* Check arguments. */
4246 if (lua_gettop(L) > 2)
4247 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4248 if (lua_gettop(L) >= 2) {
4249 len = MAY_LJMP(luaL_checkinteger(L, 2));
4250 lua_pop(L, 1);
4251 }
4252
Christopher Fauleta2097962019-07-15 16:25:33 +02004253 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004254
Christopher Fauleta2097962019-07-15 16:25:33 +02004255 /* Initialise the string catenation. */
4256 luaL_buffinit(L, &appctx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004257
Christopher Fauleta2097962019-07-15 16:25:33 +02004258 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004259}
4260
4261/* Append data in the output side of the buffer. This data is immediately
4262 * sent. The function returns the amount of data written. If the buffer
4263 * cannot contain the data, the function yields. The function returns -1
4264 * if the channel is closed.
4265 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004266__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004267{
4268 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4269 struct stream_interface *si = appctx->appctx->owner;
4270 struct channel *res = si_ic(si);
4271 struct htx *htx = htx_from_buf(&res->buf);
4272 const char *data;
4273 size_t len;
4274 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4275 int max;
4276
Christopher Faulet9060fc02019-07-03 11:39:30 +02004277 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004278 if (!max)
4279 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004280
4281 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4282
4283 /* Get the max amount of data which can write as input in the channel. */
4284 if (max > (len - l))
4285 max = len - l;
4286
4287 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02004288 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004289 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004290
4291 /* update counters. */
4292 l += max;
4293 lua_pop(L, 1);
4294 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004295
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004296 /* If some data is not send, declares the situation to the
4297 * applet, and returns a yield.
4298 */
4299 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004300 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004301 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004302 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004303 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004304 }
4305
Christopher Fauleta2097962019-07-15 16:25:33 +02004306 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004307 return 1;
4308}
4309
4310/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4311 * yield the LUA process, and resume it without checking the
4312 * input arguments.
4313 */
4314__LJMP static int hlua_applet_http_send(lua_State *L)
4315{
4316 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004317
4318 /* We want to send some data. Headers must be sent. */
4319 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4320 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4321 WILL_LJMP(lua_error(L));
4322 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004323
Christopher Fauleta2097962019-07-15 16:25:33 +02004324 /* This interger is used for followinf the amount of data sent. */
4325 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004326
Christopher Fauleta2097962019-07-15 16:25:33 +02004327 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004328}
4329
4330__LJMP static int hlua_applet_http_addheader(lua_State *L)
4331{
4332 const char *name;
4333 int ret;
4334
4335 MAY_LJMP(hlua_checkapplet_http(L, 1));
4336 name = MAY_LJMP(luaL_checkstring(L, 2));
4337 MAY_LJMP(luaL_checkstring(L, 3));
4338
4339 /* Push in the stack the "response" entry. */
4340 ret = lua_getfield(L, 1, "response");
4341 if (ret != LUA_TTABLE) {
4342 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4343 "is expected as an array. %s found", lua_typename(L, ret));
4344 WILL_LJMP(lua_error(L));
4345 }
4346
4347 /* check if the header is already registered if it is not
4348 * the case, register it.
4349 */
4350 ret = lua_getfield(L, -1, name);
4351 if (ret == LUA_TNIL) {
4352
4353 /* Entry not found. */
4354 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4355
4356 /* Insert the new header name in the array in the top of the stack.
4357 * It left the new array in the top of the stack.
4358 */
4359 lua_newtable(L);
4360 lua_pushvalue(L, 2);
4361 lua_pushvalue(L, -2);
4362 lua_settable(L, -4);
4363
4364 } else if (ret != LUA_TTABLE) {
4365
4366 /* corruption error. */
4367 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4368 "is expected as an array. %s found", name, lua_typename(L, ret));
4369 WILL_LJMP(lua_error(L));
4370 }
4371
4372 /* Now the top od thestack is an array of values. We push
4373 * the header value as new entry.
4374 */
4375 lua_pushvalue(L, 3);
4376 ret = lua_rawlen(L, -2);
4377 lua_rawseti(L, -2, ret + 1);
4378 lua_pushboolean(L, 1);
4379 return 1;
4380}
4381
4382__LJMP static int hlua_applet_http_status(lua_State *L)
4383{
4384 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4385 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004386 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004387
4388 if (status < 100 || status > 599) {
4389 lua_pushboolean(L, 0);
4390 return 1;
4391 }
4392
4393 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004394 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004395 lua_pushboolean(L, 1);
4396 return 1;
4397}
4398
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004399
Christopher Fauleta2097962019-07-15 16:25:33 +02004400__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004401{
4402 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4403 struct stream_interface *si = appctx->appctx->owner;
4404 struct channel *res = si_ic(si);
4405 struct htx *htx;
4406 struct htx_sl *sl;
4407 struct h1m h1m;
4408 const char *status, *reason;
4409 const char *name, *value;
4410 size_t nlen, vlen;
4411 unsigned int flags;
4412
4413 /* Send the message at once. */
4414 htx = htx_from_buf(&res->buf);
4415 h1m_init_res(&h1m);
4416
4417 /* Use the same http version than the request. */
4418 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4419 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4420 if (reason == NULL)
4421 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4422 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4423 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4424 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4425 }
4426 else {
4427 flags = HTX_SL_F_IS_RESP;
4428 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4429 }
4430 if (!sl) {
4431 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
4432 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4433 WILL_LJMP(lua_error(L));
4434 }
4435 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4436
4437 /* Get the array associated to the field "response" in the object AppletHTTP. */
4438 lua_pushvalue(L, 0);
4439 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4440 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4441 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4442 WILL_LJMP(lua_error(L));
4443 }
4444
4445 /* Browse the list of headers. */
4446 lua_pushnil(L);
4447 while(lua_next(L, -2) != 0) {
4448 /* We expect a string as -2. */
4449 if (lua_type(L, -2) != LUA_TSTRING) {
4450 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4451 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4452 lua_typename(L, lua_type(L, -2)));
4453 WILL_LJMP(lua_error(L));
4454 }
4455 name = lua_tolstring(L, -2, &nlen);
4456
4457 /* We expect an array as -1. */
4458 if (lua_type(L, -1) != LUA_TTABLE) {
4459 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4460 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4461 name,
4462 lua_typename(L, lua_type(L, -1)));
4463 WILL_LJMP(lua_error(L));
4464 }
4465
4466 /* Browse the table who is on the top of the stack. */
4467 lua_pushnil(L);
4468 while(lua_next(L, -2) != 0) {
4469 int id;
4470
4471 /* We expect a number as -2. */
4472 if (lua_type(L, -2) != LUA_TNUMBER) {
4473 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4474 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4475 name,
4476 lua_typename(L, lua_type(L, -2)));
4477 WILL_LJMP(lua_error(L));
4478 }
4479 id = lua_tointeger(L, -2);
4480
4481 /* We expect a string as -2. */
4482 if (lua_type(L, -1) != LUA_TSTRING) {
4483 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4484 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4485 name, id,
4486 lua_typename(L, lua_type(L, -1)));
4487 WILL_LJMP(lua_error(L));
4488 }
4489 value = lua_tolstring(L, -1, &vlen);
4490
4491 /* Simple Protocol checks. */
4492 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
Christopher Faulet700d9e82020-01-31 12:21:52 +01004493 h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004494 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4495 struct ist v = ist2(value, vlen);
4496 int ret;
4497
4498 ret = h1_parse_cont_len_header(&h1m, &v);
4499 if (ret < 0) {
4500 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
4501 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4502 name);
4503 WILL_LJMP(lua_error(L));
4504 }
4505 else if (ret == 0)
4506 goto next; /* Skip it */
4507 }
4508
4509 /* Add a new header */
4510 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4511 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
4512 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4513 name);
4514 WILL_LJMP(lua_error(L));
4515 }
4516 next:
4517 /* Remove the array from the stack, and get next element with a remaining string. */
4518 lua_pop(L, 1);
4519 }
4520
4521 /* Remove the array from the stack, and get next element with a remaining string. */
4522 lua_pop(L, 1);
4523 }
4524
4525 if (h1m.flags & H1_MF_CHNK)
4526 h1m.flags &= ~H1_MF_CLEN;
4527 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4528 h1m.flags |= H1_MF_XFER_LEN;
4529
4530 /* Uset HTX start-line flags */
4531 if (h1m.flags & H1_MF_XFER_ENC)
4532 flags |= HTX_SL_F_XFER_ENC;
4533 if (h1m.flags & H1_MF_XFER_LEN) {
4534 flags |= HTX_SL_F_XFER_LEN;
4535 if (h1m.flags & H1_MF_CHNK)
4536 flags |= HTX_SL_F_CHNK;
4537 else if (h1m.flags & H1_MF_CLEN)
4538 flags |= HTX_SL_F_CLEN;
4539 if (h1m.body_len == 0)
4540 flags |= HTX_SL_F_BODYLESS;
4541 }
4542 sl->flags |= flags;
4543
4544 /* If we dont have a content-length set, and the HTTP version is 1.1
4545 * and the status code implies the presence of a message body, we must
4546 * announce a transfer encoding chunked. This is required by haproxy
4547 * for the keepalive compliance. If the applet annouces a transfer-encoding
4548 * chunked itslef, don't do anything.
4549 */
4550 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4551 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4552 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4553 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4554 /* Add a new header */
4555 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4556 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4557 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
4558 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4559 WILL_LJMP(lua_error(L));
4560 }
4561 }
4562
4563 /* Finalize headers. */
4564 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4565 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
4566 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4567 WILL_LJMP(lua_error(L));
4568 }
4569
4570 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4571 b_reset(&res->buf);
4572 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4573 WILL_LJMP(lua_error(L));
4574 }
4575
4576 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004577 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004578
4579 /* Headers sent, set the flag. */
4580 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4581 return 0;
4582
4583}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004584/* We will build the status line and the headers of the HTTP response.
4585 * We will try send at once if its not possible, we give back the hand
4586 * waiting for more room.
4587 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004588__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004589{
4590 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4591 struct stream_interface *si = appctx->appctx->owner;
4592 struct channel *res = si_ic(si);
4593
4594 if (co_data(res)) {
4595 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004596 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004597 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004598 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004599}
4600
4601
Christopher Fauleta2097962019-07-15 16:25:33 +02004602__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004603{
Christopher Fauleta2097962019-07-15 16:25:33 +02004604 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004605}
4606
Christopher Fauleta2097962019-07-15 16:25:33 +02004607/*
4608 *
4609 *
4610 * Class HTTP
4611 *
4612 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004613 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004614
4615/* Returns a struct hlua_txn if the stack entry "ud" is
4616 * a class stream, otherwise it throws an error.
4617 */
4618__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004619{
Christopher Fauleta2097962019-07-15 16:25:33 +02004620 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
4621}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004622
Christopher Fauleta2097962019-07-15 16:25:33 +02004623/* This function creates and push in the stack a HTTP object
4624 * according with a current TXN.
4625 */
4626static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4627{
4628 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004629
Christopher Fauleta2097962019-07-15 16:25:33 +02004630 /* Check stack size. */
4631 if (!lua_checkstack(L, 3))
4632 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004633
Christopher Fauleta2097962019-07-15 16:25:33 +02004634 /* Create the object: obj[0] = userdata.
4635 * Note that the base of the Converters object is the
4636 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004637 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004638 lua_newtable(L);
4639 htxn = lua_newuserdata(L, sizeof(*htxn));
4640 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004641
4642 htxn->s = txn->s;
4643 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02004644 htxn->dir = txn->dir;
4645 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004646
4647 /* Pop a class stream metatable and affect it to the table. */
4648 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4649 lua_setmetatable(L, -2);
4650
4651 return 1;
4652}
4653
4654/* This function creates ans returns an array of HTTP headers.
4655 * This function does not fails. It is used as wrapper with the
4656 * 2 following functions.
4657 */
4658__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4659{
Christopher Fauleta2097962019-07-15 16:25:33 +02004660 struct htx *htx;
4661 int32_t pos;
4662
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004663 /* Create the table. */
4664 lua_newtable(L);
4665
4666 if (!htxn->s->txn)
4667 return 1;
4668
Christopher Fauleta2097962019-07-15 16:25:33 +02004669 htx = htxbuf(&msg->chn->buf);
4670 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4671 struct htx_blk *blk = htx_get_blk(htx, pos);
4672 enum htx_blk_type type = htx_get_blk_type(blk);
4673 struct ist n, v;
4674 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004675
Christopher Fauleta2097962019-07-15 16:25:33 +02004676 if (type == HTX_BLK_HDR) {
4677 n = htx_get_blk_name(htx,blk);
4678 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01004679 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004680 else if (type == HTX_BLK_EOH)
4681 break;
4682 else
4683 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004684
Christopher Fauleta2097962019-07-15 16:25:33 +02004685 /* Check for existing entry:
4686 * assume that the table is on the top of the stack, and
4687 * push the key in the stack, the function lua_gettable()
4688 * perform the lookup.
4689 */
4690 lua_pushlstring(L, n.ptr, n.len);
4691 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01004692
Christopher Fauleta2097962019-07-15 16:25:33 +02004693 switch (lua_type(L, -1)) {
4694 case LUA_TNIL:
4695 /* Table not found, create it. */
4696 lua_pop(L, 1); /* remove the nil value. */
4697 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
4698 lua_newtable(L); /* create and push empty table. */
4699 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
4700 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4701 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01004702 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004703
Christopher Fauleta2097962019-07-15 16:25:33 +02004704 case LUA_TTABLE:
4705 /* Entry found: push the value in the table. */
4706 len = lua_rawlen(L, -1);
4707 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
4708 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4709 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4710 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004711
Christopher Fauleta2097962019-07-15 16:25:33 +02004712 default:
4713 /* Other cases are errors. */
4714 hlua_pusherror(L, "internal error during the parsing of headers.");
4715 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004716 }
4717 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004718 return 1;
4719}
4720
4721__LJMP static int hlua_http_req_get_headers(lua_State *L)
4722{
4723 struct hlua_txn *htxn;
4724
4725 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4726 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4727
Christopher Faulet301eff82019-07-26 16:31:34 +02004728 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004729 WILL_LJMP(lua_error(L));
4730
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004731 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4732}
4733
4734__LJMP static int hlua_http_res_get_headers(lua_State *L)
4735{
4736 struct hlua_txn *htxn;
4737
4738 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4739 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4740
Christopher Faulet301eff82019-07-26 16:31:34 +02004741 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004742 WILL_LJMP(lua_error(L));
4743
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004744 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4745}
4746
4747/* This function replace full header, or just a value in
4748 * the request or in the response. It is a wrapper fir the
4749 * 4 following functions.
4750 */
4751__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
Christopher Faulet92d34fe2019-12-17 09:20:34 +01004752 struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004753{
4754 size_t name_len;
4755 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4756 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4757 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02004758 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02004759 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004760
Dragan Dosen26743032019-04-30 15:54:36 +02004761 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004762 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4763
Christopher Fauleta2097962019-07-15 16:25:33 +02004764 htx = htxbuf(&msg->chn->buf);
Christopher Faulet92d34fe2019-12-17 09:20:34 +01004765 http_replace_hdrs(htxn->s, htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02004766 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004767 return 0;
4768}
4769
4770__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4771{
4772 struct hlua_txn *htxn;
4773
4774 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4775 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4776
Christopher Faulet301eff82019-07-26 16:31:34 +02004777 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004778 WILL_LJMP(lua_error(L));
4779
Christopher Faulet92d34fe2019-12-17 09:20:34 +01004780 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004781}
4782
4783__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4784{
4785 struct hlua_txn *htxn;
4786
4787 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4788 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4789
Christopher Faulet301eff82019-07-26 16:31:34 +02004790 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004791 WILL_LJMP(lua_error(L));
4792
Christopher Faulet92d34fe2019-12-17 09:20:34 +01004793 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004794}
4795
4796__LJMP static int hlua_http_req_rep_val(lua_State *L)
4797{
4798 struct hlua_txn *htxn;
4799
4800 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4801 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4802
Christopher Faulet301eff82019-07-26 16:31:34 +02004803 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004804 WILL_LJMP(lua_error(L));
4805
Christopher Faulet92d34fe2019-12-17 09:20:34 +01004806 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004807}
4808
4809__LJMP static int hlua_http_res_rep_val(lua_State *L)
4810{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004811 struct hlua_txn *htxn;
4812
4813 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4814 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4815
Christopher Faulet301eff82019-07-26 16:31:34 +02004816 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004817 WILL_LJMP(lua_error(L));
4818
Christopher Faulet92d34fe2019-12-17 09:20:34 +01004819 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004820}
4821
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004822/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004823 * It is a wrapper for the 2 following functions.
4824 */
4825__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4826{
4827 size_t len;
4828 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02004829 struct htx *htx = htxbuf(&msg->chn->buf);
4830 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004831
Christopher Fauleta2097962019-07-15 16:25:33 +02004832 ctx.blk = NULL;
4833 while (http_find_header(htx, ist2(name, len), &ctx, 1))
4834 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004835 return 0;
4836}
4837
4838__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4839{
4840 struct hlua_txn *htxn;
4841
4842 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4843 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4844
Christopher Faulet301eff82019-07-26 16:31:34 +02004845 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004846 WILL_LJMP(lua_error(L));
4847
Willy Tarreaueee5b512015-04-03 23:46:31 +02004848 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004849}
4850
4851__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4852{
4853 struct hlua_txn *htxn;
4854
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004855 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004856 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4857
Christopher Faulet301eff82019-07-26 16:31:34 +02004858 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004859 WILL_LJMP(lua_error(L));
4860
Willy Tarreaueee5b512015-04-03 23:46:31 +02004861 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004862}
4863
4864/* This function adds an header. It is a wrapper used by
4865 * the 2 following functions.
4866 */
4867__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4868{
4869 size_t name_len;
4870 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4871 size_t value_len;
4872 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02004873 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004874
Christopher Fauleta2097962019-07-15 16:25:33 +02004875 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
4876 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004877 return 0;
4878}
4879
4880__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4881{
4882 struct hlua_txn *htxn;
4883
4884 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4885 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4886
Christopher Faulet301eff82019-07-26 16:31:34 +02004887 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004888 WILL_LJMP(lua_error(L));
4889
Willy Tarreaueee5b512015-04-03 23:46:31 +02004890 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004891}
4892
4893__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4894{
4895 struct hlua_txn *htxn;
4896
4897 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4898 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4899
Christopher Faulet301eff82019-07-26 16:31:34 +02004900 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004901 WILL_LJMP(lua_error(L));
4902
Willy Tarreaueee5b512015-04-03 23:46:31 +02004903 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004904}
4905
4906static int hlua_http_req_set_hdr(lua_State *L)
4907{
4908 struct hlua_txn *htxn;
4909
4910 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4911 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4912
Christopher Faulet301eff82019-07-26 16:31:34 +02004913 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004914 WILL_LJMP(lua_error(L));
4915
Willy Tarreaueee5b512015-04-03 23:46:31 +02004916 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4917 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004918}
4919
4920static int hlua_http_res_set_hdr(lua_State *L)
4921{
4922 struct hlua_txn *htxn;
4923
4924 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4925 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4926
Christopher Faulet301eff82019-07-26 16:31:34 +02004927 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004928 WILL_LJMP(lua_error(L));
4929
Willy Tarreaueee5b512015-04-03 23:46:31 +02004930 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4931 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004932}
4933
4934/* This function set the method. */
4935static int hlua_http_req_set_meth(lua_State *L)
4936{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004937 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004938 size_t name_len;
4939 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004940
Christopher Faulet301eff82019-07-26 16:31:34 +02004941 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004942 WILL_LJMP(lua_error(L));
4943
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004944 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004945 return 1;
4946}
4947
4948/* This function set the method. */
4949static int hlua_http_req_set_path(lua_State *L)
4950{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004951 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004952 size_t name_len;
4953 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004954
Christopher Faulet301eff82019-07-26 16:31:34 +02004955 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004956 WILL_LJMP(lua_error(L));
4957
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004958 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004959 return 1;
4960}
4961
4962/* This function set the query-string. */
4963static int hlua_http_req_set_query(lua_State *L)
4964{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004965 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004966 size_t name_len;
4967 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004968
Christopher Faulet301eff82019-07-26 16:31:34 +02004969 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004970 WILL_LJMP(lua_error(L));
4971
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004972 /* Check length. */
4973 if (name_len > trash.size - 1) {
4974 lua_pushboolean(L, 0);
4975 return 1;
4976 }
4977
4978 /* Add the mark question as prefix. */
4979 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004980 trash.area[trash.data++] = '?';
4981 memcpy(trash.area + trash.data, name, name_len);
4982 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004983
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004984 lua_pushboolean(L,
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004985 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004986 return 1;
4987}
4988
4989/* This function set the uri. */
4990static int hlua_http_req_set_uri(lua_State *L)
4991{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004992 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004993 size_t name_len;
4994 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004995
Christopher Faulet301eff82019-07-26 16:31:34 +02004996 if (htxn->dir != SMP_OPT_DIR_REQ || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02004997 WILL_LJMP(lua_error(L));
4998
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02004999 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005000 return 1;
5001}
5002
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005003/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005004static int hlua_http_res_set_status(lua_State *L)
5005{
5006 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5007 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Faulet96bff762019-12-17 13:46:18 +01005008 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5009 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005010
Christopher Faulet301eff82019-07-26 16:31:34 +02005011 if (htxn->dir != SMP_OPT_DIR_RES || !(htxn->flags & HLUA_TXN_HTTP_RDY))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005012 WILL_LJMP(lua_error(L));
5013
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005014 http_res_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005015 return 0;
5016}
5017
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005018/*
5019 *
5020 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005021 * Class TXN
5022 *
5023 *
5024 */
5025
5026/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005027 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005028 */
5029__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5030{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005031 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005032}
5033
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005034__LJMP static int hlua_set_var(lua_State *L)
5035{
5036 struct hlua_txn *htxn;
5037 const char *name;
5038 size_t len;
5039 struct sample smp;
5040
5041 MAY_LJMP(check_args(L, 3, "set_var"));
5042
5043 /* It is useles to retrieve the stream, but this function
5044 * runs only in a stream context.
5045 */
5046 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5047 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5048
5049 /* Converts the third argument in a sample. */
5050 hlua_lua2smp(L, 3, &smp);
5051
5052 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005053 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005054 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005055 return 0;
5056}
5057
Christopher Faulet85d79c92016-11-09 16:54:56 +01005058__LJMP static int hlua_unset_var(lua_State *L)
5059{
5060 struct hlua_txn *htxn;
5061 const char *name;
5062 size_t len;
5063 struct sample smp;
5064
5065 MAY_LJMP(check_args(L, 2, "unset_var"));
5066
5067 /* It is useles to retrieve the stream, but this function
5068 * runs only in a stream context.
5069 */
5070 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5071 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5072
5073 /* Unset the variable. */
5074 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5075 vars_unset_by_name(name, len, &smp);
5076 return 0;
5077}
5078
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005079__LJMP static int hlua_get_var(lua_State *L)
5080{
5081 struct hlua_txn *htxn;
5082 const char *name;
5083 size_t len;
5084 struct sample smp;
5085
5086 MAY_LJMP(check_args(L, 2, "get_var"));
5087
5088 /* It is useles to retrieve the stream, but this function
5089 * runs only in a stream context.
5090 */
5091 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5092 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5093
Willy Tarreau7560dd42016-03-10 16:28:58 +01005094 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005095 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005096 lua_pushnil(L);
5097 return 1;
5098 }
5099
5100 return hlua_smp2lua(L, &smp);
5101}
5102
Willy Tarreau59551662015-03-10 14:23:13 +01005103__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005104{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005105 struct hlua *hlua;
5106
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005107 MAY_LJMP(check_args(L, 2, "set_priv"));
5108
Willy Tarreau87b09662015-04-03 00:22:06 +02005109 /* It is useles to retrieve the stream, but this function
5110 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005111 */
5112 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005113 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005114
5115 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005116 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005117
5118 /* Get and store new value. */
5119 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5120 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5121
5122 return 0;
5123}
5124
Willy Tarreau59551662015-03-10 14:23:13 +01005125__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005126{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005127 struct hlua *hlua;
5128
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005129 MAY_LJMP(check_args(L, 1, "get_priv"));
5130
Willy Tarreau87b09662015-04-03 00:22:06 +02005131 /* It is useles to retrieve the stream, but this function
5132 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005133 */
5134 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005135 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005136
5137 /* Push configuration index in the stack. */
5138 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5139
5140 return 1;
5141}
5142
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005143/* Create stack entry containing a class TXN. This function
5144 * return 0 if the stack does not contains free slots,
5145 * otherwise it returns 1.
5146 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005147static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005148{
Willy Tarreaude491382015-04-06 11:04:28 +02005149 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005150
5151 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005152 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005153 return 0;
5154
5155 /* NOTE: The allocation never fails. The failure
5156 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005157 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005158 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005159 /* Create the object: obj[0] = userdata. */
5160 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005161 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005162 lua_rawseti(L, -2, 0);
5163
Willy Tarreaude491382015-04-06 11:04:28 +02005164 htxn->s = s;
5165 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005166 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005167 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005168
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005169 /* Create the "f" field that contains a list of fetches. */
5170 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005171 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005172 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005173 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005174
5175 /* Create the "sf" field that contains a list of stringsafe fetches. */
5176 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005177 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005178 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005179 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005180
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005181 /* Create the "c" field that contains a list of converters. */
5182 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005183 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005184 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005185 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005186
5187 /* Create the "sc" field that contains a list of stringsafe converters. */
5188 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005189 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005190 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005191 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005192
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005193 /* Create the "req" field that contains the request channel object. */
5194 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005195 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005196 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005197 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005198
5199 /* Create the "res" field that contains the response channel object. */
5200 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005201 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005202 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005203 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005204
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005205 /* Creates the HTTP object is the current proxy allows http. */
5206 lua_pushstring(L, "http");
5207 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005208 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005209 return 0;
5210 }
5211 else
5212 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005213 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005214
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005215 /* Pop a class sesison metatable and affect it to the userdata. */
5216 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5217 lua_setmetatable(L, -2);
5218
5219 return 1;
5220}
5221
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005222__LJMP static int hlua_txn_deflog(lua_State *L)
5223{
5224 const char *msg;
5225 struct hlua_txn *htxn;
5226
5227 MAY_LJMP(check_args(L, 2, "deflog"));
5228 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5229 msg = MAY_LJMP(luaL_checkstring(L, 2));
5230
5231 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5232 return 0;
5233}
5234
5235__LJMP static int hlua_txn_log(lua_State *L)
5236{
5237 int level;
5238 const char *msg;
5239 struct hlua_txn *htxn;
5240
5241 MAY_LJMP(check_args(L, 3, "log"));
5242 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5243 level = MAY_LJMP(luaL_checkinteger(L, 2));
5244 msg = MAY_LJMP(luaL_checkstring(L, 3));
5245
5246 if (level < 0 || level >= NB_LOG_LEVELS)
5247 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5248
5249 hlua_sendlog(htxn->s->be, level, msg);
5250 return 0;
5251}
5252
5253__LJMP static int hlua_txn_log_debug(lua_State *L)
5254{
5255 const char *msg;
5256 struct hlua_txn *htxn;
5257
5258 MAY_LJMP(check_args(L, 2, "Debug"));
5259 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5260 msg = MAY_LJMP(luaL_checkstring(L, 2));
5261 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5262 return 0;
5263}
5264
5265__LJMP static int hlua_txn_log_info(lua_State *L)
5266{
5267 const char *msg;
5268 struct hlua_txn *htxn;
5269
5270 MAY_LJMP(check_args(L, 2, "Info"));
5271 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5272 msg = MAY_LJMP(luaL_checkstring(L, 2));
5273 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5274 return 0;
5275}
5276
5277__LJMP static int hlua_txn_log_warning(lua_State *L)
5278{
5279 const char *msg;
5280 struct hlua_txn *htxn;
5281
5282 MAY_LJMP(check_args(L, 2, "Warning"));
5283 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5284 msg = MAY_LJMP(luaL_checkstring(L, 2));
5285 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5286 return 0;
5287}
5288
5289__LJMP static int hlua_txn_log_alert(lua_State *L)
5290{
5291 const char *msg;
5292 struct hlua_txn *htxn;
5293
5294 MAY_LJMP(check_args(L, 2, "Alert"));
5295 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5296 msg = MAY_LJMP(luaL_checkstring(L, 2));
5297 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5298 return 0;
5299}
5300
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005301__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5302{
5303 struct hlua_txn *htxn;
5304 int ll;
5305
5306 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5307 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5308 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5309
5310 if (ll < 0 || ll > 7)
5311 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5312
5313 htxn->s->logs.level = ll;
5314 return 0;
5315}
5316
5317__LJMP static int hlua_txn_set_tos(lua_State *L)
5318{
5319 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005320 int tos;
5321
5322 MAY_LJMP(check_args(L, 2, "set_tos"));
5323 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5324 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5325
Willy Tarreau1a18b542018-12-11 16:37:42 +01005326 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005327 return 0;
5328}
5329
5330__LJMP static int hlua_txn_set_mark(lua_State *L)
5331{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005332 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005333 int mark;
5334
5335 MAY_LJMP(check_args(L, 2, "set_mark"));
5336 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5337 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5338
Lukas Tribus579e3e32019-08-11 18:03:45 +02005339 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005340 return 0;
5341}
5342
Patrick Hemmer268a7072018-05-11 12:52:31 -04005343__LJMP static int hlua_txn_set_priority_class(lua_State *L)
5344{
5345 struct hlua_txn *htxn;
5346
5347 MAY_LJMP(check_args(L, 2, "set_priority_class"));
5348 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5349 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
5350 return 0;
5351}
5352
5353__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
5354{
5355 struct hlua_txn *htxn;
5356
5357 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
5358 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5359 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
5360 return 0;
5361}
5362
Christopher Faulet700d9e82020-01-31 12:21:52 +01005363/* Forward the Reply object to the client. This function converts the reply in
5364 * HTX an push it to into the response channel. It is response to foward the
5365 * message and terminate the transaction. It returns 1 on success and 0 on
5366 * error. The Reply must be on top of the stack.
5367 */
5368__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
5369{
5370 struct htx *htx;
5371 struct htx_sl *sl;
5372 struct h1m h1m;
5373 const char *status, *reason, *body;
5374 size_t status_len, reason_len, body_len;
5375 int ret, code, flags;
5376
5377 code = 200;
5378 status = "200";
5379 status_len = 3;
5380 ret = lua_getfield(L, -1, "status");
5381 if (ret == LUA_TNUMBER) {
5382 code = lua_tointeger(L, -1);
5383 status = lua_tolstring(L, -1, &status_len);
5384 }
5385 lua_pop(L, 1);
5386
5387 reason = http_get_reason(code);
5388 reason_len = strlen(reason);
5389 ret = lua_getfield(L, -1, "reason");
5390 if (ret == LUA_TSTRING)
5391 reason = lua_tolstring(L, -1, &reason_len);
5392 lua_pop(L, 1);
5393
5394 body = NULL;
5395 body_len = 0;
5396 ret = lua_getfield(L, -1, "body");
5397 if (ret == LUA_TSTRING)
5398 body = lua_tolstring(L, -1, &body_len);
5399 lua_pop(L, 1);
5400
5401 /* Prepare the response before inserting the headers */
5402 h1m_init_res(&h1m);
5403 htx = htx_from_buf(&s->res.buf);
5404 channel_htx_truncate(&s->res, htx);
5405 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
5406 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5407 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
5408 ist2(status, status_len), ist2(reason, reason_len));
5409 }
5410 else {
5411 flags = HTX_SL_F_IS_RESP;
5412 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
5413 ist2(status, status_len), ist2(reason, reason_len));
5414 }
5415 if (!sl)
5416 goto fail;
5417 sl->info.res.status = code;
5418
5419 /* Push in the stack the "headers" entry. */
5420 ret = lua_getfield(L, -1, "headers");
5421 if (ret != LUA_TTABLE)
5422 goto skip_headers;
5423
5424 lua_pushnil(L);
5425 while (lua_next(L, -2) != 0) {
5426 struct ist name, value;
5427 const char *n, *v;
5428 size_t nlen, vlen;
5429
5430 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
5431 /* Skip element if the key is not a string or if the value is not a table */
5432 goto next_hdr;
5433 }
5434
5435 n = lua_tolstring(L, -2, &nlen);
5436 name = ist2(n, nlen);
5437 if (isteqi(name, ist("content-length"))) {
5438 /* Always skip content-length header. It will be added
5439 * later with the correct len
5440 */
5441 goto next_hdr;
5442 }
5443
5444 /* Loop on header's values */
5445 lua_pushnil(L);
5446 while (lua_next(L, -2)) {
5447 if (!lua_isstring(L, -1)) {
5448 /* Skip the value if it is not a string */
5449 goto next_value;
5450 }
5451
5452 v = lua_tolstring(L, -1, &vlen);
5453 value = ist2(v, vlen);
5454
5455 if (isteqi(name, ist("transfer-encoding")))
5456 h1_parse_xfer_enc_header(&h1m, value);
5457 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
5458 goto fail;
5459
5460 next_value:
5461 lua_pop(L, 1);
5462 }
5463
5464 next_hdr:
5465 lua_pop(L, 1);
5466 }
5467 skip_headers:
5468 lua_pop(L, 1);
5469
5470 /* Update h1m flags: CLEN is set if CHNK is not present */
5471 if (!(h1m.flags & H1_MF_CHNK)) {
5472 const char *clen = ultoa(body_len);
5473
5474 h1m.flags |= H1_MF_CLEN;
5475 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
5476 goto fail;
5477 }
5478 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5479 h1m.flags |= H1_MF_XFER_LEN;
5480
5481 /* Update HTX start-line flags */
5482 if (h1m.flags & H1_MF_XFER_ENC)
5483 flags |= HTX_SL_F_XFER_ENC;
5484 if (h1m.flags & H1_MF_XFER_LEN) {
5485 flags |= HTX_SL_F_XFER_LEN;
5486 if (h1m.flags & H1_MF_CHNK)
5487 flags |= HTX_SL_F_CHNK;
5488 else if (h1m.flags & H1_MF_CLEN)
5489 flags |= HTX_SL_F_CLEN;
5490 if (h1m.body_len == 0)
5491 flags |= HTX_SL_F_BODYLESS;
5492 }
5493 sl->flags |= flags;
5494
5495
5496 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
5497 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))) ||
5498 !htx_add_endof(htx, HTX_BLK_EOM))
5499 goto fail;
5500
5501 /* Now, forward the response and terminate the transaction */
5502 s->txn->status = code;
5503 htx_to_buf(htx, &s->res.buf);
5504 if (!http_forward_proxy_resp(s, 1))
5505 goto fail;
5506
5507 return 1;
5508
5509 fail:
5510 channel_htx_truncate(&s->res, htx);
5511 return 0;
5512}
5513
5514/* Terminate a transaction if called from a lua action. For TCP streams,
5515 * processing is just aborted. Nothing is returned to the client and all
5516 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
5517 * is forwarded to the client before terminating the transaction. On success,
5518 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
5519 * with ACT_RET_ERR code. If this function is not called from a lua action, it
5520 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005521 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005522__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005523{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005524 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01005525 struct stream *s;
5526 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005527
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005528 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005529
Christopher Faulet700d9e82020-01-31 12:21:52 +01005530 /* If the flags NOTERM is set, we cannot terminate the session, so we
5531 * just end the execution of the current lua code. */
5532 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005533 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005534
Christopher Faulet700d9e82020-01-31 12:21:52 +01005535 s = htxn->s;
5536 if (!(htxn->flags & HLUA_TXN_HTTP_RDY)) {
5537 struct channel *req = &s->req;
5538 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005539
Christopher Faulet700d9e82020-01-31 12:21:52 +01005540 channel_auto_read(req);
5541 channel_abort(req);
5542 channel_auto_close(req);
5543 channel_erase(req);
5544
5545 res->wex = tick_add_ifset(now_ms, res->wto);
5546 channel_auto_read(res);
5547 channel_auto_close(res);
5548 channel_shutr_now(res);
5549
5550 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
5551 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005552 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005553
Christopher Faulet700d9e82020-01-31 12:21:52 +01005554 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
5555 /* No reply or invalid reply */
5556 s->txn->status = 0;
5557 http_reply_and_close(s, 0, NULL);
5558 }
5559 else {
5560 /* Remove extra args to have the reply on top of the stack */
5561 if (lua_gettop(L) > 2)
5562 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005563
Christopher Faulet700d9e82020-01-31 12:21:52 +01005564 if (!hlua_txn_forward_reply(L, s)) {
5565 if (!(s->flags & SF_ERR_MASK))
5566 s->flags |= SF_ERR_PRXCOND;
5567 lua_pushinteger(L, ACT_RET_ERR);
5568 WILL_LJMP(hlua_done(L));
5569 return 0; /* Never reached */
5570 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02005571 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005572
Christopher Faulet700d9e82020-01-31 12:21:52 +01005573 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
5574 if (htxn->dir == SMP_OPT_DIR_REQ) {
5575 /* let's log the request time */
5576 s->logs.tv_request = now;
5577 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
5578 _HA_ATOMIC_ADD(&s->sess->fe->fe_counters.intercepted_req, 1);
5579 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005580
Christopher Faulet700d9e82020-01-31 12:21:52 +01005581 done:
5582 if (!(s->flags & SF_ERR_MASK))
5583 s->flags |= SF_ERR_LOCAL;
5584 if (!(s->flags & SF_FINST_MASK))
5585 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005586
Christopher Faulet7716cdf2020-01-29 11:53:30 +01005587 lua_pushinteger(L, ACT_RET_DONE);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005588 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005589 return 0;
5590}
5591
Christopher Faulet700d9e82020-01-31 12:21:52 +01005592/*
5593 *
5594 *
5595 * Class REPLY
5596 *
5597 *
5598 */
5599
5600/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
5601 * free slots, the function fails and returns 0;
5602 */
5603static int hlua_txn_reply_new(lua_State *L)
5604{
5605 struct hlua_txn *htxn;
5606 const char *reason, *body = NULL;
5607 int ret, status;
5608
5609 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5610 if (!(htxn->flags & HLUA_TXN_HTTP_RDY)) {
5611 hlua_pusherror(L, "txn object is not an HTTP transaction.");
5612 WILL_LJMP(lua_error(L));
5613 }
5614
5615 /* Default value */
5616 status = 200;
5617 reason = http_get_reason(status);
5618
5619 if (lua_istable(L, 2)) {
5620 /* load status and reason from the table argument at index 2 */
5621 ret = lua_getfield(L, 2, "status");
5622 if (ret == LUA_TNIL)
5623 goto reason;
5624 else if (ret != LUA_TNUMBER) {
5625 /* invalid status: ignore the reason */
5626 goto body;
5627 }
5628 status = lua_tointeger(L, -1);
5629
5630 reason:
5631 lua_pop(L, 1); /* restore the stack: remove status */
5632 ret = lua_getfield(L, 2, "reason");
5633 if (ret == LUA_TSTRING)
5634 reason = lua_tostring(L, -1);
5635
5636 body:
5637 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
5638 ret = lua_getfield(L, 2, "body");
5639 if (ret == LUA_TSTRING)
5640 body = lua_tostring(L, -1);
5641 lua_pop(L, 1); /* restore the stack: remove body */
5642 }
5643
5644 /* Create the Reply table */
5645 lua_newtable(L);
5646
5647 /* Add status element */
5648 lua_pushstring(L, "status");
5649 lua_pushinteger(L, status);
5650 lua_settable(L, -3);
5651
5652 /* Add reason element */
5653 reason = http_get_reason(status);
5654 lua_pushstring(L, "reason");
5655 lua_pushstring(L, reason);
5656 lua_settable(L, -3);
5657
5658 /* Add body element, nil if undefined */
5659 lua_pushstring(L, "body");
5660 if (body)
5661 lua_pushstring(L, body);
5662 else
5663 lua_pushnil(L);
5664 lua_settable(L, -3);
5665
5666 /* Add headers element */
5667 lua_pushstring(L, "headers");
5668 lua_newtable(L);
5669
5670 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
5671 if (lua_istable(L, 2)) {
5672 /* load headers from the table argument at index 2. If it is a table, copy it. */
5673 ret = lua_getfield(L, 2, "headers");
5674 if (ret == LUA_TTABLE) {
5675 /* stack: [ ... <headers:table>, <table> ] */
5676 lua_pushnil(L);
5677 while (lua_next(L, -2) != 0) {
5678 /* stack: [ ... <headers:table>, <table>, k, v] */
5679 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
5680 /* invalid value type, skip it */
5681 lua_pop(L, 1);
5682 continue;
5683 }
5684
5685
5686 /* Duplicate the key and swap it with the value. */
5687 lua_pushvalue(L, -2);
5688 lua_insert(L, -2);
5689 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
5690
5691 lua_newtable(L);
5692 lua_insert(L, -2);
5693 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
5694
5695 if (lua_isstring(L, -1)) {
5696 /* push the value in the inner table */
5697 lua_rawseti(L, -2, 1);
5698 }
5699 else { /* table */
5700 lua_pushnil(L);
5701 while (lua_next(L, -2) != 0) {
5702 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
5703 if (!lua_isstring(L, -1)) {
5704 /* invalid value type, skip it*/
5705 lua_pop(L, 1);
5706 continue;
5707 }
5708 /* push the value in the inner table */
5709 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
5710 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
5711 }
5712 lua_pop(L, 1);
5713 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
5714 }
5715
5716 /* push (k,v) on the stack in the headers table:
5717 * stack: [ ... <headers:table>, <table>, k, k, v ]
5718 */
5719 lua_settable(L, -5);
5720 /* stack: [ ... <headers:table>, <table>, k ] */
5721 }
5722 }
5723 lua_pop(L, 1);
5724 }
5725 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
5726 lua_settable(L, -3);
5727 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
5728
5729 /* Pop a class sesison metatable and affect it to the userdata. */
5730 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
5731 lua_setmetatable(L, -2);
5732 return 1;
5733}
5734
5735/* Set the reply status code, and optionally the reason. If no reason is
5736 * provided, the default one corresponding to the status code is used.
5737 */
5738__LJMP static int hlua_txn_reply_set_status(lua_State *L)
5739{
5740 int status = MAY_LJMP(luaL_checkinteger(L, 2));
5741 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5742
5743 /* First argument (self) must be a table */
5744 luaL_checktype(L, 1, LUA_TTABLE);
5745
5746 if (status < 100 || status > 599) {
5747 lua_pushboolean(L, 0);
5748 return 1;
5749 }
5750 if (!reason)
5751 reason = http_get_reason(status);
5752
5753 lua_pushinteger(L, status);
5754 lua_setfield(L, 1, "status");
5755
5756 lua_pushstring(L, reason);
5757 lua_setfield(L, 1, "reason");
5758
5759 lua_pushboolean(L, 1);
5760 return 1;
5761}
5762
5763/* Add a header into the reply object. Each header name is associated to an
5764 * array of values in the "headers" table. If the header name is not found, a
5765 * new entry is created.
5766 */
5767__LJMP static int hlua_txn_reply_add_header(lua_State *L)
5768{
5769 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
5770 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
5771 int ret;
5772
5773 /* First argument (self) must be a table */
5774 luaL_checktype(L, 1, LUA_TTABLE);
5775
5776 /* Push in the stack the "headers" entry. */
5777 ret = lua_getfield(L, 1, "headers");
5778 if (ret != LUA_TTABLE) {
5779 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
5780 WILL_LJMP(lua_error(L));
5781 }
5782
5783 /* check if the header is already registered. If not, register it. */
5784 ret = lua_getfield(L, -1, name);
5785 if (ret == LUA_TNIL) {
5786 /* Entry not found. */
5787 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
5788
5789 /* Insert the new header name in the array in the top of the stack.
5790 * It left the new array in the top of the stack.
5791 */
5792 lua_newtable(L);
5793 lua_pushstring(L, name);
5794 lua_pushvalue(L, -2);
5795 lua_settable(L, -4);
5796 }
5797 else if (ret != LUA_TTABLE) {
5798 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
5799 WILL_LJMP(lua_error(L));
5800 }
5801
5802 /* Now the top od thestack is an array of values. We push
5803 * the header value as new entry.
5804 */
5805 lua_pushstring(L, value);
5806 ret = lua_rawlen(L, -2);
5807 lua_rawseti(L, -2, ret + 1);
5808
5809 lua_pushboolean(L, 1);
5810 return 1;
5811}
5812
5813/* Remove all occurrences of a given header name. */
5814__LJMP static int hlua_txn_reply_del_header(lua_State *L)
5815{
5816 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
5817 int ret;
5818
5819 /* First argument (self) must be a table */
5820 luaL_checktype(L, 1, LUA_TTABLE);
5821
5822 /* Push in the stack the "headers" entry. */
5823 ret = lua_getfield(L, 1, "headers");
5824 if (ret != LUA_TTABLE) {
5825 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
5826 WILL_LJMP(lua_error(L));
5827 }
5828
5829 lua_pushstring(L, name);
5830 lua_pushnil(L);
5831 lua_settable(L, -3);
5832
5833 lua_pushboolean(L, 1);
5834 return 1;
5835}
5836
5837/* Set the reply's body. Overwrite any existing entry. */
5838__LJMP static int hlua_txn_reply_set_body(lua_State *L)
5839{
5840 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
5841
5842 /* First argument (self) must be a table */
5843 luaL_checktype(L, 1, LUA_TTABLE);
5844
5845 lua_pushstring(L, payload);
5846 lua_setfield(L, 1, "body");
5847
5848 lua_pushboolean(L, 1);
5849 return 1;
5850}
5851
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005852__LJMP static int hlua_log(lua_State *L)
5853{
5854 int level;
5855 const char *msg;
5856
5857 MAY_LJMP(check_args(L, 2, "log"));
5858 level = MAY_LJMP(luaL_checkinteger(L, 1));
5859 msg = MAY_LJMP(luaL_checkstring(L, 2));
5860
5861 if (level < 0 || level >= NB_LOG_LEVELS)
5862 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5863
5864 hlua_sendlog(NULL, level, msg);
5865 return 0;
5866}
5867
5868__LJMP static int hlua_log_debug(lua_State *L)
5869{
5870 const char *msg;
5871
5872 MAY_LJMP(check_args(L, 1, "debug"));
5873 msg = MAY_LJMP(luaL_checkstring(L, 1));
5874 hlua_sendlog(NULL, LOG_DEBUG, msg);
5875 return 0;
5876}
5877
5878__LJMP static int hlua_log_info(lua_State *L)
5879{
5880 const char *msg;
5881
5882 MAY_LJMP(check_args(L, 1, "info"));
5883 msg = MAY_LJMP(luaL_checkstring(L, 1));
5884 hlua_sendlog(NULL, LOG_INFO, msg);
5885 return 0;
5886}
5887
5888__LJMP static int hlua_log_warning(lua_State *L)
5889{
5890 const char *msg;
5891
5892 MAY_LJMP(check_args(L, 1, "warning"));
5893 msg = MAY_LJMP(luaL_checkstring(L, 1));
5894 hlua_sendlog(NULL, LOG_WARNING, msg);
5895 return 0;
5896}
5897
5898__LJMP static int hlua_log_alert(lua_State *L)
5899{
5900 const char *msg;
5901
5902 MAY_LJMP(check_args(L, 1, "alert"));
5903 msg = MAY_LJMP(luaL_checkstring(L, 1));
5904 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005905 return 0;
5906}
5907
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005908__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005909{
5910 int wakeup_ms = lua_tointeger(L, -1);
5911 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02005912 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005913 return 0;
5914}
5915
5916__LJMP static int hlua_sleep(lua_State *L)
5917{
5918 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005919 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005920
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005921 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005922
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005923 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005924 wakeup_ms = tick_add(now_ms, delay);
5925 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005926
Willy Tarreau9635e032018-10-16 17:52:55 +02005927 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005928 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005929}
5930
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005931__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005932{
5933 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005934 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005935
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005936 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005937
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005938 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005939 wakeup_ms = tick_add(now_ms, delay);
5940 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005941
Willy Tarreau9635e032018-10-16 17:52:55 +02005942 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005943 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005944}
5945
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005946/* This functionis an LUA binding. it permits to give back
5947 * the hand at the HAProxy scheduler. It is used when the
5948 * LUA processing consumes a lot of time.
5949 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005950__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005951{
5952 return 0;
5953}
5954
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005955__LJMP static int hlua_yield(lua_State *L)
5956{
Willy Tarreau9635e032018-10-16 17:52:55 +02005957 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005958 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005959}
5960
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005961/* This function change the nice of the currently executed
5962 * task. It is used set low or high priority at the current
5963 * task.
5964 */
Willy Tarreau59551662015-03-10 14:23:13 +01005965__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005966{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005967 struct hlua *hlua;
5968 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005969
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005970 MAY_LJMP(check_args(L, 1, "set_nice"));
5971 hlua = hlua_gethlua(L);
5972 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005973
5974 /* If he task is not set, I'm in a start mode. */
5975 if (!hlua || !hlua->task)
5976 return 0;
5977
5978 if (nice < -1024)
5979 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005980 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005981 nice = 1024;
5982
5983 hlua->task->nice = nice;
5984 return 0;
5985}
5986
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005987/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005988 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5989 * return an E_AGAIN signal, the emmiter of this signal must set a
5990 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005991 *
5992 * Task wrapper are longjmp safe because the only one Lua code
5993 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005994 */
Willy Tarreau60409db2019-08-21 14:14:50 +02005995struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005996{
Olivier Houchard9f6af332018-05-25 14:04:04 +02005997 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005998 enum hlua_exec status;
5999
Christopher Faulet5bc99722018-04-25 10:34:45 +02006000 if (task->thread_mask == MAX_THREADS_MASK)
6001 task_set_affinity(task, tid_bit);
6002
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006003 /* If it is the first call to the task, we must initialize the
6004 * execution timeouts.
6005 */
6006 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006007 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006008
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006009 /* Execute the Lua code. */
6010 status = hlua_ctx_resume(hlua, 1);
6011
6012 switch (status) {
6013 /* finished or yield */
6014 case HLUA_E_OK:
6015 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006016 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006017 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006018 break;
6019
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006020 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006021 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006022 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006023 break;
6024
6025 /* finished with error. */
6026 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006027 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006028 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006029 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006030 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006031 break;
6032
6033 case HLUA_E_ERR:
6034 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006035 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006036 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006037 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006038 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006039 break;
6040 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006041 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006042}
6043
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006044/* This function is an LUA binding that register LUA function to be
6045 * executed after the HAProxy configuration parsing and before the
6046 * HAProxy scheduler starts. This function expect only one LUA
6047 * argument that is a function. This function returns nothing, but
6048 * throws if an error is encountered.
6049 */
6050__LJMP static int hlua_register_init(lua_State *L)
6051{
6052 struct hlua_init_function *init;
6053 int ref;
6054
6055 MAY_LJMP(check_args(L, 1, "register_init"));
6056
6057 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6058
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006059 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006060 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006061 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006062
6063 init->function_ref = ref;
6064 LIST_ADDQ(&hlua_init_functions, &init->l);
6065 return 0;
6066}
6067
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006068/* This functio is an LUA binding. It permits to register a task
6069 * executed in parallel of the main HAroxy activity. The task is
6070 * created and it is set in the HAProxy scheduler. It can be called
6071 * from the "init" section, "post init" or during the runtime.
6072 *
6073 * Lua prototype:
6074 *
6075 * <none> core.register_task(<function>)
6076 */
6077static int hlua_register_task(lua_State *L)
6078{
6079 struct hlua *hlua;
6080 struct task *task;
6081 int ref;
6082
6083 MAY_LJMP(check_args(L, 1, "register_task"));
6084
6085 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6086
Willy Tarreaubafbe012017-11-24 17:34:44 +01006087 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006088 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006089 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006090
Emeric Brunc60def82017-09-27 14:59:38 +02006091 task = task_new(MAX_THREADS_MASK);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006092 if (!task)
6093 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6094
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006095 task->context = hlua;
6096 task->process = hlua_process_task;
6097
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006098 if (!hlua_ctx_init(hlua, task, 1))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006099 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006100
6101 /* Restore the function in the stack. */
6102 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6103 hlua->nargs = 0;
6104
6105 /* Schedule task. */
6106 task_schedule(task, now_ms);
6107
6108 return 0;
6109}
6110
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006111/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6112 * doesn't allow "yield" functions because the HAProxy engine cannot
6113 * resume converters.
6114 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006115static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006116{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006117 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006118 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006119 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006120
Willy Tarreaube508f12016-03-10 11:47:01 +01006121 if (!stream)
6122 return 0;
6123
Willy Tarreau87b09662015-04-03 00:22:06 +02006124 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006125 * Lua context can be not initialized. This behavior
6126 * permits to save performances because a systematic
6127 * Lua initialization cause 5% performances loss.
6128 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006129 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006130 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006131 if (!stream->hlua) {
6132 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6133 return 0;
6134 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006135 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006136 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6137 return 0;
6138 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006139 }
6140
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006141 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006142 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006143
6144 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006145 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6146 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6147 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006148 else
6149 error = "critical error";
6150 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006151 return 0;
6152 }
6153
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006154 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006155 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006156 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006157 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006158 return 0;
6159 }
6160
6161 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006162 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006163
6164 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006165 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006166 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006167 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006168 return 0;
6169 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006170 hlua_smp2lua(stream->hlua->T, smp);
6171 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006172
6173 /* push keywords in the stack. */
6174 if (arg_p) {
6175 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006176 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006177 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006178 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006179 return 0;
6180 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006181 hlua_arg2lua(stream->hlua->T, arg_p);
6182 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006183 }
6184 }
6185
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006186 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006187 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006188
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006189 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006190 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006191 }
6192
6193 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006194 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006195 /* finished. */
6196 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006197 /* If the stack is empty, the function fails. */
6198 if (lua_gettop(stream->hlua->T) <= 0)
6199 return 0;
6200
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006201 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006202 hlua_lua2smp(stream->hlua->T, -1, smp);
6203 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006204 return 1;
6205
6206 /* yield. */
6207 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006208 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006209 return 0;
6210
6211 /* finished with error. */
6212 case HLUA_E_ERRMSG:
6213 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006214 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006215 fcn->name, lua_tostring(stream->hlua->T, -1));
6216 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006217 return 0;
6218
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006219 case HLUA_E_ETMOUT:
6220 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6221 return 0;
6222
6223 case HLUA_E_NOMEM:
6224 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6225 return 0;
6226
6227 case HLUA_E_YIELD:
6228 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6229 return 0;
6230
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006231 case HLUA_E_ERR:
6232 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006233 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006234
6235 default:
6236 return 0;
6237 }
6238}
6239
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006240/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6241 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006242 * resume sample-fetches. This function will be called by the sample
6243 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006244 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006245static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6246 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006247{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006248 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006249 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006250 const char *error;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006251 unsigned int hflags = HLUA_TXN_NOTERM;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006252
Willy Tarreaube508f12016-03-10 11:47:01 +01006253 if (!stream)
6254 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006255
Willy Tarreau87b09662015-04-03 00:22:06 +02006256 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006257 * Lua context can be not initialized. This behavior
6258 * permits to save performances because a systematic
6259 * Lua initialization cause 5% performances loss.
6260 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006261 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006262 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006263 if (!stream->hlua) {
6264 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6265 return 0;
6266 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006267 if (!hlua_ctx_init(stream->hlua, stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006268 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6269 return 0;
6270 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006271 }
6272
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006273 if (stream->be->mode == PR_MODE_HTTP) {
6274 if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ)
6275 hflags |= ((stream->txn->req.msg_state < HTTP_MSG_BODY) ? 0 : HLUA_TXN_HTTP_RDY);
6276 else
6277 hflags |= ((stream->txn->rsp.msg_state < HTTP_MSG_BODY) ? 0 : HLUA_TXN_HTTP_RDY);
6278 }
6279
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006280 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006281 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006282
6283 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006284 if (!SET_SAFE_LJMP(stream->hlua->T)) {
6285 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6286 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006287 else
6288 error = "critical error";
6289 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006290 return 0;
6291 }
6292
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006293 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006294 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006295 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006296 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006297 return 0;
6298 }
6299
6300 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006301 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006302
6303 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006304 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006305 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006306 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006307 return 0;
6308 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006309 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006310
6311 /* push keywords in the stack. */
6312 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6313 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006314 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006315 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006316 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006317 return 0;
6318 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006319 hlua_arg2lua(stream->hlua->T, arg_p);
6320 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006321 }
6322
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006323 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006324 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006325
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006326 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006327 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006328 }
6329
6330 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006331 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006332 /* finished. */
6333 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006334 /* If the stack is empty, the function fails. */
6335 if (lua_gettop(stream->hlua->T) <= 0)
6336 return 0;
6337
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006338 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006339 hlua_lua2smp(stream->hlua->T, -1, smp);
6340 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006341
6342 /* Set the end of execution flag. */
6343 smp->flags &= ~SMP_F_MAY_CHANGE;
6344 return 1;
6345
6346 /* yield. */
6347 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006348 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006349 return 0;
6350
6351 /* finished with error. */
6352 case HLUA_E_ERRMSG:
6353 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006354 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006355 fcn->name, lua_tostring(stream->hlua->T, -1));
6356 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006357 return 0;
6358
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006359 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006360 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6361 return 0;
6362
6363 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006364 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6365 return 0;
6366
6367 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006368 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6369 return 0;
6370
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006371 case HLUA_E_ERR:
6372 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006373 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006374
6375 default:
6376 return 0;
6377 }
6378}
6379
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006380/* This function is an LUA binding used for registering
6381 * "sample-conv" functions. It expects a converter name used
6382 * in the haproxy configuration file, and an LUA function.
6383 */
6384__LJMP static int hlua_register_converters(lua_State *L)
6385{
6386 struct sample_conv_kw_list *sck;
6387 const char *name;
6388 int ref;
6389 int len;
6390 struct hlua_function *fcn;
6391
6392 MAY_LJMP(check_args(L, 2, "register_converters"));
6393
6394 /* First argument : converter name. */
6395 name = MAY_LJMP(luaL_checkstring(L, 1));
6396
6397 /* Second argument : lua function. */
6398 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6399
6400 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006401 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006402 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006403 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006404 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006405 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006406 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006407
6408 /* Fill fcn. */
6409 fcn->name = strdup(name);
6410 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006411 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006412 fcn->function_ref = ref;
6413
6414 /* List head */
6415 sck->list.n = sck->list.p = NULL;
6416
6417 /* converter keyword. */
6418 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006419 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006420 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006421 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006422
6423 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6424 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006425 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 +01006426 sck->kw[0].val_args = NULL;
6427 sck->kw[0].in_type = SMP_T_STR;
6428 sck->kw[0].out_type = SMP_T_STR;
6429 sck->kw[0].private = fcn;
6430
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006431 /* Register this new converter */
6432 sample_register_convs(sck);
6433
6434 return 0;
6435}
6436
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006437/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006438 * "sample-fetch" functions. It expects a converter name used
6439 * in the haproxy configuration file, and an LUA function.
6440 */
6441__LJMP static int hlua_register_fetches(lua_State *L)
6442{
6443 const char *name;
6444 int ref;
6445 int len;
6446 struct sample_fetch_kw_list *sfk;
6447 struct hlua_function *fcn;
6448
6449 MAY_LJMP(check_args(L, 2, "register_fetches"));
6450
6451 /* First argument : sample-fetch name. */
6452 name = MAY_LJMP(luaL_checkstring(L, 1));
6453
6454 /* Second argument : lua function. */
6455 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6456
6457 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006458 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006459 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006460 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006461 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006462 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006463 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006464
6465 /* Fill fcn. */
6466 fcn->name = strdup(name);
6467 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006468 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006469 fcn->function_ref = ref;
6470
6471 /* List head */
6472 sfk->list.n = sfk->list.p = NULL;
6473
6474 /* sample-fetch keyword. */
6475 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006476 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006477 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006478 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006479
6480 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6481 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006482 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 +01006483 sfk->kw[0].val_args = NULL;
6484 sfk->kw[0].out_type = SMP_T_STR;
6485 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6486 sfk->kw[0].val = 0;
6487 sfk->kw[0].private = fcn;
6488
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006489 /* Register this new fetch. */
6490 sample_register_fetches(sfk);
6491
6492 return 0;
6493}
6494
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006495/* This function is a lua binding to set the wake_time from an action. It is
6496 * only used if the action return ACT_RET_YIELD.
6497 */
6498__LJMP static int hlua_action_wake_time(lua_State *L)
6499{
6500 struct hlua *hlua = hlua_gethlua(L);
6501 unsigned int delay;
6502 unsigned int wakeup_ms;
6503
6504 MAY_LJMP(check_args(L, 1, "wake_time"));
6505
6506 delay = MAY_LJMP(luaL_checkinteger(L, 1));
6507 wakeup_ms = tick_add(now_ms, delay);
6508 hlua->wake_time = wakeup_ms;
6509 return 0;
6510}
6511
6512
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006513/* This function is a wrapper to execute each LUA function declared as an action
6514 * wrapper during the initialisation period. This function may return any
6515 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
6516 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
6517 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006518 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006519static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006520 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006521{
6522 char **arg;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006523 unsigned int hflags = 0;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006524 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006525 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006526
6527 switch (rule->from) {
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006528 case ACT_F_TCP_REQ_CNT: ; dir = SMP_OPT_DIR_REQ; break;
6529 case ACT_F_TCP_RES_CNT: ; dir = SMP_OPT_DIR_RES; break;
6530 case ACT_F_HTTP_REQ: hflags = HLUA_TXN_HTTP_RDY ; dir = SMP_OPT_DIR_REQ; break;
6531 case ACT_F_HTTP_RES: hflags = HLUA_TXN_HTTP_RDY ; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006532 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006533 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006534 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006535 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006536
Willy Tarreau87b09662015-04-03 00:22:06 +02006537 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006538 * Lua context can be not initialized. This behavior
6539 * permits to save performances because a systematic
6540 * Lua initialization cause 5% performances loss.
6541 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006542 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006543 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006544 if (!s->hlua) {
6545 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6546 rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006547 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006548 }
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006549 if (!hlua_ctx_init(s->hlua, s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006550 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6551 rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006552 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006553 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006554 }
6555
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006556 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006557 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006558
6559 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006560 if (!SET_SAFE_LJMP(s->hlua->T)) {
6561 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6562 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006563 else
6564 error = "critical error";
6565 SEND_ERR(px, "Lua function '%s': %s.\n",
6566 rule->arg.hlua_rule->fcn.name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006567 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006568 }
6569
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006570 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006571 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006572 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006573 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006574 RESET_SAFE_LJMP(s->hlua->T);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006575 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006576 }
6577
6578 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006579 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006580
Willy Tarreau87b09662015-04-03 00:22:06 +02006581 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006582 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006583 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006584 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006585 RESET_SAFE_LJMP(s->hlua->T);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006586 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006587 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006588 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006589
6590 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006591 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006592 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006593 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006594 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006595 RESET_SAFE_LJMP(s->hlua->T);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006596 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006597 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006598 lua_pushstring(s->hlua->T, *arg);
6599 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006600 }
6601
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006602 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006603 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006604
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006605 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006606 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006607 }
6608
6609 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01006610 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006611 /* finished. */
6612 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006613 /* Catch the return value */
6614 if (lua_gettop(s->hlua->T) > 0)
6615 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006616
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006617 /* Set timeout in the required channel. */
6618 if (act_ret == ACT_RET_YIELD && s->hlua->wake_time != TICK_ETERNITY) {
6619 if (dir == SMP_OPT_DIR_REQ)
6620 s->req.analyse_exp = s->hlua->wake_time;
6621 else
6622 s->res.analyse_exp = s->hlua->wake_time;
6623 }
6624 goto end;
6625
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006626 /* yield. */
6627 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006628 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006629 if (s->hlua->wake_time != TICK_ETERNITY) {
Christopher Faulet81921b12019-08-14 23:19:45 +02006630 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006631 s->req.analyse_exp = s->hlua->wake_time;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006632 else
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006633 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006634 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006635 /* Some actions can be wake up when a "write" event
6636 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006637 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006638 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02006639 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006640 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006641 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006642 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006643 act_ret = ACT_RET_YIELD;
6644 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006645
6646 /* finished with error. */
6647 case HLUA_E_ERRMSG:
6648 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006649 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006650 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6651 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006652 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006653
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006654 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006655 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006656 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006657
6658 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006659 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006660 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006661
6662 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006663 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6664 rule->arg.hlua_rule->fcn.name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006665 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006666
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006667 case HLUA_E_ERR:
6668 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006669 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006670 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006671
6672 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006673 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006674 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006675
6676 end:
6677 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006678}
6679
Olivier Houchard9f6af332018-05-25 14:04:04 +02006680struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006681{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006682 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006683
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006684 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006685 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006686 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006687}
6688
6689static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6690{
6691 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006692 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006693 struct task *task;
6694 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006695 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006696
Willy Tarreaubafbe012017-11-24 17:34:44 +01006697 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006698 if (!hlua) {
6699 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6700 ctx->rule->arg.hlua_rule->fcn.name);
6701 return 0;
6702 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006703 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006704 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006705 ctx->ctx.hlua_apptcp.flags = 0;
6706
6707 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006708 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006709 if (!task) {
6710 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6711 ctx->rule->arg.hlua_rule->fcn.name);
6712 return 0;
6713 }
6714 task->nice = 0;
6715 task->context = ctx;
6716 task->process = hlua_applet_wakeup;
6717 ctx->ctx.hlua_apptcp.task = task;
6718
6719 /* In the execution wrappers linked with a stream, the
6720 * Lua context can be not initialized. This behavior
6721 * permits to save performances because a systematic
6722 * Lua initialization cause 5% performances loss.
6723 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006724 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006725 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6726 ctx->rule->arg.hlua_rule->fcn.name);
6727 return 0;
6728 }
6729
6730 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006731 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006732
6733 /* The following Lua calls can fail. */
6734 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006735 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6736 error = lua_tostring(hlua->T, -1);
6737 else
6738 error = "critical error";
6739 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6740 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006741 return 0;
6742 }
6743
6744 /* Check stack available size. */
6745 if (!lua_checkstack(hlua->T, 1)) {
6746 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6747 ctx->rule->arg.hlua_rule->fcn.name);
6748 RESET_SAFE_LJMP(hlua->T);
6749 return 0;
6750 }
6751
6752 /* Restore the function in the stack. */
6753 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6754
6755 /* Create and and push object stream in the stack. */
6756 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6757 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6758 ctx->rule->arg.hlua_rule->fcn.name);
6759 RESET_SAFE_LJMP(hlua->T);
6760 return 0;
6761 }
6762 hlua->nargs = 1;
6763
6764 /* push keywords in the stack. */
6765 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6766 if (!lua_checkstack(hlua->T, 1)) {
6767 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6768 ctx->rule->arg.hlua_rule->fcn.name);
6769 RESET_SAFE_LJMP(hlua->T);
6770 return 0;
6771 }
6772 lua_pushstring(hlua->T, *arg);
6773 hlua->nargs++;
6774 }
6775
6776 RESET_SAFE_LJMP(hlua->T);
6777
6778 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01006779 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01006780 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006781
6782 return 1;
6783}
6784
Willy Tarreau60409db2019-08-21 14:14:50 +02006785void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006786{
6787 struct stream_interface *si = ctx->owner;
6788 struct stream *strm = si_strm(si);
6789 struct channel *res = si_ic(si);
6790 struct act_rule *rule = ctx->rule;
6791 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006792 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006793
6794 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02006795 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
6796 /* eat the whole request */
6797 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006798 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02006799 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006800
6801 /* If the stream is disconnect or closed, ldo nothing. */
6802 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6803 return;
6804
6805 /* Execute the function. */
6806 switch (hlua_ctx_resume(hlua, 1)) {
6807 /* finished. */
6808 case HLUA_E_OK:
6809 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6810
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006811 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006812 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006813 res->flags |= CF_READ_NULL;
6814 si_shutr(si);
6815 return;
6816
6817 /* yield. */
6818 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006819 if (hlua->wake_time != TICK_ETERNITY)
6820 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006821 return;
6822
6823 /* finished with error. */
6824 case HLUA_E_ERRMSG:
6825 /* Display log. */
6826 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6827 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6828 lua_pop(hlua->T, 1);
6829 goto error;
6830
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006831 case HLUA_E_ETMOUT:
6832 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
6833 rule->arg.hlua_rule->fcn.name);
6834 goto error;
6835
6836 case HLUA_E_NOMEM:
6837 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
6838 rule->arg.hlua_rule->fcn.name);
6839 goto error;
6840
6841 case HLUA_E_YIELD: /* unexpected */
6842 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
6843 rule->arg.hlua_rule->fcn.name);
6844 goto error;
6845
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006846 case HLUA_E_ERR:
6847 /* Display log. */
6848 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6849 rule->arg.hlua_rule->fcn.name);
6850 goto error;
6851
6852 default:
6853 goto error;
6854 }
6855
6856error:
6857
6858 /* For all other cases, just close the stream. */
6859 si_shutw(si);
6860 si_shutr(si);
6861 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6862}
6863
6864static void hlua_applet_tcp_release(struct appctx *ctx)
6865{
Olivier Houchard3f795f72019-04-17 22:51:06 +02006866 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006867 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006868 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006869 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006870}
6871
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006872/* The function returns 1 if the initialisation is complete, 0 if
6873 * an errors occurs and -1 if more data are required for initializing
6874 * the applet.
6875 */
6876static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6877{
6878 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006879 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006880 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006881 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006882 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006883 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006884
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006885 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01006886 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006887 if (!hlua) {
6888 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6889 ctx->rule->arg.hlua_rule->fcn.name);
6890 return 0;
6891 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006892 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006893 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006894 ctx->ctx.hlua_apphttp.left_bytes = -1;
6895 ctx->ctx.hlua_apphttp.flags = 0;
6896
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006897 if (txn->req.flags & HTTP_MSGF_VER_11)
6898 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6899
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006900 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006901 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006902 if (!task) {
6903 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6904 ctx->rule->arg.hlua_rule->fcn.name);
6905 return 0;
6906 }
6907 task->nice = 0;
6908 task->context = ctx;
6909 task->process = hlua_applet_wakeup;
6910 ctx->ctx.hlua_apphttp.task = task;
6911
6912 /* In the execution wrappers linked with a stream, the
6913 * Lua context can be not initialized. This behavior
6914 * permits to save performances because a systematic
6915 * Lua initialization cause 5% performances loss.
6916 */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01006917 if (!hlua_ctx_init(hlua, task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006918 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6919 ctx->rule->arg.hlua_rule->fcn.name);
6920 return 0;
6921 }
6922
6923 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006924 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006925
6926 /* The following Lua calls can fail. */
6927 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006928 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6929 error = lua_tostring(hlua->T, -1);
6930 else
6931 error = "critical error";
6932 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6933 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006934 return 0;
6935 }
6936
6937 /* Check stack available size. */
6938 if (!lua_checkstack(hlua->T, 1)) {
6939 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6940 ctx->rule->arg.hlua_rule->fcn.name);
6941 RESET_SAFE_LJMP(hlua->T);
6942 return 0;
6943 }
6944
6945 /* Restore the function in the stack. */
6946 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6947
6948 /* Create and and push object stream in the stack. */
6949 if (!hlua_applet_http_new(hlua->T, ctx)) {
6950 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6951 ctx->rule->arg.hlua_rule->fcn.name);
6952 RESET_SAFE_LJMP(hlua->T);
6953 return 0;
6954 }
6955 hlua->nargs = 1;
6956
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006957 /* push keywords in the stack. */
6958 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6959 if (!lua_checkstack(hlua->T, 1)) {
6960 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6961 ctx->rule->arg.hlua_rule->fcn.name);
6962 RESET_SAFE_LJMP(hlua->T);
6963 return 0;
6964 }
6965 lua_pushstring(hlua->T, *arg);
6966 hlua->nargs++;
6967 }
6968
6969 RESET_SAFE_LJMP(hlua->T);
6970
6971 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01006972 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006973
6974 return 1;
6975}
6976
Willy Tarreau60409db2019-08-21 14:14:50 +02006977void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01006978{
6979 struct stream_interface *si = ctx->owner;
6980 struct stream *strm = si_strm(si);
6981 struct channel *req = si_oc(si);
6982 struct channel *res = si_ic(si);
6983 struct act_rule *rule = ctx->rule;
6984 struct proxy *px = strm->be;
6985 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
6986 struct htx *req_htx, *res_htx;
6987
6988 res_htx = htx_from_buf(&res->buf);
6989
6990 /* If the stream is disconnect or closed, ldo nothing. */
6991 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6992 goto out;
6993
6994 /* Check if the input buffer is avalaible. */
6995 if (!b_size(&res->buf)) {
6996 si_rx_room_blk(si);
6997 goto out;
6998 }
6999 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007000 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007001 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7002
7003 /* Set the currently running flag. */
7004 if (!HLUA_IS_RUNNING(hlua) &&
7005 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7006 struct htx_blk *blk;
7007 size_t count = co_data(req);
7008
7009 if (!count) {
7010 si_cant_get(si);
7011 goto out;
7012 }
7013
7014 /* We need to flush the request header. This left the body for
7015 * the Lua.
7016 */
7017 req_htx = htx_from_buf(&req->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02007018 blk = htx_get_first_blk(req_htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007019 while (count && blk) {
7020 enum htx_blk_type type = htx_get_blk_type(blk);
7021 uint32_t sz = htx_get_blksz(blk);
7022
7023 if (sz > count) {
7024 si_cant_get(si);
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007025 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007026 goto out;
7027 }
7028
7029 count -= sz;
7030 co_set_data(req, co_data(req) - sz);
7031 blk = htx_remove_blk(req_htx, blk);
7032
7033 if (type == HTX_BLK_EOH)
7034 break;
7035 }
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007036 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007037 }
7038
7039 /* Executes The applet if it is not done. */
7040 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7041
7042 /* Execute the function. */
7043 switch (hlua_ctx_resume(hlua, 1)) {
7044 /* finished. */
7045 case HLUA_E_OK:
7046 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7047 break;
7048
7049 /* yield. */
7050 case HLUA_E_AGAIN:
7051 if (hlua->wake_time != TICK_ETERNITY)
7052 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007053 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007054
7055 /* finished with error. */
7056 case HLUA_E_ERRMSG:
7057 /* Display log. */
7058 SEND_ERR(px, "Lua applet http '%s': %s.\n",
7059 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
7060 lua_pop(hlua->T, 1);
7061 goto error;
7062
7063 case HLUA_E_ETMOUT:
7064 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
7065 rule->arg.hlua_rule->fcn.name);
7066 goto error;
7067
7068 case HLUA_E_NOMEM:
7069 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
7070 rule->arg.hlua_rule->fcn.name);
7071 goto error;
7072
7073 case HLUA_E_YIELD: /* unexpected */
7074 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
7075 rule->arg.hlua_rule->fcn.name);
7076 goto error;
7077
7078 case HLUA_E_ERR:
7079 /* Display log. */
7080 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
7081 rule->arg.hlua_rule->fcn.name);
7082 goto error;
7083
7084 default:
7085 goto error;
7086 }
7087 }
7088
7089 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007090 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7091 goto done;
7092
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007093 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7094 goto error;
7095
Christopher Faulet54b5e212019-06-04 10:08:28 +02007096 /* Don't add TLR because mux-h1 will take care of it */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007097 if (!htx_add_endof(res_htx, HTX_BLK_EOM)) {
7098 si_rx_room_blk(si);
7099 goto out;
7100 }
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007101 channel_add_input(res, 1);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007102 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7103 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007104 }
7105
7106 done:
7107 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007108 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007109 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007110 si_shutr(si);
7111 }
7112
7113 /* eat the whole request */
7114 if (co_data(req)) {
7115 req_htx = htx_from_buf(&req->buf);
7116 co_htx_skip(req, req_htx, co_data(req));
7117 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007118 }
7119 }
7120
7121 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007122 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007123 return;
7124
7125 error:
7126
7127 /* If we are in HTTP mode, and we are not send any
7128 * data, return a 500 server error in best effort:
7129 * if there is no room available in the buffer,
7130 * just close the connection.
7131 */
7132 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02007133 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007134
7135 channel_erase(res);
7136 res->buf.data = b_data(err);
7137 memcpy(res->buf.area, b_head(err), b_data(err));
7138 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007139 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007140 }
7141 if (!(strm->flags & SF_ERR_MASK))
7142 strm->flags |= SF_ERR_RESOURCE;
7143 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7144 goto done;
7145}
7146
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007147static void hlua_applet_http_release(struct appctx *ctx)
7148{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007149 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007150 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007151 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007152 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007153}
7154
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007155/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
7156 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007157 *
7158 * This function can fail with an abort() due to an Lua critical error.
7159 * We are in the configuration parsing process of HAProxy, this abort() is
7160 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007161 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007162static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7163 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007164{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007165 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007166 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007167
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007168 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007169 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007170 if (!rule->arg.hlua_rule) {
7171 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007172 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007173 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007174
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007175 /* Memory for arguments. */
7176 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
7177 if (!rule->arg.hlua_rule->args) {
7178 memprintf(err, "out of memory error");
7179 return ACT_RET_PRS_ERR;
7180 }
7181
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007182 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007183 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007184
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007185 /* Expect some arguments */
7186 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007187 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007188 memprintf(err, "expect %d arguments", fcn->nargs);
7189 return ACT_RET_PRS_ERR;
7190 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007191 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007192 if (!rule->arg.hlua_rule->args[i]) {
7193 memprintf(err, "out of memory error");
7194 return ACT_RET_PRS_ERR;
7195 }
7196 (*cur_arg)++;
7197 }
7198 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007199
Thierry FOURNIER42148732015-09-02 17:17:33 +02007200 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007201 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007202 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007203}
7204
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007205static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7206 struct act_rule *rule, char **err)
7207{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007208 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007209
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007210 /* HTTP applets are forbidden in tcp-request rules.
7211 * HTTP applet request requires everything initilized by
7212 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
7213 * The applet will be immediately initilized, but its before
7214 * the call of this analyzer.
7215 */
7216 if (rule->from != ACT_F_HTTP_REQ) {
7217 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7218 return ACT_RET_PRS_ERR;
7219 }
7220
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007221 /* Memory for the rule. */
7222 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7223 if (!rule->arg.hlua_rule) {
7224 memprintf(err, "out of memory error");
7225 return ACT_RET_PRS_ERR;
7226 }
7227
7228 /* Reference the Lua function and store the reference. */
7229 rule->arg.hlua_rule->fcn = *fcn;
7230
7231 /* TODO: later accept arguments. */
7232 rule->arg.hlua_rule->args = NULL;
7233
7234 /* Add applet pointer in the rule. */
7235 rule->applet.obj_type = OBJ_TYPE_APPLET;
7236 rule->applet.name = fcn->name;
7237 rule->applet.init = hlua_applet_http_init;
7238 rule->applet.fct = hlua_applet_http_fct;
7239 rule->applet.release = hlua_applet_http_release;
7240 rule->applet.timeout = hlua_timeout_applet;
7241
7242 return ACT_RET_PRS_OK;
7243}
7244
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007245/* This function is an LUA binding used for registering
7246 * "sample-conv" functions. It expects a converter name used
7247 * in the haproxy configuration file, and an LUA function.
7248 */
7249__LJMP static int hlua_register_action(lua_State *L)
7250{
7251 struct action_kw_list *akl;
7252 const char *name;
7253 int ref;
7254 int len;
7255 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007256 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007257
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007258 /* Initialise the number of expected arguments at 0. */
7259 nargs = 0;
7260
7261 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7262 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007263
7264 /* First argument : converter name. */
7265 name = MAY_LJMP(luaL_checkstring(L, 1));
7266
7267 /* Second argument : environment. */
7268 if (lua_type(L, 2) != LUA_TTABLE)
7269 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7270
7271 /* Third argument : lua function. */
7272 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7273
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007274 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007275 if (lua_gettop(L) >= 4)
7276 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7277
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007278 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007279 lua_pushnil(L);
7280 while (lua_next(L, 2) != 0) {
7281 if (lua_type(L, -1) != LUA_TSTRING)
7282 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7283
7284 /* Check required environment. Only accepted "http" or "tcp". */
7285 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007286 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007287 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007288 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007289 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007290 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007291 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007292
7293 /* Fill fcn. */
7294 fcn->name = strdup(name);
7295 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007296 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007297 fcn->function_ref = ref;
7298
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007299 /* Set the expected number od arguments. */
7300 fcn->nargs = nargs;
7301
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007302 /* List head */
7303 akl->list.n = akl->list.p = NULL;
7304
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007305 /* action keyword. */
7306 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007307 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007308 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007309 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007310
7311 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7312
7313 akl->kw[0].match_pfx = 0;
7314 akl->kw[0].private = fcn;
7315 akl->kw[0].parse = action_register_lua;
7316
7317 /* select the action registering point. */
7318 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7319 tcp_req_cont_keywords_register(akl);
7320 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7321 tcp_res_cont_keywords_register(akl);
7322 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7323 http_req_keywords_register(akl);
7324 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7325 http_res_keywords_register(akl);
7326 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007327 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007328 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7329 "are expected.", lua_tostring(L, -1)));
7330
7331 /* pop the environment string. */
7332 lua_pop(L, 1);
7333 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007334 return ACT_RET_PRS_OK;
7335}
7336
7337static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7338 struct act_rule *rule, char **err)
7339{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007340 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007341
Christopher Faulet280f85b2019-07-15 15:02:04 +02007342 if (px->mode == PR_MODE_HTTP) {
7343 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01007344 return ACT_RET_PRS_ERR;
7345 }
7346
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007347 /* Memory for the rule. */
7348 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7349 if (!rule->arg.hlua_rule) {
7350 memprintf(err, "out of memory error");
7351 return ACT_RET_PRS_ERR;
7352 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007353
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007354 /* Reference the Lua function and store the reference. */
7355 rule->arg.hlua_rule->fcn = *fcn;
7356
7357 /* TODO: later accept arguments. */
7358 rule->arg.hlua_rule->args = NULL;
7359
7360 /* Add applet pointer in the rule. */
7361 rule->applet.obj_type = OBJ_TYPE_APPLET;
7362 rule->applet.name = fcn->name;
7363 rule->applet.init = hlua_applet_tcp_init;
7364 rule->applet.fct = hlua_applet_tcp_fct;
7365 rule->applet.release = hlua_applet_tcp_release;
7366 rule->applet.timeout = hlua_timeout_applet;
7367
7368 return 0;
7369}
7370
7371/* This function is an LUA binding used for registering
7372 * "sample-conv" functions. It expects a converter name used
7373 * in the haproxy configuration file, and an LUA function.
7374 */
7375__LJMP static int hlua_register_service(lua_State *L)
7376{
7377 struct action_kw_list *akl;
7378 const char *name;
7379 const char *env;
7380 int ref;
7381 int len;
7382 struct hlua_function *fcn;
7383
7384 MAY_LJMP(check_args(L, 3, "register_service"));
7385
7386 /* First argument : converter name. */
7387 name = MAY_LJMP(luaL_checkstring(L, 1));
7388
7389 /* Second argument : environment. */
7390 env = MAY_LJMP(luaL_checkstring(L, 2));
7391
7392 /* Third argument : lua function. */
7393 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7394
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007395 /* Allocate and fill the sample fetch keyword struct. */
7396 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7397 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007398 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007399 fcn = calloc(1, sizeof(*fcn));
7400 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007401 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007402
7403 /* Fill fcn. */
7404 len = strlen("<lua.>") + strlen(name) + 1;
7405 fcn->name = calloc(1, len);
7406 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007407 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007408 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7409 fcn->function_ref = ref;
7410
7411 /* List head */
7412 akl->list.n = akl->list.p = NULL;
7413
7414 /* converter keyword. */
7415 len = strlen("lua.") + strlen(name) + 1;
7416 akl->kw[0].kw = calloc(1, len);
7417 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007418 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007419
7420 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7421
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007422 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007423 if (strcmp(env, "tcp") == 0)
7424 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007425 else if (strcmp(env, "http") == 0)
7426 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007427 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007428 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007429 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007430
7431 akl->kw[0].match_pfx = 0;
7432 akl->kw[0].private = fcn;
7433
7434 /* End of array. */
7435 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7436
7437 /* Register this new converter */
7438 service_keywords_register(akl);
7439
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007440 return 0;
7441}
7442
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007443/* This function initialises Lua cli handler. It copies the
7444 * arguments in the Lua stack and create channel IO objects.
7445 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007446static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007447{
7448 struct hlua *hlua;
7449 struct hlua_function *fcn;
7450 int i;
7451 const char *error;
7452
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007453 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007454 appctx->ctx.hlua_cli.fcn = private;
7455
Willy Tarreaubafbe012017-11-24 17:34:44 +01007456 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007457 if (!hlua) {
7458 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007459 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007460 }
7461 HLUA_INIT(hlua);
7462 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007463
7464 /* Create task used by signal to wakeup applets.
7465 * We use the same wakeup fonction than the Lua applet_tcp and
7466 * applet_http. It is absolutely compatible.
7467 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007468 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007469 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007470 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007471 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007472 }
7473 appctx->ctx.hlua_cli.task->nice = 0;
7474 appctx->ctx.hlua_cli.task->context = appctx;
7475 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7476
7477 /* Initialises the Lua context */
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01007478 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007479 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007480 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007481 }
7482
7483 /* The following Lua calls can fail. */
7484 if (!SET_SAFE_LJMP(hlua->T)) {
7485 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7486 error = lua_tostring(hlua->T, -1);
7487 else
7488 error = "critical error";
7489 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7490 goto error;
7491 }
7492
7493 /* Check stack available size. */
7494 if (!lua_checkstack(hlua->T, 2)) {
7495 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7496 goto error;
7497 }
7498
7499 /* Restore the function in the stack. */
7500 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7501
7502 /* Once the arguments parsed, the CLI is like an AppletTCP,
7503 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007504 */
7505 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7506 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7507 goto error;
7508 }
7509 hlua->nargs = 1;
7510
7511 /* push keywords in the stack. */
7512 for (i = 0; *args[i]; i++) {
7513 /* Check stack available size. */
7514 if (!lua_checkstack(hlua->T, 1)) {
7515 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7516 goto error;
7517 }
7518 lua_pushstring(hlua->T, args[i]);
7519 hlua->nargs++;
7520 }
7521
7522 /* We must initialize the execution timeouts. */
7523 hlua->max_time = hlua_timeout_session;
7524
7525 /* At this point the execution is safe. */
7526 RESET_SAFE_LJMP(hlua->T);
7527
7528 /* It's ok */
7529 return 0;
7530
7531 /* It's not ok. */
7532error:
7533 RESET_SAFE_LJMP(hlua->T);
7534 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007535 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007536 return 1;
7537}
7538
7539static int hlua_cli_io_handler_fct(struct appctx *appctx)
7540{
7541 struct hlua *hlua;
7542 struct stream_interface *si;
7543 struct hlua_function *fcn;
7544
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007545 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007546 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007547 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007548
7549 /* If the stream is disconnect or closed, ldo nothing. */
7550 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7551 return 1;
7552
7553 /* Execute the function. */
7554 switch (hlua_ctx_resume(hlua, 1)) {
7555
7556 /* finished. */
7557 case HLUA_E_OK:
7558 return 1;
7559
7560 /* yield. */
7561 case HLUA_E_AGAIN:
7562 /* We want write. */
7563 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01007564 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007565 /* Set the timeout. */
7566 if (hlua->wake_time != TICK_ETERNITY)
7567 task_schedule(hlua->task, hlua->wake_time);
7568 return 0;
7569
7570 /* finished with error. */
7571 case HLUA_E_ERRMSG:
7572 /* Display log. */
7573 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7574 fcn->name, lua_tostring(hlua->T, -1));
7575 lua_pop(hlua->T, 1);
7576 return 1;
7577
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007578 case HLUA_E_ETMOUT:
7579 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
7580 fcn->name);
7581 return 1;
7582
7583 case HLUA_E_NOMEM:
7584 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
7585 fcn->name);
7586 return 1;
7587
7588 case HLUA_E_YIELD: /* unexpected */
7589 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
7590 fcn->name);
7591 return 1;
7592
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007593 case HLUA_E_ERR:
7594 /* Display log. */
7595 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7596 fcn->name);
7597 return 1;
7598
7599 default:
7600 return 1;
7601 }
7602
7603 return 1;
7604}
7605
7606static void hlua_cli_io_release_fct(struct appctx *appctx)
7607{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007608 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007609 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007610}
7611
7612/* This function is an LUA binding used for registering
7613 * new keywords in the cli. It expects a list of keywords
7614 * which are the "path". It is limited to 5 keywords. A
7615 * description of the command, a function to be executed
7616 * for the parsing and a function for io handlers.
7617 */
7618__LJMP static int hlua_register_cli(lua_State *L)
7619{
7620 struct cli_kw_list *cli_kws;
7621 const char *message;
7622 int ref_io;
7623 int len;
7624 struct hlua_function *fcn;
7625 int index;
7626 int i;
7627
7628 MAY_LJMP(check_args(L, 3, "register_cli"));
7629
7630 /* First argument : an array of maximum 5 keywords. */
7631 if (!lua_istable(L, 1))
7632 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7633
7634 /* Second argument : string with contextual message. */
7635 message = MAY_LJMP(luaL_checkstring(L, 2));
7636
7637 /* Third and fourth argument : lua function. */
7638 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7639
7640 /* Allocate and fill the sample fetch keyword struct. */
7641 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7642 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007643 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007644 fcn = calloc(1, sizeof(*fcn));
7645 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007646 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007647
7648 /* Fill path. */
7649 index = 0;
7650 lua_pushnil(L);
7651 while(lua_next(L, 1) != 0) {
7652 if (index >= 5)
7653 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7654 if (lua_type(L, -1) != LUA_TSTRING)
7655 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7656 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7657 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007658 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007659 index++;
7660 lua_pop(L, 1);
7661 }
7662
7663 /* Copy help message. */
7664 cli_kws->kw[0].usage = strdup(message);
7665 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007666 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007667
7668 /* Fill fcn io handler. */
7669 len = strlen("<lua.cli>") + 1;
7670 for (i = 0; i < index; i++)
7671 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7672 fcn->name = calloc(1, len);
7673 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007674 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007675 strncat((char *)fcn->name, "<lua.cli", len);
7676 for (i = 0; i < index; i++) {
7677 strncat((char *)fcn->name, ".", len);
7678 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7679 }
7680 strncat((char *)fcn->name, ">", len);
7681 fcn->function_ref = ref_io;
7682
7683 /* Fill last entries. */
7684 cli_kws->kw[0].private = fcn;
7685 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7686 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7687 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7688
7689 /* Register this new converter */
7690 cli_register_kw(cli_kws);
7691
7692 return 0;
7693}
7694
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007695static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7696 struct proxy *defpx, const char *file, int line,
7697 char **err, unsigned int *timeout)
7698{
7699 const char *error;
7700
7701 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +02007702 if (error == PARSE_TIME_OVER) {
7703 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
7704 args[1], args[0]);
7705 return -1;
7706 }
7707 else if (error == PARSE_TIME_UNDER) {
7708 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
7709 args[1], args[0]);
7710 return -1;
7711 }
7712 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007713 memprintf(err, "%s: invalid timeout", args[0]);
7714 return -1;
7715 }
7716 return 0;
7717}
7718
7719static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7720 struct proxy *defpx, const char *file, int line,
7721 char **err)
7722{
7723 return hlua_read_timeout(args, section_type, curpx, defpx,
7724 file, line, err, &hlua_timeout_session);
7725}
7726
7727static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7728 struct proxy *defpx, const char *file, int line,
7729 char **err)
7730{
7731 return hlua_read_timeout(args, section_type, curpx, defpx,
7732 file, line, err, &hlua_timeout_task);
7733}
7734
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007735static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7736 struct proxy *defpx, const char *file, int line,
7737 char **err)
7738{
7739 return hlua_read_timeout(args, section_type, curpx, defpx,
7740 file, line, err, &hlua_timeout_applet);
7741}
7742
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007743static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7744 struct proxy *defpx, const char *file, int line,
7745 char **err)
7746{
7747 char *error;
7748
7749 hlua_nb_instruction = strtoll(args[1], &error, 10);
7750 if (*error != '\0') {
7751 memprintf(err, "%s: invalid number", args[0]);
7752 return -1;
7753 }
7754 return 0;
7755}
7756
Willy Tarreau32f61e22015-03-18 17:54:59 +01007757static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7758 struct proxy *defpx, const char *file, int line,
7759 char **err)
7760{
7761 char *error;
7762
7763 if (*(args[1]) == 0) {
7764 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7765 return -1;
7766 }
7767 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7768 if (*error != '\0') {
7769 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7770 return -1;
7771 }
7772 return 0;
7773}
7774
7775
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007776/* This function is called by the main configuration key "lua-load". It loads and
7777 * execute an lua file during the parsing of the HAProxy configuration file. It is
7778 * the main lua entry point.
7779 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007780 * This function runs with the HAProxy keywords API. It returns -1 if an error
7781 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007782 *
7783 * In some error case, LUA set an error message in top of the stack. This function
7784 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007785 *
7786 * This function can fail with an abort() due to an Lua critical error.
7787 * We are in the configuration parsing process of HAProxy, this abort() is
7788 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007789 */
7790static int hlua_load(char **args, int section_type, struct proxy *curpx,
7791 struct proxy *defpx, const char *file, int line,
7792 char **err)
7793{
7794 int error;
7795
7796 /* Just load and compile the file. */
7797 error = luaL_loadfile(gL.T, args[1]);
7798 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007799 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007800 lua_pop(gL.T, 1);
7801 return -1;
7802 }
7803
7804 /* If no syntax error where detected, execute the code. */
7805 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7806 switch (error) {
7807 case LUA_OK:
7808 break;
7809 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007810 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007811 lua_pop(gL.T, 1);
7812 return -1;
7813 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007814 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007815 return -1;
7816 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007817 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007818 lua_pop(gL.T, 1);
7819 return -1;
7820 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007821 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007822 lua_pop(gL.T, 1);
7823 return -1;
7824 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007825 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007826 lua_pop(gL.T, 1);
7827 return -1;
7828 }
7829
7830 return 0;
7831}
7832
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01007833/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
7834 * in the given <ctx>.
7835 */
7836static int hlua_prepend_path(struct hlua ctx, char *type, char *path)
7837{
7838 lua_getglobal(ctx.T, "package"); /* push package variable */
7839 lua_pushstring(ctx.T, path); /* push given path */
7840 lua_pushstring(ctx.T, ";"); /* push semicolon */
7841 lua_getfield(ctx.T, -3, type); /* push old path */
7842 lua_concat(ctx.T, 3); /* concatenate to new path */
7843 lua_setfield(ctx.T, -2, type); /* store new path */
7844 lua_pop(ctx.T, 1); /* pop package variable */
7845
7846 return 0;
7847}
7848
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01007849static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
7850 struct proxy *defpx, const char *file, int line,
7851 char **err)
7852{
7853 char *path;
7854 char *type = "path";
7855 if (too_many_args(2, args, err, NULL)) {
7856 return -1;
7857 }
7858
7859 if (!(*args[1])) {
7860 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
7861 return -1;
7862 }
7863 path = args[1];
7864
7865 if (*args[2]) {
7866 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
7867 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
7868 return -1;
7869 }
7870 type = args[2];
7871 }
7872
7873 return hlua_prepend_path(gL, type, path);
7874}
7875
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007876/* configuration keywords declaration */
7877static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01007878 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007879 { CFG_GLOBAL, "lua-load", hlua_load },
7880 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7881 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007882 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007883 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007884 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007885 { 0, NULL, NULL },
7886}};
7887
Willy Tarreau0108d902018-11-25 19:14:37 +01007888INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
7889
Christopher Fauletafd8f102018-11-08 11:34:21 +01007890
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007891/* This function can fail with an abort() due to an Lua critical error.
7892 * We are in the initialisation process of HAProxy, this abort() is
7893 * tolerated.
7894 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007895int hlua_post_init()
7896{
7897 struct hlua_init_function *init;
7898 const char *msg;
7899 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007900 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007901
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007902 /* Call post initialisation function in safe environement. */
7903 if (!SET_SAFE_LJMP(gL.T)) {
7904 if (lua_type(gL.T, -1) == LUA_TSTRING)
7905 error = lua_tostring(gL.T, -1);
7906 else
7907 error = "critical error";
7908 fprintf(stderr, "Lua post-init: %s.\n", error);
7909 exit(1);
7910 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02007911
7912#if USE_OPENSSL
7913 /* Initialize SSL server. */
7914 if (socket_ssl.xprt->prepare_srv) {
7915 int saved_used_backed = global.ssl_used_backend;
7916 // don't affect maxconn automatic computation
7917 socket_ssl.xprt->prepare_srv(&socket_ssl);
7918 global.ssl_used_backend = saved_used_backed;
7919 }
7920#endif
7921
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007922 hlua_fcn_post_init(gL.T);
7923 RESET_SAFE_LJMP(gL.T);
7924
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007925 list_for_each_entry(init, &hlua_init_functions, l) {
7926 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7927 ret = hlua_ctx_resume(&gL, 0);
7928 switch (ret) {
7929 case HLUA_E_OK:
7930 lua_pop(gL.T, -1);
7931 return 1;
7932 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007933 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007934 return 0;
7935 case HLUA_E_ERRMSG:
7936 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007937 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007938 return 0;
7939 case HLUA_E_ERR:
7940 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007941 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007942 return 0;
7943 }
7944 }
7945 return 1;
7946}
7947
Willy Tarreau32f61e22015-03-18 17:54:59 +01007948/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7949 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7950 * is the previously allocated size or the kind of object in case of a new
7951 * allocation. <nsize> is the requested new size.
7952 */
7953static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7954{
7955 struct hlua_mem_allocator *zone = ud;
7956
7957 if (nsize == 0) {
7958 /* it's a free */
7959 if (ptr)
7960 zone->allocated -= osize;
7961 free(ptr);
7962 return NULL;
7963 }
7964
7965 if (!ptr) {
7966 /* it's a new allocation */
7967 if (zone->limit && zone->allocated + nsize > zone->limit)
7968 return NULL;
7969
7970 ptr = malloc(nsize);
7971 if (ptr)
7972 zone->allocated += nsize;
7973 return ptr;
7974 }
7975
7976 /* it's a realloc */
7977 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7978 return NULL;
7979
7980 ptr = realloc(ptr, nsize);
7981 if (ptr)
7982 zone->allocated += nsize - osize;
7983 return ptr;
7984}
7985
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007986/* Ithis function can fail with an abort() due to an Lua critical error.
7987 * We are in the initialisation process of HAProxy, this abort() is
7988 * tolerated.
7989 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007990void hlua_init(void)
7991{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007992 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007993 int idx;
7994 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007995 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007996 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007997 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007998#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007999 struct srv_kw *kw;
8000 int tmp_error;
8001 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008002 char *args[] = { /* SSL client configuration. */
8003 "ssl",
8004 "verify",
8005 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008006 NULL
8007 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008008#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008009
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008010 /* Init main lua stack. */
8011 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01008012 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01008013 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02008014 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008015 hlua_sethlua(&gL);
8016 gL.Tref = LUA_REFNIL;
8017 gL.task = NULL;
8018
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008019 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008020 * the Lua function can fail with an abort. We are in the initialisation
8021 * process of HAProxy, this abort() is tolerated.
8022 */
8023
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008024 /* Initialise lua. */
8025 luaL_openlibs(gL.T);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01008026#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
8027#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
8028#ifdef HLUA_PREPEND_PATH
8029 hlua_prepend_path(gL, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
8030#endif
8031#ifdef HLUA_PREPEND_CPATH
8032 hlua_prepend_path(gL, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
8033#endif
8034#undef HLUA_PREPEND_PATH_TOSTRING
8035#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008036
Thierry Fournier75933d42016-01-21 09:30:18 +01008037 /* Set safe environment for the initialisation. */
8038 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01008039 if (lua_type(gL.T, -1) == LUA_TSTRING)
8040 error_msg = lua_tostring(gL.T, -1);
8041 else
8042 error_msg = "critical error";
8043 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01008044 exit(1);
8045 }
8046
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008047 /*
8048 *
8049 * Create "core" object.
8050 *
8051 */
8052
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008053 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008054 lua_newtable(gL.T);
8055
8056 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008057 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008058 hlua_class_const_int(gL.T, log_levels[i], i);
8059
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008060 /* Register special functions. */
8061 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01008062 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01008063 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01008064 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02008065 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008066 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008067 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01008068 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01008069 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01008070 hlua_class_function(gL.T, "sleep", hlua_sleep);
8071 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01008072 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
8073 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
8074 hlua_class_function(gL.T, "set_map", hlua_set_map);
8075 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008076 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01008077 hlua_class_function(gL.T, "log", hlua_log);
8078 hlua_class_function(gL.T, "Debug", hlua_log_debug);
8079 hlua_class_function(gL.T, "Info", hlua_log_info);
8080 hlua_class_function(gL.T, "Warning", hlua_log_warning);
8081 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02008082 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01008083 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008084
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008085 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008086
8087 /*
8088 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +01008089 * Create "act" object.
8090 *
8091 */
8092
8093 /* This table entry is the object "act" base. */
8094 lua_newtable(gL.T);
8095
8096 /* push action return constants */
8097 hlua_class_const_int(gL.T, "CONTINUE", ACT_RET_CONT);
8098 hlua_class_const_int(gL.T, "STOP", ACT_RET_STOP);
8099 hlua_class_const_int(gL.T, "YIELD", ACT_RET_YIELD);
8100 hlua_class_const_int(gL.T, "ERROR", ACT_RET_ERR);
8101 hlua_class_const_int(gL.T, "DONE", ACT_RET_DONE);
8102 hlua_class_const_int(gL.T, "DENY", ACT_RET_DENY);
8103 hlua_class_const_int(gL.T, "ABORT", ACT_RET_ABRT);
8104 hlua_class_const_int(gL.T, "INVALID", ACT_RET_INV);
8105
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008106 hlua_class_function(gL.T, "wake_time", hlua_action_wake_time);
8107
Christopher Faulet0f3c8902020-01-31 18:57:12 +01008108 lua_setglobal(gL.T, "act");
8109
8110 /*
8111 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008112 * Register class Map
8113 *
8114 */
8115
8116 /* This table entry is the object "Map" base. */
8117 lua_newtable(gL.T);
8118
8119 /* register pattern types. */
8120 for (i=0; i<PAT_MATCH_NUM; i++)
8121 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008122 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008123 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
8124 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008125 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008126
8127 /* register constructor. */
8128 hlua_class_function(gL.T, "new", hlua_map_new);
8129
8130 /* Create and fill the metatable. */
8131 lua_newtable(gL.T);
8132
8133 /* Create and fille the __index entry. */
8134 lua_pushstring(gL.T, "__index");
8135 lua_newtable(gL.T);
8136
8137 /* Register . */
8138 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
8139 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
8140
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008141 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008142
Thierry Fournier45e78d72016-02-19 18:34:46 +01008143 /* Register previous table in the registry with reference and named entry.
8144 * The function hlua_register_metatable() pops the stack, so we
8145 * previously create a copy of the table.
8146 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008147 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008148 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008149
8150 /* Assign the metatable to the mai Map object. */
8151 lua_setmetatable(gL.T, -2);
8152
8153 /* Set a name to the table. */
8154 lua_setglobal(gL.T, "Map");
8155
8156 /*
8157 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008158 * Register class Channel
8159 *
8160 */
8161
8162 /* Create and fill the metatable. */
8163 lua_newtable(gL.T);
8164
8165 /* Create and fille the __index entry. */
8166 lua_pushstring(gL.T, "__index");
8167 lua_newtable(gL.T);
8168
8169 /* Register . */
8170 hlua_class_function(gL.T, "get", hlua_channel_get);
8171 hlua_class_function(gL.T, "dup", hlua_channel_dup);
8172 hlua_class_function(gL.T, "getline", hlua_channel_getline);
8173 hlua_class_function(gL.T, "set", hlua_channel_set);
8174 hlua_class_function(gL.T, "append", hlua_channel_append);
8175 hlua_class_function(gL.T, "send", hlua_channel_send);
8176 hlua_class_function(gL.T, "forward", hlua_channel_forward);
8177 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
8178 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01008179 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008180
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008181 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008182
8183 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008184 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008185
8186 /*
8187 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008188 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008189 *
8190 */
8191
8192 /* Create and fill the metatable. */
8193 lua_newtable(gL.T);
8194
8195 /* Create and fille the __index entry. */
8196 lua_pushstring(gL.T, "__index");
8197 lua_newtable(gL.T);
8198
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008199 /* Browse existing fetches and create the associated
8200 * object method.
8201 */
8202 sf = NULL;
8203 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
8204
8205 /* Dont register the keywork if the arguments check function are
8206 * not safe during the runtime.
8207 */
8208 if ((sf->val_args != NULL) &&
8209 (sf->val_args != val_payload_lv) &&
8210 (sf->val_args != val_hdr))
8211 continue;
8212
8213 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8214 * by an underscore.
8215 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008216 strncpy(trash.area, sf->kw, trash.size);
8217 trash.area[trash.size - 1] = '\0';
8218 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008219 if (*p == '.' || *p == '-' || *p == '+')
8220 *p = '_';
8221
8222 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008223 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01008224 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008225 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008226 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008227 }
8228
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008229 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008230
8231 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008232 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008233
8234 /*
8235 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008236 * Register class Converters
8237 *
8238 */
8239
8240 /* Create and fill the metatable. */
8241 lua_newtable(gL.T);
8242
8243 /* Create and fill the __index entry. */
8244 lua_pushstring(gL.T, "__index");
8245 lua_newtable(gL.T);
8246
8247 /* Browse existing converters and create the associated
8248 * object method.
8249 */
8250 sc = NULL;
8251 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
8252 /* Dont register the keywork if the arguments check function are
8253 * not safe during the runtime.
8254 */
8255 if (sc->val_args != NULL)
8256 continue;
8257
8258 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8259 * by an underscore.
8260 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008261 strncpy(trash.area, sc->kw, trash.size);
8262 trash.area[trash.size - 1] = '\0';
8263 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008264 if (*p == '.' || *p == '-' || *p == '+')
8265 *p = '_';
8266
8267 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008268 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008269 lua_pushlightuserdata(gL.T, sc);
8270 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008271 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008272 }
8273
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008274 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008275
8276 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008277 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008278
8279 /*
8280 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008281 * Register class HTTP
8282 *
8283 */
8284
8285 /* Create and fill the metatable. */
8286 lua_newtable(gL.T);
8287
8288 /* Create and fille the __index entry. */
8289 lua_pushstring(gL.T, "__index");
8290 lua_newtable(gL.T);
8291
8292 /* Register Lua functions. */
8293 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
8294 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
8295 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
8296 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
8297 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
8298 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
8299 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
8300 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
8301 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
8302 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
8303
8304 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
8305 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
8306 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
8307 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
8308 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
8309 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02008310 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008311
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008312 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008313
8314 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008315 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008316
8317 /*
8318 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008319 * Register class AppletTCP
8320 *
8321 */
8322
8323 /* Create and fill the metatable. */
8324 lua_newtable(gL.T);
8325
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008326 /* Create and fille the __index entry. */
8327 lua_pushstring(gL.T, "__index");
8328 lua_newtable(gL.T);
8329
8330 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01008331 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
8332 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
8333 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
8334 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
8335 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008336 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
8337 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
8338 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008339
8340 lua_settable(gL.T, -3);
8341
8342 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008343 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008344
8345 /*
8346 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008347 * Register class AppletHTTP
8348 *
8349 */
8350
8351 /* Create and fill the metatable. */
8352 lua_newtable(gL.T);
8353
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008354 /* Create and fille the __index entry. */
8355 lua_pushstring(gL.T, "__index");
8356 lua_newtable(gL.T);
8357
8358 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01008359 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
8360 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01008361 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
8362 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
8363 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008364 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
8365 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
8366 hlua_class_function(gL.T, "send", hlua_applet_http_send);
8367 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
8368 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
8369 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
8370
8371 lua_settable(gL.T, -3);
8372
8373 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008374 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02008375
8376 /*
8377 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008378 * Register class TXN
8379 *
8380 */
8381
8382 /* Create and fill the metatable. */
8383 lua_newtable(gL.T);
8384
8385 /* Create and fille the __index entry. */
8386 lua_pushstring(gL.T, "__index");
8387 lua_newtable(gL.T);
8388
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008389 /* Register Lua functions. */
Patrick Hemmer268a7072018-05-11 12:52:31 -04008390 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
8391 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
8392 hlua_class_function(gL.T, "set_var", hlua_set_var);
8393 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
8394 hlua_class_function(gL.T, "get_var", hlua_get_var);
8395 hlua_class_function(gL.T, "done", hlua_txn_done);
Christopher Faulet700d9e82020-01-31 12:21:52 +01008396 hlua_class_function(gL.T, "reply", hlua_txn_reply_new);
Patrick Hemmer268a7072018-05-11 12:52:31 -04008397 hlua_class_function(gL.T, "set_loglevel", hlua_txn_set_loglevel);
8398 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
8399 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
8400 hlua_class_function(gL.T, "set_priority_class", hlua_txn_set_priority_class);
8401 hlua_class_function(gL.T, "set_priority_offset", hlua_txn_set_priority_offset);
8402 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
8403 hlua_class_function(gL.T, "log", hlua_txn_log);
8404 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
8405 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
8406 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
8407 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01008408
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008409 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008410
8411 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008412 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008413
8414 /*
8415 *
Christopher Faulet700d9e82020-01-31 12:21:52 +01008416 * Register class reply
8417 *
8418 */
8419 lua_newtable(gL.T);
8420 lua_pushstring(gL.T, "__index");
8421 lua_newtable(gL.T);
8422 hlua_class_function(gL.T, "set_status", hlua_txn_reply_set_status);
8423 hlua_class_function(gL.T, "add_header", hlua_txn_reply_add_header);
8424 hlua_class_function(gL.T, "del_header", hlua_txn_reply_del_header);
8425 hlua_class_function(gL.T, "set_body", hlua_txn_reply_set_body);
8426 lua_settable(gL.T, -3); /* Sets the __index entry. */
8427 class_txn_reply_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
8428
8429
8430 /*
8431 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008432 * Register class Socket
8433 *
8434 */
8435
8436 /* Create and fill the metatable. */
8437 lua_newtable(gL.T);
8438
8439 /* Create and fille the __index entry. */
8440 lua_pushstring(gL.T, "__index");
8441 lua_newtable(gL.T);
8442
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008443#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008444 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01008445#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008446 hlua_class_function(gL.T, "connect", hlua_socket_connect);
8447 hlua_class_function(gL.T, "send", hlua_socket_send);
8448 hlua_class_function(gL.T, "receive", hlua_socket_receive);
8449 hlua_class_function(gL.T, "close", hlua_socket_close);
8450 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
8451 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
8452 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
8453 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
8454
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008455 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008456
8457 /* Register the garbage collector entry. */
8458 lua_pushstring(gL.T, "__gc");
8459 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02008460 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008461
8462 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01008463 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008464
8465 /* Proxy and server configuration initialisation. */
8466 memset(&socket_proxy, 0, sizeof(socket_proxy));
8467 init_new_proxy(&socket_proxy);
8468 socket_proxy.parent = NULL;
8469 socket_proxy.last_change = now.tv_sec;
8470 socket_proxy.id = "LUA-SOCKET";
8471 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
8472 socket_proxy.maxconn = 0;
8473 socket_proxy.accept = NULL;
8474 socket_proxy.options2 |= PR_O2_INDEPSTR;
8475 socket_proxy.srv = NULL;
8476 socket_proxy.conn_retries = 0;
8477 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8478
8479 /* Init TCP server: unchanged parameters */
8480 memset(&socket_tcp, 0, sizeof(socket_tcp));
8481 socket_tcp.next = NULL;
8482 socket_tcp.proxy = &socket_proxy;
8483 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8484 LIST_INIT(&socket_tcp.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008485 socket_tcp.pendconns = EB_ROOT;
Christopher Faulet40a007c2017-07-03 15:41:01 +02008486 socket_tcp.priv_conns = NULL;
8487 socket_tcp.idle_conns = NULL;
8488 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008489 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008490 socket_tcp.last_change = 0;
8491 socket_tcp.id = "LUA-TCP-CONN";
8492 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8493 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8494 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8495
8496 /* XXX: Copy default parameter from default server,
8497 * but the default server is not initialized.
8498 */
8499 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8500 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8501 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8502 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8503 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8504 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8505 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8506 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8507 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8508 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8509
8510 socket_tcp.check.status = HCHK_STATUS_INI;
8511 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8512 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8513 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8514 socket_tcp.check.server = &socket_tcp;
8515
8516 socket_tcp.agent.status = HCHK_STATUS_INI;
8517 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8518 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8519 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8520 socket_tcp.agent.server = &socket_tcp;
8521
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008522 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008523
8524#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008525 /* Init TCP server: unchanged parameters */
8526 memset(&socket_ssl, 0, sizeof(socket_ssl));
8527 socket_ssl.next = NULL;
8528 socket_ssl.proxy = &socket_proxy;
8529 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8530 LIST_INIT(&socket_ssl.actconns);
Patrick Hemmer0355dab2018-05-11 12:52:31 -04008531 socket_ssl.pendconns = EB_ROOT;
Willy Tarreaub784b352019-02-07 14:48:24 +01008532 socket_ssl.priv_conns = NULL;
8533 socket_ssl.idle_conns = NULL;
8534 socket_ssl.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008535 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008536 socket_ssl.last_change = 0;
8537 socket_ssl.id = "LUA-SSL-CONN";
8538 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8539 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8540 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8541
8542 /* XXX: Copy default parameter from default server,
8543 * but the default server is not initialized.
8544 */
8545 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8546 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8547 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8548 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8549 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8550 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8551 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8552 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8553 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8554 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8555
8556 socket_ssl.check.status = HCHK_STATUS_INI;
8557 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8558 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8559 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8560 socket_ssl.check.server = &socket_ssl;
8561
8562 socket_ssl.agent.status = HCHK_STATUS_INI;
8563 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8564 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8565 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8566 socket_ssl.agent.server = &socket_ssl;
8567
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008568 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008569 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008570
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008571 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008572 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8573 /*
8574 *
8575 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008576 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008577 * features like client certificates and ssl_verify.
8578 *
8579 */
8580 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8581 if (tmp_error != 0) {
8582 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8583 abort(); /* This must be never arrives because the command line
8584 not editable by the user. */
8585 }
8586 idx += kw->skip;
8587 }
8588 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008589#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008590
8591 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008592}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008593
Willy Tarreau80713382018-11-26 10:19:54 +01008594static void hlua_register_build_options(void)
8595{
Willy Tarreaubb57d942016-12-21 19:04:56 +01008596 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01008597
Willy Tarreaubb57d942016-12-21 19:04:56 +01008598 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8599 hap_register_build_opts(ptr, 1);
8600}
Willy Tarreau80713382018-11-26 10:19:54 +01008601
8602INITCALL0(STG_REGISTER, hlua_register_build_options);