blob: a60cd2e310be42770ddd56f6476f530a44e82deb [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
Bertrand Jacquinf4c12d42021-01-21 21:14:07 +000013#define _GNU_SOURCE
14
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020016#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010017
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010018#include <lauxlib.h>
19#include <lua.h>
20#include <lualib.h>
21
Thierry FOURNIER463119c2015-03-10 00:35:36 +010022#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
23#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010024#endif
25
Willy Tarreau8d2b7772020-05-27 10:58:19 +020026#include <import/ebpttree.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010027
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/api.h>
29#include <haproxy/applet.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020030#include <haproxy/arg.h>
Christopher Fauletd25d9262020-08-06 11:04:46 +020031#include <haproxy/auth.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020032#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020033#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020034#include <haproxy/cli.h>
Willy Tarreau7ea393d2020-06-04 18:02:10 +020035#include <haproxy/connection.h>
Willy Tarreau5413a872020-06-02 19:33:08 +020036#include <haproxy/h1.h>
Willy Tarreau86416052020-06-04 09:20:54 +020037#include <haproxy/hlua.h>
Willy Tarreau8c794002020-06-04 10:05:25 +020038#include <haproxy/hlua_fcn.h>
Willy Tarreauc2b1ff02020-06-04 21:21:03 +020039#include <haproxy/http_ana.h>
Willy Tarreau126ba3a2020-06-04 18:26:43 +020040#include <haproxy/http_fetch.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020041#include <haproxy/http_htx.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020042#include <haproxy/http_rules.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020043#include <haproxy/log.h>
Willy Tarreau2cd58092020-06-04 15:10:43 +020044#include <haproxy/map.h>
Willy Tarreau8efbdfb2020-06-04 11:29:21 +020045#include <haproxy/obj_type.h>
Willy Tarreau225a90a2020-06-04 15:06:28 +020046#include <haproxy/pattern.h>
Willy Tarreau469509b2020-06-04 15:13:30 +020047#include <haproxy/payload.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020048#include <haproxy/proxy-t.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020049#include <haproxy/regex.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020050#include <haproxy/sample.h>
Willy Tarreau198e92a2021-03-05 10:23:32 +010051#include <haproxy/server.h>
Willy Tarreau48d25b32020-06-04 18:58:52 +020052#include <haproxy/session.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020053#include <haproxy/stats-t.h>
Willy Tarreaudfd3de82020-06-04 23:46:14 +020054#include <haproxy/stream.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020055#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020056#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020057#include <haproxy/tcp_rules.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020058#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020059#include <haproxy/tools.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020060#include <haproxy/vars.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020061#include <haproxy/xref.h>
62
Thierry FOURNIER380d0932015-01-23 14:27:52 +010063
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010064/* Lua uses longjmp to perform yield or throwing errors. This
65 * macro is used only for identifying the function that can
66 * not return because a longjmp is executed.
67 * __LJMP marks a prototype of hlua file that can use longjmp.
68 * WILL_LJMP() marks an lua function that will use longjmp.
69 * MAY_LJMP() marks an lua function that may use longjmp.
70 */
71#define __LJMP
Willy Tarreau4e7cc332018-10-20 17:45:48 +020072#define WILL_LJMP(func) do { func; my_unreachable(); } while(0)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010073#define MAY_LJMP(func) func
74
Thierry FOURNIERbabae282015-09-17 11:36:37 +020075/* This couple of function executes securely some Lua calls outside of
76 * the lua runtime environment. Each Lua call can return a longjmp
77 * if it encounter a memory error.
78 *
79 * Lua documentation extract:
80 *
81 * If an error happens outside any protected environment, Lua calls
82 * a panic function (see lua_atpanic) and then calls abort, thus
83 * exiting the host application. Your panic function can avoid this
84 * exit by never returning (e.g., doing a long jump to your own
85 * recovery point outside Lua).
86 *
87 * The panic function runs as if it were a message handler (see
88 * §2.3); in particular, the error message is at the top of the
89 * stack. However, there is no guarantee about stack space. To push
90 * anything on the stack, the panic function must first check the
91 * available space (see §4.2).
92 *
93 * We must check all the Lua entry point. This includes:
94 * - The include/proto/hlua.h exported functions
95 * - the task wrapper function
96 * - The action wrapper function
97 * - The converters wrapper function
98 * - The sample-fetch wrapper functions
99 *
Ilya Shipitsin46a030c2020-07-05 16:36:08 +0500100 * It is tolerated that the initialisation function returns an abort.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800101 * Before each Lua abort, an error message is written on stderr.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200102 *
103 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
104 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
105 * because they must be exists in the program stack when the longjmp
106 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200107 *
108 * Note that the Lua processing is not really thread safe. It provides
109 * heavy system which consists to add our own lock function in the Lua
110 * code and recompile the library. This system will probably not accepted
111 * by maintainers of various distribs.
112 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500113 * Our main execution point of the Lua is the function lua_resume(). A
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200114 * quick looking on the Lua sources displays a lua_lock() a the start
115 * of function and a lua_unlock() at the end of the function. So I
116 * conclude that the Lua thread safe mode just perform a mutex around
117 * all execution. So I prefer to do this in the HAProxy code, it will be
118 * easier for distro maintainers.
119 *
120 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
121 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
122 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200123 */
Willy Tarreau86abe442018-11-25 20:12:18 +0100124__decl_spinlock(hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200125THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200126static int hlua_panic_safe(lua_State *L) { return 0; }
Willy Tarreau9d6bb5a2020-02-06 15:55:41 +0100127static int hlua_panic_ljmp(lua_State *L) { WILL_LJMP(longjmp(safe_ljmp_env, 1)); }
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200128
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100129/* This is the chained list of struct hlua_function referenced
130 * for haproxy action, sample-fetches, converters, cli and
131 * applet bindings. It is used for a post-initialisation control.
132 */
133static struct list referenced_functions = LIST_HEAD_INIT(referenced_functions);
134
Thierry Fournierc7492592020-11-28 23:57:24 +0100135/* This variable is used only during initialization to identify the Lua state
136 * currently being initialized. 0 is the common lua state, 1 to n are the Lua
137 * states dedicated to each thread (in this case hlua_state_id==tid+1).
138 */
139static int hlua_state_id;
140
Thierry Fournier59f11be2020-11-29 00:37:41 +0100141/* This is a NULL-terminated list of lua file which are referenced to load per thread */
142static char **per_thread_load = NULL;
143
144lua_State *hlua_init_state(int thread_id);
145
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100146#define SET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200147 ({ \
148 int ret; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100149 if ((__HLUA)->state_id == 0) \
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100150 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200151 if (setjmp(safe_ljmp_env) != 0) { \
152 lua_atpanic(__L, hlua_panic_safe); \
153 ret = 0; \
Thierry Fournier021d9862020-11-28 23:42:03 +0100154 if ((__HLUA)->state_id == 0) \
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100155 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200156 } else { \
157 lua_atpanic(__L, hlua_panic_ljmp); \
158 ret = 1; \
159 } \
160 ret; \
161 })
162
163/* If we are the last function catching Lua errors, we
164 * must reset the panic function.
165 */
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100166#define RESET_SAFE_LJMP_L(__L, __HLUA) \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200167 do { \
168 lua_atpanic(__L, hlua_panic_safe); \
Thierry Fournier021d9862020-11-28 23:42:03 +0100169 if ((__HLUA)->state_id == 0) \
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100170 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200171 } while(0)
172
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100173#define SET_SAFE_LJMP(__HLUA) \
174 SET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
175
176#define RESET_SAFE_LJMP(__HLUA) \
177 RESET_SAFE_LJMP_L((__HLUA)->T, __HLUA)
178
179#define SET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100180 SET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100181
182#define RESET_SAFE_LJMP_PARENT(__HLUA) \
Thierry Fournier021d9862020-11-28 23:42:03 +0100183 RESET_SAFE_LJMP_L(hlua_states[(__HLUA)->state_id], __HLUA)
Thierry Fournier7cbe5042020-11-28 17:02:21 +0100184
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200185/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200186#define APPLET_DONE 0x01 /* applet processing is done. */
Christopher Faulet18c2e8d2019-03-01 12:02:08 +0100187/* unused: 0x02 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200188#define APPLET_HDR_SENT 0x04 /* Response header sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +0200189/* unused: 0x08, 0x10 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100190#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +0100191#define APPLET_RSP_SENT 0x40 /* The response was fully sent */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200192
Thierry Fournierafc63e22020-11-28 17:06:51 +0100193/* The main Lua execution context. The 0 index is the
194 * common state shared by all threads.
195 */
Willy Tarreau186f3762020-12-04 11:48:12 +0100196static lua_State *hlua_states[MAX_THREADS + 1];
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100197
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100198/* This is the memory pool containing struct lua for applets
199 * (including cli).
200 */
Willy Tarreau8ceae722018-11-26 11:58:30 +0100201DECLARE_STATIC_POOL(pool_head_hlua, "hlua", sizeof(struct hlua));
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100202
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100203/* Used for Socket connection. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +0100204static struct proxy *socket_proxy;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100205static struct server *socket_tcp;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100206#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +0100207static struct server *socket_ssl;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100208#endif
209
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100210/* List head of the function called at the initialisation time. */
Thierry Fournierc7492592020-11-28 23:57:24 +0100211struct list hlua_init_functions[MAX_THREADS + 1];
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100212
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100213/* The following variables contains the reference of the different
214 * Lua classes. These references are useful for identify metadata
215 * associated with an object.
216 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100217static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100218static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100219static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100220static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100221static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100222static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200223static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200224static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200225static int class_applet_http_ref;
Christopher Faulet700d9e82020-01-31 12:21:52 +0100226static int class_txn_reply_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100227
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100228/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200229 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100230 * short timeout. Lua linked with tasks doesn't have a timeout
231 * because a task may remain alive during all the haproxy execution.
232 */
233static unsigned int hlua_timeout_session = 4000; /* session timeout. */
234static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200235static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100236
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100237/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
238 * it is used for preventing infinite loops.
239 *
240 * I test the scheer with an infinite loop containing one incrementation
241 * and one test. I run this loop between 10 seconds, I raise a ceil of
242 * 710M loops from one interrupt each 9000 instructions, so I fix the value
243 * to one interrupt each 10 000 instructions.
244 *
245 * configured | Number of
246 * instructions | loops executed
247 * between two | in milions
248 * forced yields |
249 * ---------------+---------------
250 * 10 | 160
251 * 500 | 670
252 * 1000 | 680
253 * 5000 | 700
254 * 7000 | 700
255 * 8000 | 700
256 * 9000 | 710 <- ceil
257 * 10000 | 710
258 * 100000 | 710
259 * 1000000 | 710
260 *
261 */
262static unsigned int hlua_nb_instruction = 10000;
263
Willy Tarreaucdb53462020-12-02 12:12:00 +0100264/* Descriptor for the memory allocation state. The limit is pre-initialised to
265 * 0 until it is replaced by "tune.lua.maxmem" during the config parsing, or it
266 * is replaced with ~0 during post_init after everything was loaded. This way
267 * it is guaranteed that if limit is ~0 the boot is complete and that if it's
268 * zero it's not yet limited and proper accounting is required.
Willy Tarreau32f61e22015-03-18 17:54:59 +0100269 */
270struct hlua_mem_allocator {
271 size_t allocated;
272 size_t limit;
273};
274
Willy Tarreaucdb53462020-12-02 12:12:00 +0100275static struct hlua_mem_allocator hlua_global_allocator THREAD_ALIGNED(64);
Willy Tarreau32f61e22015-03-18 17:54:59 +0100276
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100277/* These functions converts types between HAProxy internal args or
278 * sample and LUA types. Another function permits to check if the
279 * LUA stack contains arguments according with an required ARG_T
280 * format.
281 */
282static int hlua_arg2lua(lua_State *L, const struct arg *arg);
283static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100284__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100285 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100286static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100287static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100288static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
289
Christopher Faulet9d1332b2020-02-24 16:46:16 +0100290__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200291
Thierry Fournier59f11be2020-11-29 00:37:41 +0100292struct prepend_path {
293 struct list l;
294 char *type;
295 char *path;
296};
297
298static struct list prepend_path_list = LIST_HEAD_INIT(prepend_path_list);
299
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200300#define SEND_ERR(__be, __fmt, __args...) \
301 do { \
302 send_log(__be, LOG_ERR, __fmt, ## __args); \
303 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100304 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200305 } while (0)
306
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100307static inline struct hlua_function *new_hlua_function()
308{
309 struct hlua_function *fcn;
Thierry Fournierc7492592020-11-28 23:57:24 +0100310 int i;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100311
312 fcn = calloc(1, sizeof(*fcn));
313 if (!fcn)
314 return NULL;
315 LIST_ADDQ(&referenced_functions, &fcn->l);
Thierry Fournierc7492592020-11-28 23:57:24 +0100316 for (i = 0; i < MAX_THREADS + 1; i++)
317 fcn->function_ref[i] = -1;
Thierry Fournier62a22aa2020-11-28 21:06:35 +0100318 return fcn;
319}
320
Christopher Fauletdda44442021-04-12 14:05:43 +0200321static inline void release_hlua_function(struct hlua_function *fcn)
322{
323 if (!fcn)
324 return;
325 if (fcn->name)
326 ha_free(&fcn->name);
327 LIST_DEL(&fcn->l);
328 ha_free(&fcn);
329}
330
Thierry Fournierc7492592020-11-28 23:57:24 +0100331/* If the common state is set, the stack id is 0, otherwise it is the tid + 1 */
332static inline int fcn_ref_to_stack_id(struct hlua_function *fcn)
333{
334 if (fcn->function_ref[0] == -1)
335 return tid + 1;
336 return 0;
337}
338
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100339/* Used to check an Lua function type in the stack. It creates and
340 * returns a reference of the function. This function throws an
341 * error if the rgument is not a "function".
342 */
343__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
344{
345 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100346 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100347 WILL_LJMP(luaL_argerror(L, argno, msg));
348 }
349 lua_pushvalue(L, argno);
350 return luaL_ref(L, LUA_REGISTRYINDEX);
351}
352
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200353/* Return the string that is of the top of the stack. */
354const char *hlua_get_top_error_string(lua_State *L)
355{
356 if (lua_gettop(L) < 1)
357 return "unknown error";
358 if (lua_type(L, -1) != LUA_TSTRING)
359 return "unknown error";
360 return lua_tostring(L, -1);
361}
362
Christopher Fauletd09cc512021-03-24 14:48:45 +0100363__LJMP const char *hlua_traceback(lua_State *L, const char* sep)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200364{
365 lua_Debug ar;
366 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200367 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200368
369 while (lua_getstack(L, level++, &ar)) {
370
371 /* Add separator */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100372 if (b_data(msg))
373 chunk_appendf(msg, "%s", sep);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200374
375 /* Fill fields:
376 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
377 * 'l': fills in the field currentline;
378 * 'n': fills in the field name and namewhat;
379 * 't': fills in the field istailcall;
380 */
381 lua_getinfo(L, "Slnt", &ar);
382
383 /* Append code localisation */
384 if (ar.currentline > 0)
Christopher Fauletd09cc512021-03-24 14:48:45 +0100385 chunk_appendf(msg, "%s:%d: ", ar.short_src, ar.currentline);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200386 else
Christopher Fauletd09cc512021-03-24 14:48:45 +0100387 chunk_appendf(msg, "%s: ", ar.short_src);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200388
389 /*
390 * Get function name
391 *
392 * if namewhat is no empty, name is defined.
393 * what contains "Lua" for Lua function, "C" for C function,
394 * or "main" for main code.
395 */
396 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100397 chunk_appendf(msg, "in %s '%s'", ar.namewhat, ar.name); /* use it */
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200398
399 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100400 chunk_appendf(msg, "in main chunk");
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200401
402 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
Christopher Fauletd09cc512021-03-24 14:48:45 +0100403 chunk_appendf(msg, "in function line %d", ar.linedefined);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200404
405 else /* nothing left... */
406 chunk_appendf(msg, "?");
407
408
409 /* Display tailed call */
410 if (ar.istailcall)
411 chunk_appendf(msg, " ...");
412 }
413
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200414 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200415}
416
417
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100418/* This function check the number of arguments available in the
419 * stack. If the number of arguments available is not the same
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500420 * then <nb> an error is thrown.
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100421 */
422__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
423{
424 if (lua_gettop(L) == nb)
425 return;
426 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
427}
428
Mark Lakes22154b42018-01-29 14:38:40 -0800429/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100430 * and the line number where the error is encountered.
431 */
432static int hlua_pusherror(lua_State *L, const char *fmt, ...)
433{
434 va_list argp;
435 va_start(argp, fmt);
436 luaL_where(L, 1);
437 lua_pushvfstring(L, fmt, argp);
438 va_end(argp);
439 lua_concat(L, 2);
440 return 1;
441}
442
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100443/* This functions is used with sample fetch and converters. It
444 * converts the HAProxy configuration argument in a lua stack
445 * values.
446 *
447 * It takes an array of "arg", and each entry of the array is
448 * converted and pushed in the LUA stack.
449 */
450static int hlua_arg2lua(lua_State *L, const struct arg *arg)
451{
452 switch (arg->type) {
453 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100454 case ARGT_TIME:
455 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100456 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100457 break;
458
459 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200460 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100461 break;
462
463 case ARGT_IPV4:
464 case ARGT_IPV6:
465 case ARGT_MSK4:
466 case ARGT_MSK6:
467 case ARGT_FE:
468 case ARGT_BE:
469 case ARGT_TAB:
470 case ARGT_SRV:
471 case ARGT_USR:
472 case ARGT_MAP:
473 default:
474 lua_pushnil(L);
475 break;
476 }
477 return 1;
478}
479
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500480/* This function take one entry in an LUA stack at the index "ud",
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100481 * and try to convert it in an HAProxy argument entry. This is useful
Ilya Shipitsind4259502020-04-08 01:07:56 +0500482 * with sample fetch wrappers. The input arguments are given to the
483 * lua wrapper and converted as arg list by the function.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100484 */
485static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
486{
487 switch (lua_type(L, ud)) {
488
489 case LUA_TNUMBER:
490 case LUA_TBOOLEAN:
491 arg->type = ARGT_SINT;
492 arg->data.sint = lua_tointeger(L, ud);
493 break;
494
495 case LUA_TSTRING:
496 arg->type = ARGT_STR;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200497 arg->data.str.area = (char *)lua_tolstring(L, ud, &arg->data.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200498 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200499 arg->data.str.size = arg->data.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200500 arg->data.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100501 break;
502
503 case LUA_TUSERDATA:
504 case LUA_TNIL:
505 case LUA_TTABLE:
506 case LUA_TFUNCTION:
507 case LUA_TTHREAD:
508 case LUA_TLIGHTUSERDATA:
509 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200510 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100511 break;
512 }
513 return 1;
514}
515
516/* the following functions are used to convert a struct sample
517 * in Lua type. This useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500518 * fetches or converters.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100519 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100520static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100521{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200522 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100523 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100524 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200525 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100526 break;
527
528 case SMP_T_BIN:
529 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200530 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100531 break;
532
533 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200534 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100535 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
536 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
537 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
538 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
539 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
540 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
541 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
542 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
543 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200544 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100545 break;
546 default:
547 lua_pushnil(L);
548 break;
549 }
550 break;
551
552 case SMP_T_IPV4:
553 case SMP_T_IPV6:
554 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200555 if (sample_casts[smp->data.type][SMP_T_STR] &&
556 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200557 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100558 else
559 lua_pushnil(L);
560 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100561 default:
562 lua_pushnil(L);
563 break;
564 }
565 return 1;
566}
567
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100568/* the following functions are used to convert a struct sample
569 * in Lua strings. This is useful to convert the return of the
Ilya Shipitsind4259502020-04-08 01:07:56 +0500570 * fetches or converters.
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100571 */
572static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
573{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200574 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100575
576 case SMP_T_BIN:
577 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200578 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100579 break;
580
581 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200582 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100583 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
584 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
585 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
586 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
587 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
588 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
589 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
590 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
591 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200592 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100593 break;
594 default:
595 lua_pushstring(L, "");
596 break;
597 }
598 break;
599
600 case SMP_T_SINT:
601 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100602 case SMP_T_IPV4:
603 case SMP_T_IPV6:
604 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200605 if (sample_casts[smp->data.type][SMP_T_STR] &&
606 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200607 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100608 else
609 lua_pushstring(L, "");
610 break;
611 default:
612 lua_pushstring(L, "");
613 break;
614 }
615 return 1;
616}
617
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100618/* the following functions are used to convert an Lua type in a
619 * struct sample. This is useful to provide data from a converter
620 * to the LUA code.
621 */
622static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
623{
624 switch (lua_type(L, ud)) {
625
626 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200627 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200628 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100629 break;
630
631
632 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200633 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200634 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100635 break;
636
637 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200638 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100639 smp->flags |= SMP_F_CONST;
Tim Duesterhus2e89dec2019-09-29 23:03:08 +0200640 smp->data.u.str.area = (char *)lua_tolstring(L, ud, &smp->data.u.str.data);
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200641 /* We don't know the actual size of the underlying allocation, so be conservative. */
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200642 smp->data.u.str.size = smp->data.u.str.data+1; /* count the terminating null byte */
Tim Duesterhus29d2e8a2019-09-29 23:03:07 +0200643 smp->data.u.str.head = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100644 break;
645
646 case LUA_TUSERDATA:
647 case LUA_TNIL:
648 case LUA_TTABLE:
649 case LUA_TFUNCTION:
650 case LUA_TTHREAD:
651 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200652 case LUA_TNONE:
653 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200654 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200655 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100656 break;
657 }
658 return 1;
659}
660
Ilya Shipitsind4259502020-04-08 01:07:56 +0500661/* This function check the "argp" built by another conversion function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -0800662 * is in accord with the expected argp defined by the "mask". The function
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100663 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100664 *
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500665 * This function assumes that the argp argument contains ARGM_NBARGS + 1
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100666 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100668__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100669 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100670{
671 int min_arg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200672 int i, idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100673 struct proxy *px;
Christopher Fauletd25d9262020-08-06 11:04:46 +0200674 struct userlist *ul;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200675 struct my_regex *reg;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200676 const char *msg = NULL;
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200677 char *sname, *pname, *err = NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100678
679 idx = 0;
680 min_arg = ARGM(mask);
681 mask >>= ARGM_BITS;
682
683 while (1) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200684 struct buffer tmp = BUF_NULL;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100685
686 /* Check oversize. */
687 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200688 msg = "Malformed argument mask";
689 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100690 }
691
692 /* Check for mandatory arguments. */
693 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100694 if (idx < min_arg) {
695
696 /* If miss other argument than the first one, we return an error. */
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200697 if (idx > 0) {
698 msg = "Mandatory argument expected";
699 goto error;
700 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100701
702 /* If first argument have a certain type, some default values
703 * may be used. See the function smp_resolve_args().
704 */
705 switch (mask & ARGT_MASK) {
706
707 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200708 if (!(p->cap & PR_CAP_FE)) {
709 msg = "Mandatory argument expected";
710 goto error;
711 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100712 argp[idx].data.prx = p;
713 argp[idx].type = ARGT_FE;
714 argp[idx+1].type = ARGT_STOP;
715 break;
716
717 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200718 if (!(p->cap & PR_CAP_BE)) {
719 msg = "Mandatory argument expected";
720 goto error;
721 }
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100722 argp[idx].data.prx = p;
723 argp[idx].type = ARGT_BE;
724 argp[idx+1].type = ARGT_STOP;
725 break;
726
727 case ARGT_TAB:
728 argp[idx].data.prx = p;
729 argp[idx].type = ARGT_TAB;
730 argp[idx+1].type = ARGT_STOP;
731 break;
732
733 default:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200734 msg = "Mandatory argument expected";
735 goto error;
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100736 break;
737 }
738 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200739 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100740 }
741
Ilya Shipitsin856aabc2020-04-16 23:51:34 +0500742 /* Check for exceed the number of required argument. */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100743 if ((mask & ARGT_MASK) == ARGT_STOP &&
744 argp[idx].type != ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200745 msg = "Last argument expected";
746 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100747 }
748
749 if ((mask & ARGT_MASK) == ARGT_STOP &&
750 argp[idx].type == ARGT_STOP) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200751 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100752 }
753
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200754 /* Convert some argument types. All string in argp[] are for not
755 * duplicated yet.
756 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100757 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100758 case ARGT_SINT:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200759 if (argp[idx].type != ARGT_SINT) {
760 msg = "integer expected";
761 goto error;
762 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100763 argp[idx].type = ARGT_SINT;
764 break;
765
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100766 case ARGT_TIME:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200767 if (argp[idx].type != ARGT_SINT) {
768 msg = "integer expected";
769 goto error;
770 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200771 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100772 break;
773
774 case ARGT_SIZE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200775 if (argp[idx].type != ARGT_SINT) {
776 msg = "integer expected";
777 goto error;
778 }
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200779 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100780 break;
781
782 case ARGT_FE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200783 if (argp[idx].type != ARGT_STR) {
784 msg = "string expected";
785 goto error;
786 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200787 argp[idx].data.prx = proxy_fe_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200788 if (!argp[idx].data.prx) {
789 msg = "frontend doesn't exist";
790 goto error;
791 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100792 argp[idx].type = ARGT_FE;
793 break;
794
795 case ARGT_BE:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200796 if (argp[idx].type != ARGT_STR) {
797 msg = "string expected";
798 goto error;
799 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200800 argp[idx].data.prx = proxy_be_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200801 if (!argp[idx].data.prx) {
802 msg = "backend doesn't exist";
803 goto error;
804 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100805 argp[idx].type = ARGT_BE;
806 break;
807
808 case ARGT_TAB:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200809 if (argp[idx].type != ARGT_STR) {
810 msg = "string expected";
811 goto error;
812 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200813 argp[idx].data.t = stktable_find_by_name(argp[idx].data.str.area);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200814 if (!argp[idx].data.t) {
815 msg = "table doesn't exist";
816 goto error;
817 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100818 argp[idx].type = ARGT_TAB;
819 break;
820
821 case ARGT_SRV:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200822 if (argp[idx].type != ARGT_STR) {
823 msg = "string expected";
824 goto error;
825 }
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200826 sname = strrchr(argp[idx].data.str.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100827 if (sname) {
828 *sname++ = '\0';
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200829 pname = argp[idx].data.str.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200830 px = proxy_be_by_name(pname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200831 if (!px) {
832 msg = "backend doesn't exist";
833 goto error;
834 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100835 }
836 else {
Christopher Fauletfdea1b62020-08-06 08:29:18 +0200837 sname = argp[idx].data.str.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100838 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100839 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100840 argp[idx].data.srv = findserver(px, sname);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200841 if (!argp[idx].data.srv) {
842 msg = "server doesn't exist";
843 goto error;
844 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100845 argp[idx].type = ARGT_SRV;
846 break;
847
848 case ARGT_IPV4:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200849 if (argp[idx].type != ARGT_STR) {
850 msg = "string expected";
851 goto error;
852 }
853 if (inet_pton(AF_INET, argp[idx].data.str.area, &argp[idx].data.ipv4)) {
854 msg = "invalid IPv4 address";
855 goto error;
856 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100857 argp[idx].type = ARGT_IPV4;
858 break;
859
860 case ARGT_MSK4:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200861 if (argp[idx].type == ARGT_SINT)
862 len2mask4(argp[idx].data.sint, &argp[idx].data.ipv4);
863 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200864 if (!str2mask(argp[idx].data.str.area, &argp[idx].data.ipv4)) {
865 msg = "invalid IPv4 mask";
866 goto error;
867 }
868 }
869 else {
870 msg = "integer or string expected";
871 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +0200872 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100873 argp[idx].type = ARGT_MSK4;
874 break;
875
876 case ARGT_IPV6:
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200877 if (argp[idx].type != ARGT_STR) {
878 msg = "string expected";
879 goto error;
880 }
881 if (inet_pton(AF_INET6, argp[idx].data.str.area, &argp[idx].data.ipv6)) {
882 msg = "invalid IPv6 address";
883 goto error;
884 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100885 argp[idx].type = ARGT_IPV6;
886 break;
887
888 case ARGT_MSK6:
Christopher Faulete663a6e2020-08-07 09:11:22 +0200889 if (argp[idx].type == ARGT_SINT)
890 len2mask6(argp[idx].data.sint, &argp[idx].data.ipv6);
891 else if (argp[idx].type == ARGT_STR) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200892 if (!str2mask6(argp[idx].data.str.area, &argp[idx].data.ipv6)) {
893 msg = "invalid IPv6 mask";
894 goto error;
895 }
896 }
897 else {
898 msg = "integer or string expected";
899 goto error;
Christopher Faulete663a6e2020-08-07 09:11:22 +0200900 }
Tim Duesterhusb814da62018-01-25 16:24:50 +0100901 argp[idx].type = ARGT_MSK6;
902 break;
903
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200904 case ARGT_REG:
905 if (argp[idx].type != ARGT_STR) {
906 msg = "string expected";
907 goto error;
908 }
909 reg = regex_comp(argp[idx].data.str.area, !(argp[idx].type_flags & ARGF_REG_ICASE), 1, &err);
910 if (!reg) {
911 msg = lua_pushfstring(L, "error compiling regex '%s' : '%s'",
912 argp[idx].data.str.area, err);
913 free(err);
914 goto error;
915 }
916 argp[idx].type = ARGT_REG;
917 argp[idx].data.reg = reg;
918 break;
919
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100920 case ARGT_USR:
Christopher Fauletd25d9262020-08-06 11:04:46 +0200921 if (argp[idx].type != ARGT_STR) {
922 msg = "string expected";
923 goto error;
924 }
925 if (p->uri_auth && p->uri_auth->userlist &&
Tim Duesterhuse5ff1412021-01-02 22:31:53 +0100926 strcmp(p->uri_auth->userlist->name, argp[idx].data.str.area) == 0)
Christopher Fauletd25d9262020-08-06 11:04:46 +0200927 ul = p->uri_auth->userlist;
928 else
929 ul = auth_find_userlist(argp[idx].data.str.area);
930
931 if (!ul) {
932 msg = lua_pushfstring(L, "unable to find userlist '%s'", argp[idx].data.str.area);
933 goto error;
934 }
935 argp[idx].type = ARGT_USR;
936 argp[idx].data.usr = ul;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200937 break;
938
939 case ARGT_STR:
940 if (!chunk_dup(&tmp, &argp[idx].data.str)) {
941 msg = "unable to duplicate string arg";
942 goto error;
943 }
944 argp[idx].data.str = tmp;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100945 break;
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200946
Christopher Fauletd25d9262020-08-06 11:04:46 +0200947 case ARGT_MAP:
Christopher Fauletd25d9262020-08-06 11:04:46 +0200948 msg = "type not yet supported";
949 goto error;
950 break;
951
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100952 }
953
954 /* Check for type of argument. */
955 if ((mask & ARGT_MASK) != argp[idx].type) {
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200956 msg = lua_pushfstring(L, "'%s' expected, got '%s'",
957 arg_type_names[(mask & ARGT_MASK)],
958 arg_type_names[argp[idx].type & ARGT_MASK]);
959 goto error;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100960 }
961
962 /* Next argument. */
963 mask >>= ARGT_BITS;
964 idx++;
965 }
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200966 return 0;
967
968 error:
969 for (i = 0; i < idx; i++) {
970 if (argp[i].type == ARGT_STR)
971 chunk_destroy(&argp[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +0200972 else if (argp[i].type == ARGT_REG)
973 regex_free(argp[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +0200974 }
975 WILL_LJMP(luaL_argerror(L, first + idx, msg));
976 return 0; /* Never reached */
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100977}
978
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100979/*
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +0500980 * The following functions are used to make correspondence between the the
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100981 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100982 *
983 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100984 * - hlua_sethlua : create the association between hlua context and lua_state.
985 */
986static inline struct hlua *hlua_gethlua(lua_State *L)
987{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100988 struct hlua **hlua = lua_getextraspace(L);
989 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100990}
991static inline void hlua_sethlua(struct hlua *hlua)
992{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100993 struct hlua **hlua_store = lua_getextraspace(hlua->T);
994 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100995}
996
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100997/* This function is used to send logs. It try to send on screen (stderr)
998 * and on the default syslog server.
999 */
1000static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
1001{
1002 struct tm tm;
1003 char *p;
1004
1005 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001006 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001007 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001008 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +02001009 /* Break the message if exceed the buffer size. */
1010 *(p-4) = ' ';
1011 *(p-3) = '.';
1012 *(p-2) = '.';
1013 *(p-1) = '.';
1014 break;
1015 }
Willy Tarreau90807112020-02-25 08:16:33 +01001016 if (isprint((unsigned char)*msg))
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001017 *p = *msg;
1018 else
1019 *p = '.';
1020 }
1021 *p = '\0';
1022
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001023 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001024 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Christopher Fauletf98d8212020-10-02 18:13:52 +02001025 if (level == LOG_DEBUG && !(global.mode & MODE_DEBUG))
1026 return;
1027
Willy Tarreaua678b432015-08-28 10:14:59 +02001028 get_localtime(date.tv_sec, &tm);
1029 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001030 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001031 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01001032 fflush(stderr);
1033 }
1034}
1035
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001036/* This function just ensure that the yield will be always
1037 * returned with a timeout and permit to set some flags
1038 */
1039__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001040 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001041{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001042 struct hlua *hlua;
1043
1044 /* Get hlua struct, or NULL if we execute from main lua state */
1045 hlua = hlua_gethlua(L);
1046 if (!hlua) {
1047 return;
1048 }
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001049
1050 /* Set the wake timeout. If timeout is required, we set
1051 * the expiration time.
1052 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001053 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001054
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001055 hlua->flags |= flags;
1056
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001057 /* Process the yield. */
Willy Tarreau9635e032018-10-16 17:52:55 +02001058 MAY_LJMP(lua_yieldk(L, nresults, ctx, k));
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001059}
1060
Willy Tarreau87b09662015-04-03 00:22:06 +02001061/* This function initialises the Lua environment stored in the stream.
1062 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001063 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001064 *
1065 * This function is particular. it initialises a new Lua thread. If the
1066 * initialisation fails (example: out of memory error), the lua function
1067 * throws an error (longjmp).
1068 *
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001069 * In some case (at least one), this function can be called from safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001070 * environment, so we must not initialise it. While the support of
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001071 * threads appear, the safe environment set a lock to ensure only one
1072 * Lua execution at a time. If we initialize safe environment in another
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001073 * safe environment, we have a dead lock.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001074 *
1075 * set "already_safe" true if the context is initialized form safe
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001076 * Lua function.
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001077 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001078 * This function manipulates two Lua stacks: the main and the thread. Only
Thierry FOURNIERbabae282015-09-17 11:36:37 +02001079 * the main stack can fail. The thread is not manipulated. This function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001080 * MUST NOT manipulate the created thread stack state, because it is not
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001081 * protected against errors thrown by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001082 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001083int hlua_ctx_init(struct hlua *lua, int state_id, struct task *task, int already_safe)
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001084{
1085 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001086 lua->flags = 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001087 lua->gc_count = 0;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001088 lua->wake_time = TICK_ETERNITY;
Thierry Fournier021d9862020-11-28 23:42:03 +01001089 lua->state_id = state_id;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001090 LIST_INIT(&lua->com);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001091 if (!already_safe) {
1092 if (!SET_SAFE_LJMP_PARENT(lua)) {
1093 lua->Tref = LUA_REFNIL;
1094 return 0;
1095 }
1096 }
Thierry Fournier021d9862020-11-28 23:42:03 +01001097 lua->T = lua_newthread(hlua_states[state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001098 if (!lua->T) {
1099 lua->Tref = LUA_REFNIL;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001100 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001101 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001102 return 0;
1103 }
1104 hlua_sethlua(lua);
Thierry Fournier021d9862020-11-28 23:42:03 +01001105 lua->Tref = luaL_ref(hlua_states[state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001106 lua->task = task;
Thierry FOURNIERbf90ce12019-01-06 19:04:24 +01001107 if (!already_safe)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001108 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001109 return 1;
1110}
1111
Willy Tarreau87b09662015-04-03 00:22:06 +02001112/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001113 * is destroyed. The destroy also the memory context. The struct "lua"
1114 * is not freed.
1115 */
1116void hlua_ctx_destroy(struct hlua *lua)
1117{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001118 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +01001119 return;
1120
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001121 if (!lua->T)
1122 goto end;
1123
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001124 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001125 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001126
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001127 if (!SET_SAFE_LJMP(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001128 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001129 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001130 RESET_SAFE_LJMP(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001131
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001132 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001133 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001134 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001135 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001136 /* Forces a garbage collecting process. If the Lua program is finished
1137 * without error, we run the GC on the thread pointer. Its freed all
1138 * the unused memory.
1139 * If the thread is finnish with an error or is currently yielded,
1140 * it seems that the GC applied on the thread doesn't clean anything,
1141 * so e run the GC on the main thread.
1142 * NOTE: maybe this action locks all the Lua threads untiml the en of
1143 * the garbage collection.
1144 */
Willy Tarreauf31af932020-01-14 09:59:38 +01001145 if (lua->gc_count) {
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001146 if (!SET_SAFE_LJMP_PARENT(lua))
Thierry FOURNIER75d02082017-07-12 13:41:33 +02001147 return;
Thierry Fournier021d9862020-11-28 23:42:03 +01001148 lua_gc(hlua_states[lua->state_id], LUA_GCCOLLECT, 0);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001149 RESET_SAFE_LJMP_PARENT(lua);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001150 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +02001151
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +02001152 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01001153
1154end:
Willy Tarreaubafbe012017-11-24 17:34:44 +01001155 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001156}
1157
1158/* This function is used to restore the Lua context when a coroutine
1159 * fails. This function copy the common memory between old coroutine
1160 * and the new coroutine. The old coroutine is destroyed, and its
1161 * replaced by the new coroutine.
1162 * If the flag "keep_msg" is set, the last entry of the old is assumed
1163 * as string error message and it is copied in the new stack.
1164 */
1165static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
1166{
1167 lua_State *T;
1168 int new_ref;
1169
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001170 /* New Lua coroutine. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001171 T = lua_newthread(hlua_states[lua->state_id]);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001172 if (!T)
1173 return 0;
1174
1175 /* Copy last error message. */
1176 if (keep_msg)
1177 lua_xmove(lua->T, T, 1);
1178
1179 /* Copy data between the coroutines. */
1180 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1181 lua_xmove(lua->T, T, 1);
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001182 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Value popped. */
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001183
1184 /* Destroy old data. */
1185 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
1186
1187 /* The thread is garbage collected by Lua. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001188 luaL_unref(hlua_states[lua->state_id], LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001189
1190 /* Fill the struct with the new coroutine values. */
1191 lua->Mref = new_ref;
1192 lua->T = T;
Thierry Fournier021d9862020-11-28 23:42:03 +01001193 lua->Tref = luaL_ref(hlua_states[lua->state_id], LUA_REGISTRYINDEX);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001194
1195 /* Set context. */
1196 hlua_sethlua(lua);
1197
1198 return 1;
1199}
1200
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001201void hlua_hook(lua_State *L, lua_Debug *ar)
1202{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001203 struct hlua *hlua;
1204
1205 /* Get hlua struct, or NULL if we execute from main lua state */
1206 hlua = hlua_gethlua(L);
1207 if (!hlua)
1208 return;
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001209
1210 /* Lua cannot yield when its returning from a function,
1211 * so, we can fix the interrupt hook to 1 instruction,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001212 * expecting that the function is finished.
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001213 */
1214 if (lua_gethookmask(L) & LUA_MASKRET) {
1215 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1216 return;
1217 }
1218
1219 /* restore the interrupt condition. */
1220 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1221
1222 /* If we interrupt the Lua processing in yieldable state, we yield.
1223 * If the state is not yieldable, trying yield causes an error.
1224 */
1225 if (lua_isyieldable(L))
Willy Tarreau9635e032018-10-16 17:52:55 +02001226 MAY_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001227
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001228 /* If we cannot yield, update the clock and check the timeout. */
1229 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001230 hlua->run_time += now_ms - hlua->start_time;
1231 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001232 lua_pushfstring(L, "execution timeout");
1233 WILL_LJMP(lua_error(L));
1234 }
1235
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001236 /* Update the start time. */
1237 hlua->start_time = now_ms;
1238
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001239 /* Try to interrupt the process at the end of the current
1240 * unyieldable function.
1241 */
1242 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001243}
1244
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001245/* This function start or resumes the Lua stack execution. If the flag
1246 * "yield_allowed" if no set and the LUA stack execution returns a yield
1247 * The function return an error.
1248 *
1249 * The function can returns 4 values:
1250 * - HLUA_E_OK : The execution is terminated without any errors.
1251 * - HLUA_E_AGAIN : The execution must continue at the next associated
1252 * task wakeup.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001253 * - HLUA_E_ERRMSG : An error has occurred, an error message is set in
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001254 * the top of the stack.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001255 * - HLUA_E_ERR : An error has occurred without error message.
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001256 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001257 * If an error occurred, the stack is renewed and it is ready to run new
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001258 * LUA code.
1259 */
1260static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1261{
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001262#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
1263 int nres;
1264#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001265 int ret;
1266 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001267 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001268
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001269 /* Initialise run time counter. */
1270 if (!HLUA_IS_RUNNING(lua))
1271 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001272
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001273 /* Lock the whole Lua execution. This lock must be before the
1274 * label "resume_execution".
1275 */
Thierry Fournier021d9862020-11-28 23:42:03 +01001276 if (lua->state_id == 0)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001277 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001278
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001279resume_execution:
1280
1281 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1282 * instructions. it is used for preventing infinite loops.
1283 */
1284 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1285
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001286 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001287 HLUA_SET_RUN(lua);
1288 HLUA_CLR_CTRLYIELD(lua);
1289 HLUA_CLR_WAKERESWR(lua);
1290 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001291
Christopher Fauletbc275a92020-02-26 14:55:16 +01001292 /* Update the start time and reset wake_time. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001293 lua->start_time = now_ms;
Christopher Fauletbc275a92020-02-26 14:55:16 +01001294 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001295
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001296 /* Call the function. */
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001297#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournier021d9862020-11-28 23:42:03 +01001298 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs, &nres);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001299#else
Thierry Fournier021d9862020-11-28 23:42:03 +01001300 ret = lua_resume(lua->T, hlua_states[lua->state_id], lua->nargs);
Christopher Faulet08ed98f2020-07-28 10:33:25 +02001301#endif
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001302 switch (ret) {
1303
1304 case LUA_OK:
1305 ret = HLUA_E_OK;
1306 break;
1307
1308 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001309 /* Check if the execution timeout is expired. It it is the case, we
1310 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001311 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001312 tv_update_date(0, 1);
1313 lua->run_time += now_ms - lua->start_time;
1314 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001315 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001316 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001317 break;
1318 }
1319 /* Process the forced yield. if the general yield is not allowed or
1320 * if no task were associated this the current Lua execution
1321 * coroutine, we resume the execution. Else we want to return in the
1322 * scheduler and we want to be waked up again, to continue the
1323 * current Lua execution. So we schedule our own task.
1324 */
1325 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001326 if (!yield_allowed || !lua->task)
1327 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001328 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001329 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001330 if (!yield_allowed) {
1331 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001332 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001333 break;
1334 }
1335 ret = HLUA_E_AGAIN;
1336 break;
1337
1338 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001339
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001340 /* Special exit case. The traditional exit is returned as an error
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001341 * because the errors ares the only one mean to return immediately
1342 * from and lua execution.
1343 */
1344 if (lua->flags & HLUA_EXIT) {
1345 ret = HLUA_E_OK;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01001346 hlua_ctx_renew(lua, 1);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001347 break;
1348 }
1349
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001350 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001351 if (!lua_checkstack(lua->T, 1)) {
1352 ret = HLUA_E_ERR;
1353 break;
1354 }
1355 msg = lua_tostring(lua->T, -1);
1356 lua_settop(lua->T, 0); /* Empty the stack. */
1357 lua_pop(lua->T, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01001358 trace = hlua_traceback(lua->T, ", ");
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001359 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001360 lua_pushfstring(lua->T, "[state-id %d] runtime error: %s from %s", lua->state_id, msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001361 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001362 lua_pushfstring(lua->T, "[state-id %d] unknown runtime error from %s", lua->state_id, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001363 ret = HLUA_E_ERRMSG;
1364 break;
1365
1366 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001367 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001368 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001369 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001370 break;
1371
1372 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001373 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001374 if (!lua_checkstack(lua->T, 1)) {
1375 ret = HLUA_E_ERR;
1376 break;
1377 }
1378 msg = lua_tostring(lua->T, -1);
1379 lua_settop(lua->T, 0); /* Empty the stack. */
1380 lua_pop(lua->T, 1);
1381 if (msg)
Thierry Fournier46278ff2020-11-29 11:48:12 +01001382 lua_pushfstring(lua->T, "[state-id %d] message handler error: %s", lua->state_id, msg);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001383 else
Thierry Fournier46278ff2020-11-29 11:48:12 +01001384 lua_pushfstring(lua->T, "[state-id %d] message handler error", lua->state_id);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001385 ret = HLUA_E_ERRMSG;
1386 break;
1387
1388 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001389 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001390 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001391 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001392 break;
1393 }
1394
1395 switch (ret) {
1396 case HLUA_E_AGAIN:
1397 break;
1398
1399 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001400 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001401 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001402 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001403 break;
1404
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001405 case HLUA_E_ETMOUT:
1406 case HLUA_E_NOMEM:
1407 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001408 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001409 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001410 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001411 hlua_ctx_renew(lua, 0);
1412 break;
1413
1414 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001415 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001416 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001417 break;
1418 }
1419
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001420 /* This is the main exit point, remove the Lua lock. */
Thierry Fournier021d9862020-11-28 23:42:03 +01001421 if (lua->state_id == 0)
Thierry Fournier7cbe5042020-11-28 17:02:21 +01001422 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001423
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001424 return ret;
1425}
1426
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001427/* This function exit the current code. */
1428__LJMP static int hlua_done(lua_State *L)
1429{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001430 struct hlua *hlua;
1431
1432 /* Get hlua struct, or NULL if we execute from main lua state */
1433 hlua = hlua_gethlua(L);
1434 if (!hlua)
1435 return 0;
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001436
1437 hlua->flags |= HLUA_EXIT;
1438 WILL_LJMP(lua_error(L));
1439
1440 return 0;
1441}
1442
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001443/* This function is an LUA binding. It provides a function
1444 * for deleting ACL from a referenced ACL file.
1445 */
1446__LJMP static int hlua_del_acl(lua_State *L)
1447{
1448 const char *name;
1449 const char *key;
1450 struct pat_ref *ref;
1451
1452 MAY_LJMP(check_args(L, 2, "del_acl"));
1453
1454 name = MAY_LJMP(luaL_checkstring(L, 1));
1455 key = MAY_LJMP(luaL_checkstring(L, 2));
1456
1457 ref = pat_ref_lookup(name);
1458 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001459 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001460
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001461 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001462 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001463 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001464 return 0;
1465}
1466
1467/* This function is an LUA binding. It provides a function
1468 * for deleting map entry from a referenced map file.
1469 */
1470static int hlua_del_map(lua_State *L)
1471{
1472 const char *name;
1473 const char *key;
1474 struct pat_ref *ref;
1475
1476 MAY_LJMP(check_args(L, 2, "del_map"));
1477
1478 name = MAY_LJMP(luaL_checkstring(L, 1));
1479 key = MAY_LJMP(luaL_checkstring(L, 2));
1480
1481 ref = pat_ref_lookup(name);
1482 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001483 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001484
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001485 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001486 pat_ref_delete(ref, key);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001487 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001488 return 0;
1489}
1490
1491/* This function is an LUA binding. It provides a function
1492 * for adding ACL pattern from a referenced ACL file.
1493 */
1494static int hlua_add_acl(lua_State *L)
1495{
1496 const char *name;
1497 const char *key;
1498 struct pat_ref *ref;
1499
1500 MAY_LJMP(check_args(L, 2, "add_acl"));
1501
1502 name = MAY_LJMP(luaL_checkstring(L, 1));
1503 key = MAY_LJMP(luaL_checkstring(L, 2));
1504
1505 ref = pat_ref_lookup(name);
1506 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001507 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001508
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001509 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001510 if (pat_ref_find_elt(ref, key) == NULL)
1511 pat_ref_add(ref, key, NULL, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001512 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001513 return 0;
1514}
1515
1516/* This function is an LUA binding. It provides a function
1517 * for setting map pattern and sample from a referenced map
1518 * file.
1519 */
1520static int hlua_set_map(lua_State *L)
1521{
1522 const char *name;
1523 const char *key;
1524 const char *value;
1525 struct pat_ref *ref;
1526
1527 MAY_LJMP(check_args(L, 3, "set_map"));
1528
1529 name = MAY_LJMP(luaL_checkstring(L, 1));
1530 key = MAY_LJMP(luaL_checkstring(L, 2));
1531 value = MAY_LJMP(luaL_checkstring(L, 3));
1532
1533 ref = pat_ref_lookup(name);
1534 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001535 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001536
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001537 HA_SPIN_LOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001538 if (pat_ref_find_elt(ref, key) != NULL)
1539 pat_ref_set(ref, key, value, NULL);
1540 else
1541 pat_ref_add(ref, key, value, NULL);
Christopher Faulet5cf2dfc2020-06-03 18:39:16 +02001542 HA_SPIN_UNLOCK(PATREF_LOCK, &ref->lock);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001543 return 0;
1544}
1545
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001546/* A class is a lot of memory that contain data. This data can be a table,
1547 * an integer or user data. This data is associated with a metatable. This
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05001548 * metatable have an original version registered in the global context with
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001549 * the name of the object (_G[<name>] = <metable> ).
1550 *
1551 * A metable is a table that modify the standard behavior of a standard
1552 * access to the associated data. The entries of this new metatable are
1553 * defined as is:
1554 *
1555 * http://lua-users.org/wiki/MetatableEvents
1556 *
1557 * __index
1558 *
1559 * we access an absent field in a table, the result is nil. This is
1560 * true, but it is not the whole truth. Actually, such access triggers
1561 * the interpreter to look for an __index metamethod: If there is no
1562 * such method, as usually happens, then the access results in nil;
1563 * otherwise, the metamethod will provide the result.
1564 *
1565 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1566 * the key does not appear in the table, but the metatable has an __index
1567 * property:
1568 *
1569 * - if the value is a function, the function is called, passing in the
1570 * table and the key; the return value of that function is returned as
1571 * the result.
1572 *
1573 * - if the value is another table, the value of the key in that table is
1574 * asked for and returned (and if it doesn't exist in that table, but that
1575 * table's metatable has an __index property, then it continues on up)
1576 *
1577 * - Use "rawget(myTable,key)" to skip this metamethod.
1578 *
1579 * http://www.lua.org/pil/13.4.1.html
1580 *
1581 * __newindex
1582 *
1583 * Like __index, but control property assignment.
1584 *
1585 * __mode - Control weak references. A string value with one or both
1586 * of the characters 'k' and 'v' which specifies that the the
1587 * keys and/or values in the table are weak references.
1588 *
1589 * __call - Treat a table like a function. When a table is followed by
1590 * parenthesis such as "myTable( 'foo' )" and the metatable has
1591 * a __call key pointing to a function, that function is invoked
1592 * (passing any specified arguments) and the return value is
1593 * returned.
1594 *
1595 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1596 * called, if the metatable for myTable has a __metatable
1597 * key, the value of that key is returned instead of the
1598 * actual metatable.
1599 *
1600 * __tostring - Control string representation. When the builtin
1601 * "tostring( myTable )" function is called, if the metatable
1602 * for myTable has a __tostring property set to a function,
1603 * that function is invoked (passing myTable to it) and the
1604 * return value is used as the string representation.
1605 *
1606 * __len - Control table length. When the table length is requested using
1607 * the length operator ( '#' ), if the metatable for myTable has
1608 * a __len key pointing to a function, that function is invoked
1609 * (passing myTable to it) and the return value used as the value
1610 * of "#myTable".
1611 *
1612 * __gc - Userdata finalizer code. When userdata is set to be garbage
1613 * collected, if the metatable has a __gc field pointing to a
1614 * function, that function is first invoked, passing the userdata
1615 * to it. The __gc metamethod is not called for tables.
1616 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1617 *
1618 * Special metamethods for redefining standard operators:
1619 * http://www.lua.org/pil/13.1.html
1620 *
1621 * __add "+"
1622 * __sub "-"
1623 * __mul "*"
1624 * __div "/"
1625 * __unm "!"
1626 * __pow "^"
1627 * __concat ".."
1628 *
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001629 * Special methods for redefining standard relations
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001630 * http://www.lua.org/pil/13.2.html
1631 *
1632 * __eq "=="
1633 * __lt "<"
1634 * __le "<="
1635 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001636
1637/*
1638 *
1639 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001640 * Class Map
1641 *
1642 *
1643 */
1644
1645/* Returns a struct hlua_map if the stack entry "ud" is
1646 * a class session, otherwise it throws an error.
1647 */
1648__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1649{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001650 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001651}
1652
1653/* This function is the map constructor. It don't need
1654 * the class Map object. It creates and return a new Map
1655 * object. It must be called only during "body" or "init"
1656 * context because it process some filesystem accesses.
1657 */
1658__LJMP static int hlua_map_new(struct lua_State *L)
1659{
1660 const char *fn;
1661 int match = PAT_MATCH_STR;
1662 struct sample_conv conv;
1663 const char *file = "";
1664 int line = 0;
1665 lua_Debug ar;
1666 char *err = NULL;
1667 struct arg args[2];
1668
1669 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1670 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1671
1672 fn = MAY_LJMP(luaL_checkstring(L, 1));
1673
1674 if (lua_gettop(L) >= 2) {
1675 match = MAY_LJMP(luaL_checkinteger(L, 2));
1676 if (match < 0 || match >= PAT_MATCH_NUM)
1677 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1678 }
1679
1680 /* Get Lua filename and line number. */
1681 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1682 lua_getinfo(L, "Sl", &ar); /* get info about it */
1683 if (ar.currentline > 0) { /* is there info? */
1684 file = ar.short_src;
1685 line = ar.currentline;
1686 }
1687 }
1688
1689 /* fill fake sample_conv struct. */
1690 conv.kw = ""; /* unused. */
1691 conv.process = NULL; /* unused. */
1692 conv.arg_mask = 0; /* unused. */
1693 conv.val_args = NULL; /* unused. */
1694 conv.out_type = SMP_T_STR;
1695 conv.private = (void *)(long)match;
1696 switch (match) {
1697 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1698 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1699 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1700 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1701 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1702 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1703 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001704 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001705 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1706 default:
1707 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1708 }
1709
1710 /* fill fake args. */
1711 args[0].type = ARGT_STR;
Christopher Faulet73292e92020-08-06 08:40:09 +02001712 args[0].data.str.area = strdup(fn);
1713 args[0].data.str.data = strlen(fn);
1714 args[0].data.str.size = args[0].data.str.data+1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001715 args[1].type = ARGT_STOP;
1716
1717 /* load the map. */
1718 if (!sample_load_map(args, &conv, file, line, &err)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001719 /* error case: we can't use luaL_error because we must
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001720 * free the err variable.
1721 */
1722 luaL_where(L, 1);
1723 lua_pushfstring(L, "'new': %s.", err);
1724 lua_concat(L, 2);
1725 free(err);
Christopher Faulet6ad7df42020-08-07 11:45:18 +02001726 chunk_destroy(&args[0].data.str);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001727 WILL_LJMP(lua_error(L));
1728 }
1729
1730 /* create the lua object. */
1731 lua_newtable(L);
1732 lua_pushlightuserdata(L, args[0].data.map);
1733 lua_rawseti(L, -2, 0);
1734
1735 /* Pop a class Map metatable and affect it to the userdata. */
1736 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1737 lua_setmetatable(L, -2);
1738
1739
1740 return 1;
1741}
1742
1743__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1744{
1745 struct map_descriptor *desc;
1746 struct pattern *pat;
1747 struct sample smp;
1748
1749 MAY_LJMP(check_args(L, 2, "lookup"));
1750 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001751 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001752 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001753 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001754 }
1755 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001756 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001757 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001758 smp.data.u.str.area = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.data));
Thierry Fournier91dc0c02020-11-10 20:38:20 +01001759 smp.data.u.str.size = smp.data.u.str.data + 1;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001760 }
1761
1762 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001763 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001764 if (str)
1765 lua_pushstring(L, "");
1766 else
1767 lua_pushnil(L);
1768 return 1;
1769 }
1770
1771 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001772 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001773 return 1;
1774}
1775
1776__LJMP static int hlua_map_lookup(struct lua_State *L)
1777{
1778 return _hlua_map_lookup(L, 0);
1779}
1780
1781__LJMP static int hlua_map_slookup(struct lua_State *L)
1782{
1783 return _hlua_map_lookup(L, 1);
1784}
1785
1786/*
1787 *
1788 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001789 * Class Socket
1790 *
1791 *
1792 */
1793
1794__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1795{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001796 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001797}
1798
1799/* This function is the handler called for each I/O on the established
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001800 * connection. It is used for notify space available to send or data
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001801 * received.
1802 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001803static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001804{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001805 struct stream_interface *si = appctx->owner;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001806
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001807 if (appctx->ctx.hlua_cosocket.die) {
1808 si_shutw(si);
1809 si_shutr(si);
1810 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001811 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1812 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001813 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1814 }
1815
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001816 /* If we can't write, wakeup the pending write signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001817 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001818 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001819
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05001820 /* If we can't read, wakeup the pending read signals. */
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001821 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001822 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001823
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001824 /* if the connection is not established, inform the stream that we want
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001825 * to be notified whenever the connection completes.
1826 */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02001827 if (si_opposite(si)->state < SI_ST_EST) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01001828 si_cant_get(si);
Willy Tarreau12c24232018-12-06 15:29:50 +01001829 si_rx_conn_blk(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01001830 si_rx_endp_more(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001831 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001832 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001833
1834 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001835 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001836
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08001837 /* Wake the tasks which wants to write if the buffer have available space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001838 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001839 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001840
1841 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001842 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001843 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001844
1845 /* Some data were injected in the buffer, notify the stream
1846 * interface.
1847 */
1848 if (!channel_is_empty(si_ic(si)))
Willy Tarreau14bfe9a2018-12-19 15:19:27 +01001849 si_update(si);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001850
1851 /* If write notifications are registered, we considers we want
Willy Tarreau3367d412018-11-15 10:57:41 +01001852 * to write, so we clear the blocking flag.
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001853 */
1854 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
Willy Tarreau3367d412018-11-15 10:57:41 +01001855 si_rx_endp_more(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001856}
1857
Willy Tarreau87b09662015-04-03 00:22:06 +02001858/* This function is called when the "struct stream" is destroyed.
1859 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001860 * Wake all the pending signals.
1861 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001862static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001863{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001864 struct xref *peer;
1865
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001866 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001867 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1868 if (peer)
1869 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001870
1871 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001872 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1873 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001874}
1875
1876/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001877 * uses this object. If the stream does not exists, just quit.
1878 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001879 * pending signal can rest in the read and write lists. destroy
1880 * it.
1881 */
1882__LJMP static int hlua_socket_gc(lua_State *L)
1883{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001884 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001885 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001886 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001887
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001888 MAY_LJMP(check_args(L, 1, "__gc"));
1889
1890 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001891 peer = xref_get_peer_and_lock(&socket->xref);
1892 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001893 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001894 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001895
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001896 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001897 appctx->ctx.hlua_cosocket.die = 1;
1898 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001899
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001900 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001901 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001902 return 0;
1903}
1904
1905/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001906 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001907 */
sada05ed3302018-05-11 11:48:18 -07001908__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001909{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001910 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001911 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001912 struct xref *peer;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001913 struct hlua *hlua;
1914
1915 /* Get hlua struct, or NULL if we execute from main lua state */
1916 hlua = hlua_gethlua(L);
1917 if (!hlua)
1918 return 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001919
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001920 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001921
1922 /* Check if we run on the same thread than the xreator thread.
1923 * We cannot access to the socket if the thread is different.
1924 */
1925 if (socket->tid != tid)
1926 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1927
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001928 peer = xref_get_peer_and_lock(&socket->xref);
1929 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001930 return 0;
Willy Tarreauf31af932020-01-14 09:59:38 +01001931
1932 hlua->gc_count--;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001933 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001934
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001935 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001936 appctx->ctx.hlua_cosocket.die = 1;
1937 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001938
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001939 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001940 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001941 return 0;
1942}
1943
sada05ed3302018-05-11 11:48:18 -07001944/* The close function calls close_helper.
1945 */
1946__LJMP static int hlua_socket_close(lua_State *L)
1947{
1948 MAY_LJMP(check_args(L, 1, "close"));
1949 return hlua_socket_close_helper(L);
1950}
1951
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001952/* This Lua function assumes that the stack contain three parameters.
1953 * 1 - USERDATA containing a struct socket
1954 * 2 - INTEGER with values of the macro defined below
1955 * If the integer is -1, we must read at most one line.
1956 * If the integer is -2, we ust read all the data until the
1957 * end of the stream.
1958 * If the integer is positive value, we must read a number of
1959 * bytes corresponding to this value.
1960 */
1961#define HLSR_READ_LINE (-1)
1962#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001963__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001964{
1965 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1966 int wanted = lua_tointeger(L, 2);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001967 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001968 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001969 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001970 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001971 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001972 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001973 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001974 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001975 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001976 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001977 struct stream_interface *si;
1978 struct stream *s;
1979 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001980 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001981
Thierry Fournier4234dbd2020-11-28 13:18:23 +01001982 /* Get hlua struct, or NULL if we execute from main lua state */
1983 hlua = hlua_gethlua(L);
1984
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001985 /* Check if this lua stack is schedulable. */
1986 if (!hlua || !hlua->task)
1987 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1988 "'frontend', 'backend' or 'task'"));
1989
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001990 /* Check if we run on the same thread than the xreator thread.
1991 * We cannot access to the socket if the thread is different.
1992 */
1993 if (socket->tid != tid)
1994 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1995
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001996 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001997 peer = xref_get_peer_and_lock(&socket->xref);
1998 if (!peer)
1999 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002000 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2001 si = appctx->owner;
2002 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002003
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002004 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002005 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002006 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002007 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002008 if (nblk < 0) /* Connection close. */
2009 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002010 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002011 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01002012
2013 /* remove final \r\n. */
2014 if (nblk == 1) {
2015 if (blk1[len1-1] == '\n') {
2016 len1--;
2017 skip_at_end++;
2018 if (blk1[len1-1] == '\r') {
2019 len1--;
2020 skip_at_end++;
2021 }
2022 }
2023 }
2024 else {
2025 if (blk2[len2-1] == '\n') {
2026 len2--;
2027 skip_at_end++;
2028 if (blk2[len2-1] == '\r') {
2029 len2--;
2030 skip_at_end++;
2031 }
2032 }
2033 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002034 }
2035
2036 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002037 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002038 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002039 if (nblk < 0) /* Connection close. */
2040 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002041 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002042 goto connection_empty;
2043 }
2044
2045 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002046 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002047 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002048 if (nblk < 0) /* Connection close. */
2049 goto connection_closed;
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002050 if (nblk == 0) /* No data available. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002051 goto connection_empty;
2052
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002053 missing_bytes = wanted - socket->b.n;
2054 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002055 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002056 len1 = missing_bytes;
2057 } if (nblk == 2 && len1 + len2 > missing_bytes)
2058 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002059 }
2060
2061 len = len1;
2062
2063 luaL_addlstring(&socket->b, blk1, len1);
2064 if (nblk == 2) {
2065 len += len2;
2066 luaL_addlstring(&socket->b, blk2, len2);
2067 }
2068
2069 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002070 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002071
2072 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02002073 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002074
2075 /* If the pattern reclaim to read all the data
2076 * in the connection, got out.
2077 */
2078 if (wanted == HLSR_READ_ALL)
2079 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02002080 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002081 goto connection_empty;
2082
2083 /* Return result. */
2084 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002085 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086 return 1;
2087
2088connection_closed:
2089
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002090 xref_unlock(&socket->xref, peer);
2091
2092no_peer:
2093
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002094 /* If the buffer containds data. */
2095 if (socket->b.n > 0) {
2096 luaL_pushresult(&socket->b);
2097 return 1;
2098 }
2099 lua_pushnil(L);
2100 lua_pushstring(L, "connection closed.");
2101 return 2;
2102
2103connection_empty:
2104
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002105 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
2106 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002107 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002108 }
2109 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002110 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002111 return 0;
2112}
2113
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002114/* This Lua function gets two parameters. The first one can be string
2115 * or a number. If the string is "*l", the user requires one line. If
2116 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002117 * If the value is a number, the user require a number of bytes equal
2118 * to the value. The default value is "*l" (a line).
2119 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002120 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002121 * integer takes this values:
2122 * -1 : read a line
2123 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002124 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002125 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002126 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002127 * concatenated with the read data.
2128 */
2129__LJMP static int hlua_socket_receive(struct lua_State *L)
2130{
2131 int wanted = HLSR_READ_LINE;
2132 const char *pattern;
2133 int type;
2134 char *error;
2135 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002136 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002137
2138 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
2139 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
2140
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002141 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002143 /* Check if we run on the same thread than the xreator thread.
2144 * We cannot access to the socket if the thread is different.
2145 */
2146 if (socket->tid != tid)
2147 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2148
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002149 /* check for pattern. */
2150 if (lua_gettop(L) >= 2) {
2151 type = lua_type(L, 2);
2152 if (type == LUA_TSTRING) {
2153 pattern = lua_tostring(L, 2);
2154 if (strcmp(pattern, "*a") == 0)
2155 wanted = HLSR_READ_ALL;
2156 else if (strcmp(pattern, "*l") == 0)
2157 wanted = HLSR_READ_LINE;
2158 else {
2159 wanted = strtoll(pattern, &error, 10);
2160 if (*error != '\0')
2161 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
2162 }
2163 }
2164 else if (type == LUA_TNUMBER) {
2165 wanted = lua_tointeger(L, 2);
2166 if (wanted < 0)
2167 WILL_LJMP(luaL_error(L, "Unsupported size."));
2168 }
2169 }
2170
2171 /* Set pattern. */
2172 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01002173
2174 /* Check if we would replace the top by itself. */
2175 if (lua_gettop(L) != 2)
2176 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002177
Tim Duesterhusb33754c2018-01-04 19:32:14 +01002178 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002179 luaL_buffinit(L, &socket->b);
2180
2181 /* Check prefix. */
2182 if (lua_gettop(L) >= 3) {
2183 if (lua_type(L, 3) != LUA_TSTRING)
2184 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
2185 pattern = lua_tolstring(L, 3, &len);
2186 luaL_addlstring(&socket->b, pattern, len);
2187 }
2188
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002189 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002190}
2191
2192/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08002193 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002195static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002196{
2197 struct hlua_socket *socket;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002198 struct hlua *hlua;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002199 struct appctx *appctx;
2200 size_t buf_len;
2201 const char *buf;
2202 int len;
2203 int send_len;
2204 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002205 struct xref *peer;
2206 struct stream_interface *si;
2207 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002208
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002209 /* Get hlua struct, or NULL if we execute from main lua state */
2210 hlua = hlua_gethlua(L);
2211
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002212 /* Check if this lua stack is schedulable. */
2213 if (!hlua || !hlua->task)
2214 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
2215 "'frontend', 'backend' or 'task'"));
2216
2217 /* Get object */
2218 socket = MAY_LJMP(hlua_checksocket(L, 1));
2219 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002220 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002221
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002222 /* Check if we run on the same thread than the xreator thread.
2223 * We cannot access to the socket if the thread is different.
2224 */
2225 if (socket->tid != tid)
2226 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2227
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002228 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002229 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002230 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002231 lua_pushinteger(L, -1);
2232 return 1;
2233 }
2234 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2235 si = appctx->owner;
2236 s = si_strm(si);
2237
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002238 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002239 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002240 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002241 lua_pushinteger(L, -1);
2242 return 1;
2243 }
2244
2245 /* Update the input buffer data. */
2246 buf += sent;
2247 send_len = buf_len - sent;
2248
2249 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002250 if (sent >= buf_len) {
2251 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002252 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002253 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002254
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002255 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002256 * the request buffer if its not required.
2257 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002258 if (s->req.buf.size == 0) {
Willy Tarreau581abd32018-10-25 10:21:41 +02002259 if (!si_alloc_ibuf(si, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002260 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002261 }
2262
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002263 /* Check for available space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002264 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002265 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002266 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002267 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002268
2269 /* send data */
2270 if (len < send_len)
2271 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002272 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002273
2274 /* "Not enough space" (-1), "Buffer too little to contain
2275 * the data" (-2) are not expected because the available length
2276 * is tested.
2277 * Other unknown error are also not expected.
2278 */
2279 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002280 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002281 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002282
sada05ed3302018-05-11 11:48:18 -07002283 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002284 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002285 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002286 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002287 return 1;
2288 }
2289
2290 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002291 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002292
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002293 s->req.rex = TICK_ETERNITY;
2294 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002295
2296 /* Update length sent. */
2297 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002298 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002299
2300 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002301 if (sent + len >= buf_len) {
2302 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002303 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002304 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002305
2306hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002307 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2308 xref_unlock(&socket->xref, peer);
2309 WILL_LJMP(luaL_error(L, "out of memory"));
2310 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002311 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002312 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313 return 0;
2314}
2315
2316/* This function initiate the send of data. It just check the input
2317 * parameters and push an integer in the Lua stack that contain the
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08002318 * amount of data written to the buffer. This is used by the function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002319 * "hlua_socket_write_yield" that can yield.
2320 *
2321 * The Lua function gets between 3 and 4 parameters. The first one is
2322 * the associated object. The second is a string buffer. The third is
2323 * a facultative integer that represents where is the buffer position
2324 * of the start of the data that can send. The first byte is the
2325 * position "1". The default value is "1". The fourth argument is a
2326 * facultative integer that represents where is the buffer position
2327 * of the end of the data that can send. The default is the last byte.
2328 */
2329static int hlua_socket_send(struct lua_State *L)
2330{
2331 int i;
2332 int j;
2333 const char *buf;
2334 size_t buf_len;
2335
2336 /* Check number of arguments. */
2337 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2338 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2339
2340 /* Get the string. */
2341 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2342
2343 /* Get and check j. */
2344 if (lua_gettop(L) == 4) {
2345 j = MAY_LJMP(luaL_checkinteger(L, 4));
2346 if (j < 0)
2347 j = buf_len + j + 1;
2348 if (j > buf_len)
2349 j = buf_len + 1;
2350 lua_pop(L, 1);
2351 }
2352 else
2353 j = buf_len;
2354
2355 /* Get and check i. */
2356 if (lua_gettop(L) == 3) {
2357 i = MAY_LJMP(luaL_checkinteger(L, 3));
2358 if (i < 0)
2359 i = buf_len + i + 1;
2360 if (i > buf_len)
2361 i = buf_len + 1;
2362 lua_pop(L, 1);
2363 } else
2364 i = 1;
2365
2366 /* Check bth i and j. */
2367 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002368 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002369 return 1;
2370 }
2371 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002372 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002373 return 1;
2374 }
2375 if (i == 0)
2376 i = 1;
2377 if (j == 0)
2378 j = 1;
2379
2380 /* Pop the string. */
2381 lua_pop(L, 1);
2382
2383 /* Update the buffer length. */
2384 buf += i - 1;
2385 buf_len = j - i + 1;
2386 lua_pushlstring(L, buf, buf_len);
2387
2388 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002389 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002390
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002391 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002392}
2393
Willy Tarreau22b0a682015-06-17 19:43:49 +02002394#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002395__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2396{
2397 static char buffer[SOCKET_INFO_MAX_LEN];
2398 int ret;
2399 int len;
2400 char *p;
2401
2402 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2403 if (ret <= 0) {
2404 lua_pushnil(L);
2405 return 1;
2406 }
2407
2408 if (ret == AF_UNIX) {
2409 lua_pushstring(L, buffer+1);
2410 return 1;
2411 }
2412 else if (ret == AF_INET6) {
2413 buffer[0] = '[';
2414 len = strlen(buffer);
2415 buffer[len] = ']';
2416 len++;
2417 buffer[len] = ':';
2418 len++;
2419 p = buffer;
2420 }
2421 else if (ret == AF_INET) {
2422 p = buffer + 1;
2423 len = strlen(p);
2424 p[len] = ':';
2425 len++;
2426 }
2427 else {
2428 lua_pushnil(L);
2429 return 1;
2430 }
2431
2432 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2433 lua_pushnil(L);
2434 return 1;
2435 }
2436
2437 lua_pushstring(L, p);
2438 return 1;
2439}
2440
2441/* Returns information about the peer of the connection. */
2442__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2443{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002444 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002445 struct xref *peer;
2446 struct appctx *appctx;
2447 struct stream_interface *si;
2448 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002449 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002450
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002451 MAY_LJMP(check_args(L, 1, "getpeername"));
2452
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002453 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002454
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002455 /* Check if we run on the same thread than the xreator thread.
2456 * We cannot access to the socket if the thread is different.
2457 */
2458 if (socket->tid != tid)
2459 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2460
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002461 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002462 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002463 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002464 lua_pushnil(L);
2465 return 1;
2466 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002467 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2468 si = appctx->owner;
2469 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002470
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002471 if (!s->target_addr) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002472 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002473 lua_pushnil(L);
2474 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002475 }
2476
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002477 ret = MAY_LJMP(hlua_socket_info(L, s->target_addr));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002478 xref_unlock(&socket->xref, peer);
2479 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002480}
2481
2482/* Returns information about my connection side. */
2483static int hlua_socket_getsockname(struct lua_State *L)
2484{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002485 struct hlua_socket *socket;
2486 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002487 struct appctx *appctx;
2488 struct xref *peer;
2489 struct stream_interface *si;
2490 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002491 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002492
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002493 MAY_LJMP(check_args(L, 1, "getsockname"));
2494
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002495 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002496
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002497 /* Check if we run on the same thread than the xreator thread.
2498 * We cannot access to the socket if the thread is different.
2499 */
2500 if (socket->tid != tid)
2501 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2502
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002503 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002504 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002505 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002506 lua_pushnil(L);
2507 return 1;
2508 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002509 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2510 si = appctx->owner;
2511 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002512
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002513 conn = cs_conn(objt_cs(s->si[1].end));
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002514 if (!conn || !conn_get_src(conn)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002515 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002516 lua_pushnil(L);
2517 return 1;
2518 }
2519
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002520 ret = hlua_socket_info(L, conn->src);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002521 xref_unlock(&socket->xref, peer);
2522 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002523}
2524
2525/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002526static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002527 .obj_type = OBJ_TYPE_APPLET,
2528 .name = "<LUA_TCP>",
2529 .fct = hlua_socket_handler,
2530 .release = hlua_socket_release,
2531};
2532
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002533__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002534{
2535 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002536 struct hlua *hlua;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002537 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002538 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002539 struct stream_interface *si;
2540 struct stream *s;
2541
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002542 /* Get hlua struct, or NULL if we execute from main lua state */
2543 hlua = hlua_gethlua(L);
2544 if (!hlua)
2545 return 0;
2546
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002547 /* Check if we run on the same thread than the xreator thread.
2548 * We cannot access to the socket if the thread is different.
2549 */
2550 if (socket->tid != tid)
2551 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2552
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002553 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002554 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002555 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002556 lua_pushnil(L);
2557 lua_pushstring(L, "Can't connect");
2558 return 2;
2559 }
2560 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2561 si = appctx->owner;
2562 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002563
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002564 /* Check if we run on the same thread than the xreator thread.
2565 * We cannot access to the socket if the thread is different.
2566 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002567 if (socket->tid != tid) {
2568 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002569 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002570 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002571
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002572 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002573 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002574 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002575 lua_pushnil(L);
2576 lua_pushstring(L, "Can't connect");
2577 return 2;
2578 }
2579
Willy Tarreaue09101e2018-10-16 17:37:12 +02002580 appctx = __objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002581
2582 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002583 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002584 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002585 lua_pushinteger(L, 1);
2586 return 1;
2587 }
2588
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002589 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2590 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002591 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002592 }
2593 xref_unlock(&socket->xref, peer);
Willy Tarreau9635e032018-10-16 17:52:55 +02002594 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002595 return 0;
2596}
2597
2598/* This function fail or initite the connection. */
2599__LJMP static int hlua_socket_connect(struct lua_State *L)
2600{
2601 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002602 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002603 const char *ip;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002604 struct hlua *hlua;
2605 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002606 int low, high;
2607 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002608 struct xref *peer;
2609 struct stream_interface *si;
2610 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002611
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002612 if (lua_gettop(L) < 2)
2613 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002614
2615 /* Get args. */
2616 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002617
2618 /* Check if we run on the same thread than the xreator thread.
2619 * We cannot access to the socket if the thread is different.
2620 */
2621 if (socket->tid != tid)
2622 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2623
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002624 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002625 if (lua_gettop(L) >= 3) {
2626 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002627 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002628
Tim Duesterhus6edab862018-01-06 19:04:45 +01002629 /* Force the ip to end with a colon, to support IPv6 addresses
2630 * that are not enclosed within square brackets.
2631 */
2632 if (port > 0) {
2633 luaL_buffinit(L, &b);
2634 luaL_addstring(&b, ip);
2635 luaL_addchar(&b, ':');
2636 luaL_pushresult(&b);
2637 ip = lua_tolstring(L, lua_gettop(L), NULL);
2638 }
2639 }
2640
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002641 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002642 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002643 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002644 lua_pushnil(L);
2645 return 1;
2646 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002647
2648 /* Parse ip address. */
Willy Tarreau5fc93282020-09-16 18:25:03 +02002649 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, NULL, NULL, PA_O_PORT_OK | PA_O_STREAM);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002650 if (!addr) {
2651 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002652 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002653 }
Willy Tarreau9da9a6f2019-07-17 14:49:44 +02002654
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002655 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002656 if (low == 0) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002657 if (addr->ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002658 if (port == -1) {
2659 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002660 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002661 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002662 ((struct sockaddr_in *)addr)->sin_port = htons(port);
2663 } else if (addr->ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002664 if (port == -1) {
2665 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002666 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002667 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002668 ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002669 }
2670 }
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002671
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002672 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2673 si = appctx->owner;
2674 s = si_strm(si);
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002675
Willy Tarreau9b7587a2020-10-15 07:32:10 +02002676 if (!sockaddr_alloc(&s->target_addr, addr, sizeof(*addr))) {
Willy Tarreau1c8d32b2019-07-18 15:47:45 +02002677 xref_unlock(&socket->xref, peer);
2678 WILL_LJMP(luaL_error(L, "connect: internal error"));
2679 }
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002680 s->flags |= SF_ADDR_SET;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002681
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002682 /* Get hlua struct, or NULL if we execute from main lua state */
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002683 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01002684 if (!hlua)
2685 return 0;
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002686
2687 /* inform the stream that we want to be notified whenever the
2688 * connection completes.
2689 */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01002690 si_cant_get(&s->si[0]);
Willy Tarreau3367d412018-11-15 10:57:41 +01002691 si_rx_endp_more(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002692 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002693
Willy Tarreauf31af932020-01-14 09:59:38 +01002694 hlua->gc_count++;
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002695
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002696 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2697 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002698 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002699 }
2700 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002701
2702 task_wakeup(s->task, TASK_WOKEN_INIT);
2703 /* Return yield waiting for connection. */
2704
Willy Tarreau9635e032018-10-16 17:52:55 +02002705 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002706
2707 return 0;
2708}
2709
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002710#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002711__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2712{
2713 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002714 struct xref *peer;
2715 struct appctx *appctx;
2716 struct stream_interface *si;
2717 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002718
2719 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2720 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002721
2722 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002723 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002724 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002725 lua_pushnil(L);
2726 return 1;
2727 }
2728 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2729 si = appctx->owner;
2730 s = si_strm(si);
2731
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002732 s->target = &socket_ssl->obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002733 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002734 return MAY_LJMP(hlua_socket_connect(L));
2735}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002736#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002737
2738__LJMP static int hlua_socket_setoption(struct lua_State *L)
2739{
2740 return 0;
2741}
2742
2743__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2744{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002745 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002746 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002747 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002748 struct xref *peer;
2749 struct appctx *appctx;
2750 struct stream_interface *si;
2751 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002752
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002753 MAY_LJMP(check_args(L, 2, "settimeout"));
2754
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002755 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002756
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002757 /* convert the timeout to millis */
2758 dtmout = MAY_LJMP(luaL_checknumber(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002759
Thierry Fournier17a921b2018-03-08 09:59:02 +01002760 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002761 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002762 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2763
Mark Lakes56cc1252018-03-27 09:48:06 +02002764 if (dtmout > INT_MAX) /* overflow check */
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002765 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d ms", INT_MAX));
Mark Lakes56cc1252018-03-27 09:48:06 +02002766
2767 tmout = MS_TO_TICKS((int)dtmout);
Cyril Bonté7ee465f2018-08-19 22:08:50 +02002768 if (tmout == 0)
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002769 tmout++; /* very small timeouts are adjusted to a minimum of 1ms */
Mark Lakes56cc1252018-03-27 09:48:06 +02002770
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002771 /* Check if we run on the same thread than the xreator thread.
2772 * We cannot access to the socket if the thread is different.
2773 */
2774 if (socket->tid != tid)
2775 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2776
Mark Lakes56cc1252018-03-27 09:48:06 +02002777 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002778 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002779 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002780 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2781 WILL_LJMP(lua_error(L));
2782 return 0;
2783 }
2784 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2785 si = appctx->owner;
2786 s = si_strm(si);
2787
Cyril Bonté7bb63452018-08-17 23:51:02 +02002788 s->sess->fe->timeout.connect = tmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002789 s->req.rto = tmout;
2790 s->req.wto = tmout;
2791 s->res.rto = tmout;
2792 s->res.wto = tmout;
Cyril Bonté7bb63452018-08-17 23:51:02 +02002793 s->req.rex = tick_add_ifset(now_ms, tmout);
2794 s->req.wex = tick_add_ifset(now_ms, tmout);
2795 s->res.rex = tick_add_ifset(now_ms, tmout);
2796 s->res.wex = tick_add_ifset(now_ms, tmout);
2797
2798 s->task->expire = tick_add_ifset(now_ms, tmout);
2799 task_queue(s->task);
2800
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002801 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002802
Thierry Fourniere9636f12018-03-08 09:54:32 +01002803 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002804 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002805}
2806
2807__LJMP static int hlua_socket_new(lua_State *L)
2808{
2809 struct hlua_socket *socket;
2810 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002811 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002812 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002813
2814 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002815 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002816 hlua_pusherror(L, "socket: full stack");
2817 goto out_fail_conf;
2818 }
2819
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002820 /* Create the object: obj[0] = userdata. */
2821 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002822 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002823 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002824 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002825 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002826
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002827 /* Check if the various memory pools are initialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002828 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002829 hlua_pusherror(L, "socket: uninitialized pools.");
2830 goto out_fail_conf;
2831 }
2832
Willy Tarreau87b09662015-04-03 00:22:06 +02002833 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002834 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2835 lua_setmetatable(L, -2);
2836
Willy Tarreaud420a972015-04-06 00:39:18 +02002837 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002838 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002839 if (!appctx) {
2840 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002841 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002842 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002843
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002844 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002845 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002846 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2847 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002848
Willy Tarreaud420a972015-04-06 00:39:18 +02002849 /* Now create a session, task and stream for this applet */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01002850 sess = session_new(socket_proxy, NULL, &appctx->obj_type);
Willy Tarreaud420a972015-04-06 00:39:18 +02002851 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002852 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002853 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002854 }
2855
Christopher Faulet26256f82020-09-14 11:40:13 +02002856 strm = stream_new(sess, &appctx->obj_type, &BUF_NULL);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002857 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002858 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002859 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002860 }
2861
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002862 /* Initialise cross reference between stream and Lua socket object. */
2863 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002864
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002865 /* Configure "right" stream interface. this "si" is used to connect
2866 * and retrieve data from the server. The connection is initialized
2867 * with the "struct server".
2868 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002869 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002870
2871 /* Force destination server. */
Willy Tarreau5a0b25d2019-07-18 18:01:14 +02002872 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_BE_ASSIGNED;
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01002873 strm->target = &socket_tcp->obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002874
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002875 return 1;
2876
Willy Tarreaud420a972015-04-06 00:39:18 +02002877 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002878 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002879 out_fail_sess:
2880 appctx_free(appctx);
2881 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002882 WILL_LJMP(lua_error(L));
2883 return 0;
2884}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002885
2886/*
2887 *
2888 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002889 * Class Channel
2890 *
2891 *
2892 */
2893
2894/* Returns the struct hlua_channel join to the class channel in the
2895 * stack entry "ud" or throws an argument error.
2896 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002897__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002898{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002899 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002900}
2901
Willy Tarreau47860ed2015-03-10 14:07:50 +01002902/* Pushes the channel onto the top of the stack. If the stask does not have a
2903 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002904 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002905static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002906{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002907 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002908 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002909 return 0;
2910
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002911 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002912 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002913 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002914
2915 /* Pop a class sesison metatable and affect it to the userdata. */
2916 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2917 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002918 return 1;
2919}
2920
2921/* Duplicate all the data present in the input channel and put it
2922 * in a string LUA variables. Returns -1 and push a nil value in
2923 * the stack if the channel is closed and all the data are consumed,
2924 * returns 0 if no data are available, otherwise it returns the length
Ilya Shipitsind4259502020-04-08 01:07:56 +05002925 * of the built string.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002926 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002927static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002928{
2929 char *blk1;
2930 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002931 size_t len1;
2932 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002933 int ret;
2934 luaL_Buffer b;
2935
Willy Tarreau06d80a92017-10-19 14:32:15 +02002936 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002937 if (unlikely(ret == 0))
2938 return 0;
2939
2940 if (unlikely(ret < 0)) {
2941 lua_pushnil(L);
2942 return -1;
2943 }
2944
2945 luaL_buffinit(L, &b);
2946 luaL_addlstring(&b, blk1, len1);
2947 if (unlikely(ret == 2))
2948 luaL_addlstring(&b, blk2, len2);
2949 luaL_pushresult(&b);
2950
2951 if (unlikely(ret == 2))
2952 return len1 + len2;
2953 return len1;
2954}
2955
2956/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2957 * a yield. This function keep the data in the buffer.
2958 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002959__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002960{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002961 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002962
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002963 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2964
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01002965 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02002966 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01002967 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02002968 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01002969
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002970 if (_hlua_channel_dup(chn, L) == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02002971 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002972 return 1;
2973}
2974
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002975/* Check arguments for the function "hlua_channel_dup_yield". */
2976__LJMP static int hlua_channel_dup(lua_State *L)
2977{
2978 MAY_LJMP(check_args(L, 1, "dup"));
2979 MAY_LJMP(hlua_checkchannel(L, 1));
2980 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2981}
2982
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002983/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2984 * a yield. This function consumes the data in the buffer. It returns
2985 * a string containing the data or a nil pointer if no data are available
2986 * and the channel is closed.
2987 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002988__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002989{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002990 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002991 int ret;
2992
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002993 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002994
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01002995 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02002996 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01002997 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02002998 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01002999
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003000 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003001 if (unlikely(ret == 0))
Willy Tarreau9635e032018-10-16 17:52:55 +02003002 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003003
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003004 if (unlikely(ret == -1))
3005 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003006
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003007 b_sub(&chn->buf, ret);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003008 return 1;
3009}
3010
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003011/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003012__LJMP static int hlua_channel_get(lua_State *L)
3013{
3014 MAY_LJMP(check_args(L, 1, "get"));
3015 MAY_LJMP(hlua_checkchannel(L, 1));
3016 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
3017}
3018
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003019/* This functions consumes and returns one line. If the channel is closed,
3020 * and the last data does not contains a final '\n', the data are returned
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003021 * without the final '\n'. When no more data are available, it returns nil
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003022 * value.
3023 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003024__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003025{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003026 char *blk1;
3027 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003028 size_t len1;
3029 size_t len2;
3030 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01003031 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003032 int ret;
3033 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003034
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003035 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3036
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003037 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003038 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003039 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003040 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003041
Willy Tarreau06d80a92017-10-19 14:32:15 +02003042 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003043 if (ret == 0)
Willy Tarreau9635e032018-10-16 17:52:55 +02003044 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003045
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003046 if (ret == -1) {
3047 lua_pushnil(L);
3048 return 1;
3049 }
3050
3051 luaL_buffinit(L, &b);
3052 luaL_addlstring(&b, blk1, len1);
3053 len = len1;
3054 if (unlikely(ret == 2)) {
3055 luaL_addlstring(&b, blk2, len2);
3056 len += len2;
3057 }
3058 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003059 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003060 return 1;
3061}
3062
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003063/* Check arguments for the function "hlua_channel_getline_yield". */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003064__LJMP static int hlua_channel_getline(lua_State *L)
3065{
3066 MAY_LJMP(check_args(L, 1, "getline"));
3067 MAY_LJMP(hlua_checkchannel(L, 1));
3068 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
3069}
3070
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003071/* This function takes a string as input, and append it at the
3072 * input side of channel. If the data is too big, but a space
3073 * is probably available after sending some data, the function
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003074 * yields. If the data is bigger than the buffer, or if the
3075 * channel is closed, it returns -1. Otherwise, it returns the
3076 * amount of data written.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003077 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003078__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003079{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003080 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003081 size_t len;
3082 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3083 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3084 int ret;
3085 int max;
3086
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003087 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003088 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003089 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003090 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003091
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003092 /* Check if the buffer is available because HAProxy doesn't allocate
Christopher Fauleta73e59b2016-12-09 17:30:18 +01003093 * the request buffer if its not required.
3094 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003095 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01003096 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02003097 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Christopher Fauleta73e59b2016-12-09 17:30:18 +01003098 }
3099
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003100 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003101 if (max > len - l)
3102 max = len - l;
3103
Willy Tarreau06d80a92017-10-19 14:32:15 +02003104 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003105 if (ret == -2 || ret == -3) {
3106 lua_pushinteger(L, -1);
3107 return 1;
3108 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01003109 if (ret == -1) {
3110 chn->flags |= CF_WAKE_WRITE;
Willy Tarreau9635e032018-10-16 17:52:55 +02003111 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01003112 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003113 l += ret;
3114 lua_pop(L, 1);
3115 lua_pushinteger(L, l);
3116
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003117 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003118 if (max == 0 && co_data(chn) == 0) {
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003119 /* There are no space available, and the output buffer is empty.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003120 * in this case, we cannot add more data, so we cannot yield,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003121 * we return the amount of copied data.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003122 */
3123 return 1;
3124 }
3125 if (l < len)
Willy Tarreau9635e032018-10-16 17:52:55 +02003126 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003127 return 1;
3128}
3129
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003130/* Just a wrapper of "hlua_channel_append_yield". It returns the length
3131 * of the written string, or -1 if the channel is closed or if the
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003132 * buffer size is too little for the data.
3133 */
3134__LJMP static int hlua_channel_append(lua_State *L)
3135{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003136 size_t len;
3137
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003138 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003139 MAY_LJMP(hlua_checkchannel(L, 1));
3140 MAY_LJMP(luaL_checklstring(L, 2, &len));
3141 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003142 lua_pushinteger(L, 0);
3143
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003144 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003145}
3146
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003147/* Just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003148 * his process by cleaning the buffer. The result is a replacement
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003149 * of the current data. It returns the length of the written string,
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003150 * or -1 if the channel is closed or if the buffer size is too
3151 * little for the data.
3152 */
3153__LJMP static int hlua_channel_set(lua_State *L)
3154{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003155 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003156
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003157 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003158 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003159 lua_pushinteger(L, 0);
3160
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003161 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003162 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003163 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003164 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003165
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003166 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003167
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003168 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003169}
3170
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003171/* Append data in the output side of the buffer. This data is immediately
3172 * sent. The function returns the amount of data written. If the buffer
3173 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003174 * if the channel is closed.
3175 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003176__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003177{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003178 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003179 size_t len;
3180 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3181 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3182 int max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003183 struct hlua *hlua;
3184
3185 /* Get hlua struct, or NULL if we execute from main lua state */
3186 hlua = hlua_gethlua(L);
3187 if (!hlua) {
3188 lua_pushnil(L);
3189 return 1;
3190 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003191
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003192 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003193 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003194 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003195 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003196
Willy Tarreau47860ed2015-03-10 14:07:50 +01003197 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003198 lua_pushinteger(L, -1);
3199 return 1;
3200 }
3201
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003202 /* Check if the buffer is available because HAProxy doesn't allocate
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003203 * the request buffer if its not required.
3204 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003205 if (chn->buf.size == 0) {
Willy Tarreau4b962a42018-11-15 11:03:21 +01003206 si_rx_buff_blk(chn_prod(chn));
Willy Tarreau9635e032018-10-16 17:52:55 +02003207 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003208 }
3209
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003210 /* The written data will be immediately sent, so we can check
3211 * the available space without taking in account the reserve.
3212 * The reserve is guaranteed for the processing of incoming
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003213 * data, because the buffer will be flushed.
3214 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003215 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003216
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003217 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003218 * in this case, we cannot add more data, so we cannot yield,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003219 * we return the amount of copied data.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003220 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003221 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003222 return 1;
3223
3224 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003225 if (max > len - l)
3226 max = len - l;
3227
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003228 /* The buffer available size may be not contiguous. This test
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003229 * detects a non contiguous buffer and realign it.
3230 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003231 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003232 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003233
3234 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003235 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003236
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003237 /* buffer replace considers that the input part is filled.
3238 * so, I must forward these new data in the output part.
3239 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003240 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003241
3242 l += max;
3243 lua_pop(L, 1);
3244 lua_pushinteger(L, l);
3245
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003246 /* If there is no space available, and the output buffer is empty.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003247 * in this case, we cannot add more data, so we cannot yield,
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003248 * we return the amount of copied data.
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003249 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003250 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003251 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003252 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003253
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003254 if (l < len) {
3255 /* If we are waiting for space in the response buffer, we
3256 * must set the flag WAKERESWR. This flag required the task
3257 * wake up if any activity is detected on the response buffer.
3258 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003259 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003260 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003261 else
3262 HLUA_SET_WAKEREQWR(hlua);
Willy Tarreau9635e032018-10-16 17:52:55 +02003263 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003264 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003265
3266 return 1;
3267}
3268
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003269/* Just a wrapper of "_hlua_channel_send". This wrapper permits
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003270 * yield the LUA process, and resume it without checking the
3271 * input arguments.
3272 */
3273__LJMP static int hlua_channel_send(lua_State *L)
3274{
3275 MAY_LJMP(check_args(L, 2, "send"));
3276 lua_pushinteger(L, 0);
3277
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003278 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003279}
3280
3281/* This function forward and amount of butes. The data pass from
3282 * the input side of the buffer to the output side, and can be
3283 * forwarded. This function never fails.
3284 *
3285 * The Lua function takes an amount of bytes to be forwarded in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003286 * input. It returns the number of bytes forwarded.
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003287 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003288__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003289{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003290 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003291 int len;
3292 int l;
3293 int max;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01003294 struct hlua *hlua;
3295
3296 /* Get hlua struct, or NULL if we execute from main lua state */
3297 hlua = hlua_gethlua(L);
3298 if (!hlua)
3299 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003300
3301 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet3f829a42018-12-13 21:56:45 +01003302
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01003303 if (IS_HTX_STRM(chn_strm(chn))) {
Thierry Fournier77016da2020-08-15 14:35:51 +02003304 lua_pushfstring(L, "Cannot manipulate HAProxy channels in HTTP mode.");
Christopher Faulet3f829a42018-12-13 21:56:45 +01003305 WILL_LJMP(lua_error(L));
Thierry Fournier77016da2020-08-15 14:35:51 +02003306 }
Christopher Faulet3f829a42018-12-13 21:56:45 +01003307
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003308 len = MAY_LJMP(luaL_checkinteger(L, 2));
3309 l = MAY_LJMP(luaL_checkinteger(L, -1));
3310
3311 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003312 if (max > ci_data(chn))
3313 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003314 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003315 l += max;
3316
3317 lua_pop(L, 1);
3318 lua_pushinteger(L, l);
3319
3320 /* Check if it miss bytes to forward. */
3321 if (l < len) {
3322 /* The the input channel or the output channel are closed, we
3323 * must return the amount of data forwarded.
3324 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003325 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003326 return 1;
3327
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003328 /* If we are waiting for space data in the response buffer, we
3329 * must set the flag WAKERESWR. This flag required the task
3330 * wake up if any activity is detected on the response buffer.
3331 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003332 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003333 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003334 else
3335 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003336
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003337 /* Otherwise, we can yield waiting for new data in the inpout side. */
Willy Tarreau9635e032018-10-16 17:52:55 +02003338 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003339 }
3340
3341 return 1;
3342}
3343
3344/* Just check the input and prepare the stack for the previous
3345 * function "hlua_channel_forward_yield"
3346 */
3347__LJMP static int hlua_channel_forward(lua_State *L)
3348{
3349 MAY_LJMP(check_args(L, 2, "forward"));
3350 MAY_LJMP(hlua_checkchannel(L, 1));
3351 MAY_LJMP(luaL_checkinteger(L, 2));
3352
3353 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003354 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003355}
3356
3357/* Just returns the number of bytes available in the input
3358 * side of the buffer. This function never fails.
3359 */
3360__LJMP static int hlua_channel_get_in_len(lua_State *L)
3361{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003362 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003363
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003364 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003365 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Fauleta3ceac12018-12-14 13:39:09 +01003366 if (IS_HTX_STRM(chn_strm(chn))) {
3367 struct htx *htx = htxbuf(&chn->buf);
3368 lua_pushinteger(L, htx->data - co_data(chn));
3369 }
3370 else
3371 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003372 return 1;
3373}
3374
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003375/* Returns true if the channel is full. */
3376__LJMP static int hlua_channel_is_full(lua_State *L)
3377{
3378 struct channel *chn;
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003379
3380 MAY_LJMP(check_args(L, 1, "is_full"));
3381 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Christopher Faulet0ec740e2020-02-26 11:59:19 +01003382 /* ignore the reserve, we are not on a producer side (ie in an
3383 * applet).
3384 */
3385 lua_pushboolean(L, channel_full(chn, 0));
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003386 return 1;
3387}
3388
Christopher Faulet2ac9ba22020-02-25 10:15:50 +01003389/* Returns true if the channel is the response channel. */
3390__LJMP static int hlua_channel_is_resp(lua_State *L)
3391{
3392 struct channel *chn;
3393
3394 MAY_LJMP(check_args(L, 1, "is_resp"));
3395 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3396
3397 lua_pushboolean(L, !!(chn->flags & CF_ISRESP));
3398 return 1;
3399}
3400
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003401/* Just returns the number of bytes available in the output
3402 * side of the buffer. This function never fails.
3403 */
3404__LJMP static int hlua_channel_get_out_len(lua_State *L)
3405{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003406 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003407
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003408 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003409 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003410 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003411 return 1;
3412}
3413
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003414/*
3415 *
3416 *
3417 * Class Fetches
3418 *
3419 *
3420 */
3421
3422/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003423 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003424 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003425__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003426{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003427 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003428}
3429
3430/* This function creates and push in the stack a fetch object according
3431 * with a current TXN.
3432 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003433static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003434{
Willy Tarreau7073c472015-04-06 11:15:40 +02003435 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003436
3437 /* Check stack size. */
3438 if (!lua_checkstack(L, 3))
3439 return 0;
3440
3441 /* Create the object: obj[0] = userdata.
3442 * Note that the base of the Fetches object is the
3443 * transaction object.
3444 */
3445 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003446 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003447 lua_rawseti(L, -2, 0);
3448
Willy Tarreau7073c472015-04-06 11:15:40 +02003449 hsmp->s = txn->s;
3450 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003451 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003452 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003453
3454 /* Pop a class sesison metatable and affect it to the userdata. */
3455 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3456 lua_setmetatable(L, -2);
3457
3458 return 1;
3459}
3460
3461/* This function is an LUA binding. It is called with each sample-fetch.
3462 * It uses closure argument to store the associated sample-fetch. It
3463 * returns only one argument or throws an error. An error is thrown
3464 * only if an error is encountered during the argument parsing. If
3465 * the "sample-fetch" function fails, nil is returned.
3466 */
3467__LJMP static int hlua_run_sample_fetch(lua_State *L)
3468{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003469 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003470 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003471 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003472 int i;
3473 struct sample smp;
3474
3475 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003476 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003477
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003478 /* Get traditional arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003479 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003480
Thierry FOURNIERca988662015-12-20 18:43:03 +01003481 /* Check execution authorization. */
3482 if (f->use & SMP_USE_HTTP_ANY &&
3483 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3484 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3485 "is not available in Lua services", f->kw);
3486 WILL_LJMP(lua_error(L));
3487 }
3488
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003489 /* Get extra arguments. */
3490 for (i = 0; i < lua_gettop(L) - 1; i++) {
3491 if (i >= ARGM_NBARGS)
3492 break;
3493 hlua_lua2arg(L, i + 2, &args[i]);
3494 }
3495 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003496 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003497
3498 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003499 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003500
3501 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003502 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003503 lua_pushfstring(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003504 goto error;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003505 }
3506
3507 /* Initialise the sample. */
3508 memset(&smp, 0, sizeof(smp));
3509
3510 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003511 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003512 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003513 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003514 lua_pushstring(L, "");
3515 else
3516 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003517 goto end;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003518 }
3519
3520 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003521 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003522 hlua_smp2lua_str(L, &smp);
3523 else
3524 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003525
3526 end:
3527 for (i = 0; args[i].type != ARGT_STOP; i++) {
3528 if (args[i].type == ARGT_STR)
3529 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003530 else if (args[i].type == ARGT_REG)
3531 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003532 }
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003533 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003534
3535 error:
3536 for (i = 0; args[i].type != ARGT_STOP; i++) {
3537 if (args[i].type == ARGT_STR)
3538 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003539 else if (args[i].type == ARGT_REG)
3540 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003541 }
3542 WILL_LJMP(lua_error(L));
3543 return 0; /* Never reached */
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003544}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003545
3546/*
3547 *
3548 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003549 * Class Converters
3550 *
3551 *
3552 */
3553
3554/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003555 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003556 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003557__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003558{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003559 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003560}
3561
3562/* This function creates and push in the stack a Converters object
3563 * according with a current TXN.
3564 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003565static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003566{
Willy Tarreau7073c472015-04-06 11:15:40 +02003567 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003568
3569 /* Check stack size. */
3570 if (!lua_checkstack(L, 3))
3571 return 0;
3572
3573 /* Create the object: obj[0] = userdata.
3574 * Note that the base of the Converters object is the
3575 * same than the TXN object.
3576 */
3577 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003578 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003579 lua_rawseti(L, -2, 0);
3580
Willy Tarreau7073c472015-04-06 11:15:40 +02003581 hsmp->s = txn->s;
3582 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003583 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003584 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003585
Willy Tarreau87b09662015-04-03 00:22:06 +02003586 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003587 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3588 lua_setmetatable(L, -2);
3589
3590 return 1;
3591}
3592
3593/* This function is an LUA binding. It is called with each converter.
3594 * It uses closure argument to store the associated converter. It
3595 * returns only one argument or throws an error. An error is thrown
3596 * only if an error is encountered during the argument parsing. If
3597 * the converter function function fails, nil is returned.
3598 */
3599__LJMP static int hlua_run_sample_conv(lua_State *L)
3600{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003601 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003602 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003603 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003604 int i;
3605 struct sample smp;
3606
3607 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003608 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003609
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003610 /* Get traditional arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003611 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003612
3613 /* Get extra arguments. */
3614 for (i = 0; i < lua_gettop(L) - 2; i++) {
3615 if (i >= ARGM_NBARGS)
3616 break;
3617 hlua_lua2arg(L, i + 3, &args[i]);
3618 }
3619 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003620 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003621
3622 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003623 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003624
3625 /* Run the special args checker. */
3626 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3627 hlua_pusherror(L, "error in arguments");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003628 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003629 }
3630
3631 /* Initialise the sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01003632 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003633 if (!hlua_lua2smp(L, 2, &smp)) {
3634 hlua_pusherror(L, "error in the input argument");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003635 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003636 }
3637
Willy Tarreau1777ea62016-03-10 16:15:46 +01003638 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3639
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003640 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003641 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003642 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003643 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003644 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003645 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003646 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3647 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003648 hlua_pusherror(L, "error during the input argument casting");
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003649 goto error;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003650 }
3651
3652 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003653 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003654 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003655 lua_pushstring(L, "");
3656 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003657 lua_pushnil(L);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003658 goto end;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003659 }
3660
3661 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003662 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003663 hlua_smp2lua_str(L, &smp);
3664 else
3665 hlua_smp2lua(L, &smp);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003666 end:
3667 for (i = 0; args[i].type != ARGT_STOP; i++) {
3668 if (args[i].type == ARGT_STR)
3669 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003670 else if (args[i].type == ARGT_REG)
3671 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003672 }
Willy Tarreaua678b432015-08-28 10:14:59 +02003673 return 1;
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003674
3675 error:
3676 for (i = 0; args[i].type != ARGT_STOP; i++) {
3677 if (args[i].type == ARGT_STR)
3678 chunk_destroy(&args[i].data.str);
Christopher Fauletfd2e9062020-08-06 11:10:57 +02003679 else if (args[i].type == ARGT_REG)
3680 regex_free(args[i].data.reg);
Christopher Fauletaec27ef2020-08-06 08:54:25 +02003681 }
3682 WILL_LJMP(lua_error(L));
3683 return 0; /* Never reached */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003684}
3685
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003686/*
3687 *
3688 *
3689 * Class AppletTCP
3690 *
3691 *
3692 */
3693
3694/* Returns a struct hlua_txn if the stack entry "ud" is
3695 * a class stream, otherwise it throws an error.
3696 */
3697__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3698{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003699 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003700}
3701
3702/* This function creates and push in the stack an Applet object
3703 * according with a current TXN.
3704 */
3705static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3706{
3707 struct hlua_appctx *appctx;
3708 struct stream_interface *si = ctx->owner;
3709 struct stream *s = si_strm(si);
3710 struct proxy *p = s->be;
3711
3712 /* Check stack size. */
3713 if (!lua_checkstack(L, 3))
3714 return 0;
3715
3716 /* Create the object: obj[0] = userdata.
3717 * Note that the base of the Converters object is the
3718 * same than the TXN object.
3719 */
3720 lua_newtable(L);
3721 appctx = lua_newuserdata(L, sizeof(*appctx));
3722 lua_rawseti(L, -2, 0);
3723 appctx->appctx = ctx;
3724 appctx->htxn.s = s;
3725 appctx->htxn.p = p;
3726
3727 /* Create the "f" field that contains a list of fetches. */
3728 lua_pushstring(L, "f");
3729 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3730 return 0;
3731 lua_settable(L, -3);
3732
3733 /* Create the "sf" field that contains a list of stringsafe fetches. */
3734 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003735 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003736 return 0;
3737 lua_settable(L, -3);
3738
3739 /* Create the "c" field that contains a list of converters. */
3740 lua_pushstring(L, "c");
3741 if (!hlua_converters_new(L, &appctx->htxn, 0))
3742 return 0;
3743 lua_settable(L, -3);
3744
3745 /* Create the "sc" field that contains a list of stringsafe converters. */
3746 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003747 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003748 return 0;
3749 lua_settable(L, -3);
3750
3751 /* Pop a class stream metatable and affect it to the table. */
3752 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3753 lua_setmetatable(L, -2);
3754
3755 return 1;
3756}
3757
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003758__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3759{
3760 struct hlua_appctx *appctx;
3761 struct stream *s;
3762 const char *name;
3763 size_t len;
3764 struct sample smp;
3765
Tim Duesterhus4e172c92020-05-19 13:49:42 +02003766 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
3767 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003768
3769 /* It is useles to retrieve the stream, but this function
3770 * runs only in a stream context.
3771 */
3772 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3773 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3774 s = appctx->htxn.s;
3775
3776 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01003777 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003778 hlua_lua2smp(L, 3, &smp);
3779
3780 /* Store the sample in a variable. */
3781 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02003782
3783 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
3784 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
3785 else
3786 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
3787
Tim Duesterhus84ebc132020-05-19 13:49:41 +02003788 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003789}
3790
3791__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3792{
3793 struct hlua_appctx *appctx;
3794 struct stream *s;
3795 const char *name;
3796 size_t len;
3797 struct sample smp;
3798
3799 MAY_LJMP(check_args(L, 2, "unset_var"));
3800
3801 /* It is useles to retrieve the stream, but this function
3802 * runs only in a stream context.
3803 */
3804 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3805 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3806 s = appctx->htxn.s;
3807
3808 /* Unset the variable. */
3809 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02003810 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
3811 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003812}
3813
3814__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3815{
3816 struct hlua_appctx *appctx;
3817 struct stream *s;
3818 const char *name;
3819 size_t len;
3820 struct sample smp;
3821
3822 MAY_LJMP(check_args(L, 2, "get_var"));
3823
3824 /* It is useles to retrieve the stream, but this function
3825 * runs only in a stream context.
3826 */
3827 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3828 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3829 s = appctx->htxn.s;
3830
3831 smp_set_owner(&smp, s->be, s->sess, s, 0);
3832 if (!vars_get_by_name(name, len, &smp)) {
3833 lua_pushnil(L);
3834 return 1;
3835 }
3836
3837 return hlua_smp2lua(L, &smp);
3838}
3839
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003840__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3841{
3842 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3843 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003844 struct hlua *hlua;
3845
3846 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003847 if (!s->hlua)
3848 return 0;
3849 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003850
3851 MAY_LJMP(check_args(L, 2, "set_priv"));
3852
3853 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003854 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003855
3856 /* Get and store new value. */
3857 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3858 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3859
3860 return 0;
3861}
3862
3863__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3864{
3865 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3866 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003867 struct hlua *hlua;
3868
3869 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003870 if (!s->hlua) {
3871 lua_pushnil(L);
3872 return 1;
3873 }
3874 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003875
3876 /* Push configuration index in the stack. */
3877 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3878
3879 return 1;
3880}
3881
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003882/* If expected data not yet available, it returns a yield. This function
3883 * consumes the data in the buffer. It returns a string containing the
3884 * data. This string can be empty.
3885 */
3886__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3887{
3888 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3889 struct stream_interface *si = appctx->appctx->owner;
3890 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003891 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003892 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003893 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003894 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003895
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003896 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003897 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003898
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003899 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003900 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003901 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003902 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003903 }
3904
3905 /* End of data: commit the total strings and return. */
3906 if (ret < 0) {
3907 luaL_pushresult(&appctx->b);
3908 return 1;
3909 }
3910
3911 /* Ensure that the block 2 length is usable. */
3912 if (ret == 1)
3913 len2 = 0;
3914
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07003915 /* don't check the max length read and don't check. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003916 luaL_addlstring(&appctx->b, blk1, len1);
3917 luaL_addlstring(&appctx->b, blk2, len2);
3918
3919 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003920 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003921 luaL_pushresult(&appctx->b);
3922 return 1;
3923}
3924
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003925/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003926__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3927{
3928 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3929
3930 /* Initialise the string catenation. */
3931 luaL_buffinit(L, &appctx->b);
3932
3933 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3934}
3935
3936/* If expected data not yet available, it returns a yield. This function
3937 * consumes the data in the buffer. It returns a string containing the
3938 * data. This string can be empty.
3939 */
3940__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3941{
3942 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3943 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003944 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003945 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003946 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003947 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003948 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003949 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003950
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003951 /* Read the maximum amount of data available. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003952 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003953
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003954 /* Data not yet available. return yield. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003955 if (ret == 0) {
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003956 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003957 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003958 }
3959
3960 /* End of data: commit the total strings and return. */
3961 if (ret < 0) {
3962 luaL_pushresult(&appctx->b);
3963 return 1;
3964 }
3965
3966 /* Ensure that the block 2 length is usable. */
3967 if (ret == 1)
3968 len2 = 0;
3969
3970 if (len == -1) {
3971
3972 /* If len == -1, catenate all the data avalaile and
3973 * yield because we want to get all the data until
3974 * the end of data stream.
3975 */
3976 luaL_addlstring(&appctx->b, blk1, len1);
3977 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003978 co_skip(si_oc(si), len1 + len2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01003979 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02003980 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003981
3982 } else {
3983
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003984 /* Copy the first block caping to the length required. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003985 if (len1 > len)
3986 len1 = len;
3987 luaL_addlstring(&appctx->b, blk1, len1);
3988 len -= len1;
3989
3990 /* Copy the second block. */
3991 if (len2 > len)
3992 len2 = len;
3993 luaL_addlstring(&appctx->b, blk2, len2);
3994 len -= len2;
3995
3996 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003997 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003998
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08003999 /* If there is no other data available, yield waiting for new data. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004000 if (len > 0) {
4001 lua_pushinteger(L, len);
4002 lua_replace(L, 2);
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01004003 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004004 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004005 }
4006
4007 /* return the result. */
4008 luaL_pushresult(&appctx->b);
4009 return 1;
4010 }
4011
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004012 /* we never execute this */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004013 hlua_pusherror(L, "Lua: internal error");
4014 WILL_LJMP(lua_error(L));
4015 return 0;
4016}
4017
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004018/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004019__LJMP static int hlua_applet_tcp_recv(lua_State *L)
4020{
4021 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4022 int len = -1;
4023
4024 if (lua_gettop(L) > 2)
4025 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4026 if (lua_gettop(L) >= 2) {
4027 len = MAY_LJMP(luaL_checkinteger(L, 2));
4028 lua_pop(L, 1);
4029 }
4030
4031 /* Confirm or set the required length */
4032 lua_pushinteger(L, len);
4033
4034 /* Initialise the string catenation. */
4035 luaL_buffinit(L, &appctx->b);
4036
4037 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
4038}
4039
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004040/* Append data in the output side of the buffer. This data is immediately
4041 * sent. The function returns the amount of data written. If the buffer
4042 * cannot contain the data, the function yields. The function returns -1
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004043 * if the channel is closed.
4044 */
4045__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
4046{
4047 size_t len;
4048 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
4049 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4050 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4051 struct stream_interface *si = appctx->appctx->owner;
4052 struct channel *chn = si_ic(si);
4053 int max;
4054
4055 /* Get the max amount of data which can write as input in the channel. */
4056 max = channel_recv_max(chn);
4057 if (max > (len - l))
4058 max = len - l;
4059
4060 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004061 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004062
4063 /* update counters. */
4064 l += max;
4065 lua_pop(L, 1);
4066 lua_pushinteger(L, l);
4067
4068 /* If some data is not send, declares the situation to the
4069 * applet, and returns a yield.
4070 */
4071 if (l < len) {
Willy Tarreaudb398432018-11-15 11:08:52 +01004072 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004073 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004074 }
4075
4076 return 1;
4077}
4078
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004079/* Just a wrapper of "hlua_applet_tcp_send_yield". This wrapper permits
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02004080 * yield the LUA process, and resume it without checking the
4081 * input arguments.
4082 */
4083__LJMP static int hlua_applet_tcp_send(lua_State *L)
4084{
4085 MAY_LJMP(check_args(L, 2, "send"));
4086 lua_pushinteger(L, 0);
4087
4088 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
4089}
4090
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004091/*
4092 *
4093 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004094 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004095 *
4096 *
4097 */
4098
4099/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004100 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004101 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004102__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004103{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004104 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004105}
4106
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004107/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004108 * according with a current TXN.
4109 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004110static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004111{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004112 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01004113 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004114 struct stream_interface *si = ctx->owner;
4115 struct stream *s = si_strm(si);
4116 struct proxy *px = s->be;
Christopher Fauleta2097962019-07-15 16:25:33 +02004117 struct htx *htx;
4118 struct htx_blk *blk;
4119 struct htx_sl *sl;
4120 struct ist path;
4121 unsigned long long len = 0;
4122 int32_t pos;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004123
4124 /* Check stack size. */
4125 if (!lua_checkstack(L, 3))
4126 return 0;
4127
4128 /* Create the object: obj[0] = userdata.
4129 * Note that the base of the Converters object is the
4130 * same than the TXN object.
4131 */
4132 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004133 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004134 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004135 appctx->appctx = ctx;
4136 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004137 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004138 appctx->htxn.s = s;
4139 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004140
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004141 /* Create the "f" field that contains a list of fetches. */
4142 lua_pushstring(L, "f");
4143 if (!hlua_fetches_new(L, &appctx->htxn, 0))
4144 return 0;
4145 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004146
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004147 /* Create the "sf" field that contains a list of stringsafe fetches. */
4148 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004149 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004150 return 0;
4151 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004152
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004153 /* Create the "c" field that contains a list of converters. */
4154 lua_pushstring(L, "c");
4155 if (!hlua_converters_new(L, &appctx->htxn, 0))
4156 return 0;
4157 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004158
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004159 /* Create the "sc" field that contains a list of stringsafe converters. */
4160 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004161 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004162 return 0;
4163 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02004164
Christopher Fauleta2097962019-07-15 16:25:33 +02004165 htx = htxbuf(&s->req.buf);
4166 blk = htx_get_first_blk(htx);
Christopher Fauletea009732019-11-18 15:50:25 +01004167 BUG_ON(!blk || htx_get_blk_type(blk) != HTX_BLK_REQ_SL);
Christopher Fauleta2097962019-07-15 16:25:33 +02004168 sl = htx_get_blk_ptr(htx, blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004169
Christopher Fauleta2097962019-07-15 16:25:33 +02004170 /* Stores the request method. */
4171 lua_pushstring(L, "method");
4172 lua_pushlstring(L, HTX_SL_REQ_MPTR(sl), HTX_SL_REQ_MLEN(sl));
4173 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004174
Christopher Fauleta2097962019-07-15 16:25:33 +02004175 /* Stores the http version. */
4176 lua_pushstring(L, "version");
4177 lua_pushlstring(L, HTX_SL_REQ_VPTR(sl), HTX_SL_REQ_VLEN(sl));
4178 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004179
Christopher Fauleta2097962019-07-15 16:25:33 +02004180 /* creates an array of headers. hlua_http_get_headers() crates and push
4181 * the array on the top of the stack.
4182 */
4183 lua_pushstring(L, "headers");
4184 htxn.s = s;
4185 htxn.p = px;
4186 htxn.dir = SMP_OPT_DIR_REQ;
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004187 if (!hlua_http_get_headers(L, &htxn.s->txn->req))
Christopher Fauleta2097962019-07-15 16:25:33 +02004188 return 0;
4189 lua_settable(L, -3);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004190
Christopher Fauleta2097962019-07-15 16:25:33 +02004191 path = http_get_path(htx_sl_req_uri(sl));
Tim Duesterhused526372020-03-05 17:56:33 +01004192 if (isttest(path)) {
Christopher Fauleta2097962019-07-15 16:25:33 +02004193 char *p, *q, *end;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004194
Christopher Fauleta2097962019-07-15 16:25:33 +02004195 p = path.ptr;
4196 end = path.ptr + path.len;
4197 q = p;
4198 while (q < end && *q != '?')
4199 q++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004200
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004201 /* Stores the request path. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004202 lua_pushstring(L, "path");
4203 lua_pushlstring(L, p, q - p);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01004204 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004205
Christopher Fauleta2097962019-07-15 16:25:33 +02004206 /* Stores the query string. */
4207 lua_pushstring(L, "qs");
4208 if (*q == '?')
4209 q++;
4210 lua_pushlstring(L, q, end - q);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004211 lua_settable(L, -3);
Christopher Fauleta2097962019-07-15 16:25:33 +02004212 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004213
Christopher Fauleta2097962019-07-15 16:25:33 +02004214 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4215 struct htx_blk *blk = htx_get_blk(htx, pos);
4216 enum htx_blk_type type = htx_get_blk_type(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004217
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004218 if (type == HTX_BLK_TLR || type == HTX_BLK_EOT)
Christopher Fauleta2097962019-07-15 16:25:33 +02004219 break;
4220 if (type == HTX_BLK_DATA)
4221 len += htx_get_blksz(blk);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004222 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004223 if (htx->extra != ULLONG_MAX)
4224 len += htx->extra;
4225
4226 /* Stores the request path. */
4227 lua_pushstring(L, "length");
4228 lua_pushinteger(L, len);
4229 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004230
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004231 /* Create an empty array of HTTP request headers. */
4232 lua_pushstring(L, "response");
4233 lua_newtable(L);
4234 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01004235
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004236 /* Pop a class stream metatable and affect it to the table. */
4237 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
4238 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004239
4240 return 1;
4241}
4242
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004243__LJMP static int hlua_applet_http_set_var(lua_State *L)
4244{
4245 struct hlua_appctx *appctx;
4246 struct stream *s;
4247 const char *name;
4248 size_t len;
4249 struct sample smp;
4250
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004251 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
4252 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004253
4254 /* It is useles to retrieve the stream, but this function
4255 * runs only in a stream context.
4256 */
4257 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4258 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4259 s = appctx->htxn.s;
4260
4261 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01004262 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004263 hlua_lua2smp(L, 3, &smp);
4264
4265 /* Store the sample in a variable. */
4266 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02004267
4268 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
4269 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
4270 else
4271 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
4272
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004273 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004274}
4275
4276__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4277{
4278 struct hlua_appctx *appctx;
4279 struct stream *s;
4280 const char *name;
4281 size_t len;
4282 struct sample smp;
4283
4284 MAY_LJMP(check_args(L, 2, "unset_var"));
4285
4286 /* It is useles to retrieve the stream, but this function
4287 * runs only in a stream context.
4288 */
4289 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4290 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4291 s = appctx->htxn.s;
4292
4293 /* Unset the variable. */
4294 smp_set_owner(&smp, s->be, s->sess, s, 0);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02004295 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
4296 return 1;
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01004297}
4298
4299__LJMP static int hlua_applet_http_get_var(lua_State *L)
4300{
4301 struct hlua_appctx *appctx;
4302 struct stream *s;
4303 const char *name;
4304 size_t len;
4305 struct sample smp;
4306
4307 MAY_LJMP(check_args(L, 2, "get_var"));
4308
4309 /* It is useles to retrieve the stream, but this function
4310 * runs only in a stream context.
4311 */
4312 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4313 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4314 s = appctx->htxn.s;
4315
4316 smp_set_owner(&smp, s->be, s->sess, s, 0);
4317 if (!vars_get_by_name(name, len, &smp)) {
4318 lua_pushnil(L);
4319 return 1;
4320 }
4321
4322 return hlua_smp2lua(L, &smp);
4323}
4324
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004325__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4326{
4327 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4328 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004329 struct hlua *hlua;
4330
4331 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004332 if (!s->hlua)
4333 return 0;
4334 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004335
4336 MAY_LJMP(check_args(L, 2, "set_priv"));
4337
4338 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004339 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004340
4341 /* Get and store new value. */
4342 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4343 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4344
4345 return 0;
4346}
4347
4348__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4349{
4350 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4351 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004352 struct hlua *hlua;
4353
4354 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004355 if (!s->hlua) {
4356 lua_pushnil(L);
4357 return 1;
4358 }
4359 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004360
4361 /* Push configuration index in the stack. */
4362 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4363
4364 return 1;
4365}
4366
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004367/* If expected data not yet available, it returns a yield. This function
4368 * consumes the data in the buffer. It returns a string containing the
4369 * data. This string can be empty.
4370 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004371__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004372{
4373 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4374 struct stream_interface *si = appctx->appctx->owner;
4375 struct channel *req = si_oc(si);
4376 struct htx *htx;
4377 struct htx_blk *blk;
4378 size_t count;
4379 int stop = 0;
4380
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004381 htx = htx_from_buf(&req->buf);
4382 count = co_data(req);
Christopher Fauleta3f15502019-05-13 15:27:23 +02004383 blk = htx_get_first_blk(htx);
Christopher Fauletcc26b132018-12-18 21:20:57 +01004384
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004385 while (count && !stop && blk) {
4386 enum htx_blk_type type = htx_get_blk_type(blk);
4387 uint32_t sz = htx_get_blksz(blk);
4388 struct ist v;
4389 uint32_t vlen;
4390 char *nl;
4391
4392 vlen = sz;
4393 if (vlen > count) {
4394 if (type != HTX_BLK_DATA)
4395 break;
4396 vlen = count;
4397 }
4398
4399 switch (type) {
4400 case HTX_BLK_UNUSED:
4401 break;
4402
4403 case HTX_BLK_DATA:
4404 v = htx_get_blk_value(htx, blk);
4405 v.len = vlen;
4406 nl = istchr(v, '\n');
4407 if (nl != NULL) {
4408 stop = 1;
4409 vlen = nl - v.ptr + 1;
4410 }
4411 luaL_addlstring(&appctx->b, v.ptr, vlen);
4412 break;
4413
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004414 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004415 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004416 stop = 1;
4417 break;
4418
4419 default:
4420 break;
4421 }
4422
4423 co_set_data(req, co_data(req) - vlen);
4424 count -= vlen;
4425 if (sz == vlen)
4426 blk = htx_remove_blk(htx, blk);
4427 else {
4428 htx_cut_data_blk(htx, blk, vlen);
4429 break;
4430 }
4431 }
4432
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004433 /* The message was fully consumed and no more data are expected
4434 * (EOM flag set).
4435 */
4436 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
4437 stop = 1;
4438
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004439 htx_to_buf(htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004440 if (!stop) {
4441 si_cant_get(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004442 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004443 }
4444
4445 /* return the result. */
4446 luaL_pushresult(&appctx->b);
4447 return 1;
4448}
4449
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004450
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004451/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004452__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004453{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004454 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004455
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004456 /* Initialise the string catenation. */
4457 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004458
Christopher Fauleta2097962019-07-15 16:25:33 +02004459 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004460}
4461
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004462/* If expected data not yet available, it returns a yield. This function
4463 * consumes the data in the buffer. It returns a string containing the
4464 * data. This string can be empty.
4465 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004466__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004467{
4468 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4469 struct stream_interface *si = appctx->appctx->owner;
4470 struct channel *req = si_oc(si);
4471 struct htx *htx;
4472 struct htx_blk *blk;
4473 size_t count;
4474 int len;
4475
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004476 htx = htx_from_buf(&req->buf);
4477 len = MAY_LJMP(luaL_checkinteger(L, 2));
4478 count = co_data(req);
Christopher Faulet29f17582019-05-23 11:03:26 +02004479 blk = htx_get_head_blk(htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004480 while (count && len && blk) {
4481 enum htx_blk_type type = htx_get_blk_type(blk);
4482 uint32_t sz = htx_get_blksz(blk);
4483 struct ist v;
4484 uint32_t vlen;
4485
4486 vlen = sz;
4487 if (len > 0 && vlen > len)
4488 vlen = len;
4489 if (vlen > count) {
4490 if (type != HTX_BLK_DATA)
4491 break;
4492 vlen = count;
4493 }
4494
4495 switch (type) {
4496 case HTX_BLK_UNUSED:
4497 break;
4498
4499 case HTX_BLK_DATA:
4500 v = htx_get_blk_value(htx, blk);
4501 luaL_addlstring(&appctx->b, v.ptr, vlen);
4502 break;
4503
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004504 case HTX_BLK_TLR:
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01004505 case HTX_BLK_EOT:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004506 len = 0;
4507 break;
4508
4509 default:
4510 break;
4511 }
4512
4513 co_set_data(req, co_data(req) - vlen);
4514 count -= vlen;
4515 if (len > 0)
4516 len -= vlen;
4517 if (sz == vlen)
4518 blk = htx_remove_blk(htx, blk);
4519 else {
4520 htx_cut_data_blk(htx, blk, vlen);
4521 break;
4522 }
4523 }
4524
Christopher Fauleteccb31c2021-04-02 14:24:56 +02004525 /* The message was fully consumed and no more data are expected
4526 * (EOM flag set).
4527 */
4528 if (htx_is_empty(htx) && (htx->flags & HTX_FL_EOM))
4529 len = 0;
4530
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004531 htx_to_buf(htx, &req->buf);
4532
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004533 /* If we are no other data available, yield waiting for new data. */
4534 if (len) {
4535 if (len > 0) {
4536 lua_pushinteger(L, len);
4537 lua_replace(L, 2);
4538 }
4539 si_cant_get(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004540 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004541 }
4542
4543 /* return the result. */
4544 luaL_pushresult(&appctx->b);
4545 return 1;
4546}
4547
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08004548/* Check arguments for the function "hlua_channel_get_yield". */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004549__LJMP static int hlua_applet_http_recv(lua_State *L)
4550{
4551 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4552 int len = -1;
4553
4554 /* Check arguments. */
4555 if (lua_gettop(L) > 2)
4556 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4557 if (lua_gettop(L) >= 2) {
4558 len = MAY_LJMP(luaL_checkinteger(L, 2));
4559 lua_pop(L, 1);
4560 }
4561
Christopher Fauleta2097962019-07-15 16:25:33 +02004562 lua_pushinteger(L, len);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004563
Christopher Fauleta2097962019-07-15 16:25:33 +02004564 /* Initialise the string catenation. */
4565 luaL_buffinit(L, &appctx->b);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004566
Christopher Fauleta2097962019-07-15 16:25:33 +02004567 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004568}
4569
4570/* Append data in the output side of the buffer. This data is immediately
4571 * sent. The function returns the amount of data written. If the buffer
4572 * cannot contain the data, the function yields. The function returns -1
4573 * if the channel is closed.
4574 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004575__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004576{
4577 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4578 struct stream_interface *si = appctx->appctx->owner;
4579 struct channel *res = si_ic(si);
4580 struct htx *htx = htx_from_buf(&res->buf);
4581 const char *data;
4582 size_t len;
4583 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4584 int max;
4585
Christopher Faulet9060fc02019-07-03 11:39:30 +02004586 max = htx_get_max_blksz(htx, channel_htx_recv_max(res, htx));
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004587 if (!max)
4588 goto snd_yield;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004589
4590 data = MAY_LJMP(luaL_checklstring(L, 2, &len));
4591
4592 /* Get the max amount of data which can write as input in the channel. */
4593 if (max > (len - l))
4594 max = len - l;
4595
4596 /* Copy data. */
Willy Tarreau0a7ef022019-05-28 10:30:11 +02004597 max = htx_add_data(htx, ist2(data + l, max));
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004598 channel_add_input(res, max);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004599
4600 /* update counters. */
4601 l += max;
4602 lua_pop(L, 1);
4603 lua_pushinteger(L, l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004604
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004605 /* If some data is not send, declares the situation to the
4606 * applet, and returns a yield.
4607 */
4608 if (l < len) {
Christopher Faulet4b0e9b22019-01-09 12:16:58 +01004609 snd_yield:
Christopher Faulet0ae79d02019-02-27 21:36:59 +01004610 htx_to_buf(htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004611 si_rx_room_blk(si);
Willy Tarreau9635e032018-10-16 17:52:55 +02004612 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004613 }
4614
Christopher Fauleta2097962019-07-15 16:25:33 +02004615 htx_to_buf(htx, &res->buf);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004616 return 1;
4617}
4618
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004619/* Just a wrapper of "hlua_applet_send_yield". This wrapper permits
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004620 * yield the LUA process, and resume it without checking the
4621 * input arguments.
4622 */
4623__LJMP static int hlua_applet_http_send(lua_State *L)
4624{
4625 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004626
4627 /* We want to send some data. Headers must be sent. */
4628 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4629 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4630 WILL_LJMP(lua_error(L));
4631 }
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004632
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004633 /* This integer is used for followinf the amount of data sent. */
Christopher Fauleta2097962019-07-15 16:25:33 +02004634 lua_pushinteger(L, 0);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004635
Christopher Fauleta2097962019-07-15 16:25:33 +02004636 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004637}
4638
4639__LJMP static int hlua_applet_http_addheader(lua_State *L)
4640{
4641 const char *name;
4642 int ret;
4643
4644 MAY_LJMP(hlua_checkapplet_http(L, 1));
4645 name = MAY_LJMP(luaL_checkstring(L, 2));
4646 MAY_LJMP(luaL_checkstring(L, 3));
4647
4648 /* Push in the stack the "response" entry. */
4649 ret = lua_getfield(L, 1, "response");
4650 if (ret != LUA_TTABLE) {
4651 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4652 "is expected as an array. %s found", lua_typename(L, ret));
4653 WILL_LJMP(lua_error(L));
4654 }
4655
4656 /* check if the header is already registered if it is not
4657 * the case, register it.
4658 */
4659 ret = lua_getfield(L, -1, name);
4660 if (ret == LUA_TNIL) {
4661
4662 /* Entry not found. */
4663 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4664
4665 /* Insert the new header name in the array in the top of the stack.
4666 * It left the new array in the top of the stack.
4667 */
4668 lua_newtable(L);
4669 lua_pushvalue(L, 2);
4670 lua_pushvalue(L, -2);
4671 lua_settable(L, -4);
4672
4673 } else if (ret != LUA_TTABLE) {
4674
4675 /* corruption error. */
4676 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4677 "is expected as an array. %s found", name, lua_typename(L, ret));
4678 WILL_LJMP(lua_error(L));
4679 }
4680
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004681 /* Now the top of thestack is an array of values. We push
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004682 * the header value as new entry.
4683 */
4684 lua_pushvalue(L, 3);
4685 ret = lua_rawlen(L, -2);
4686 lua_rawseti(L, -2, ret + 1);
4687 lua_pushboolean(L, 1);
4688 return 1;
4689}
4690
4691__LJMP static int hlua_applet_http_status(lua_State *L)
4692{
4693 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4694 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004695 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004696
4697 if (status < 100 || status > 599) {
4698 lua_pushboolean(L, 0);
4699 return 1;
4700 }
4701
4702 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004703 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004704 lua_pushboolean(L, 1);
4705 return 1;
4706}
4707
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004708
Christopher Fauleta2097962019-07-15 16:25:33 +02004709__LJMP static int hlua_applet_http_send_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004710{
4711 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4712 struct stream_interface *si = appctx->appctx->owner;
4713 struct channel *res = si_ic(si);
4714 struct htx *htx;
4715 struct htx_sl *sl;
4716 struct h1m h1m;
4717 const char *status, *reason;
4718 const char *name, *value;
4719 size_t nlen, vlen;
4720 unsigned int flags;
4721
4722 /* Send the message at once. */
4723 htx = htx_from_buf(&res->buf);
4724 h1m_init_res(&h1m);
4725
4726 /* Use the same http version than the request. */
4727 status = ultoa_r(appctx->appctx->ctx.hlua_apphttp.status, trash.area, trash.size);
4728 reason = appctx->appctx->ctx.hlua_apphttp.reason;
4729 if (reason == NULL)
4730 reason = http_get_reason(appctx->appctx->ctx.hlua_apphttp.status);
4731 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) {
4732 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
4733 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"), ist(status), ist(reason));
4734 }
4735 else {
4736 flags = HTX_SL_F_IS_RESP;
4737 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"), ist(status), ist(reason));
4738 }
4739 if (!sl) {
4740 hlua_pusherror(L, "Lua applet http '%s': Failed to create response.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01004741 appctx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004742 WILL_LJMP(lua_error(L));
4743 }
4744 sl->info.res.status = appctx->appctx->ctx.hlua_apphttp.status;
4745
4746 /* Get the array associated to the field "response" in the object AppletHTTP. */
4747 lua_pushvalue(L, 0);
4748 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4749 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01004750 appctx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004751 WILL_LJMP(lua_error(L));
4752 }
4753
4754 /* Browse the list of headers. */
4755 lua_pushnil(L);
4756 while(lua_next(L, -2) != 0) {
4757 /* We expect a string as -2. */
4758 if (lua_type(L, -2) != LUA_TSTRING) {
4759 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01004760 appctx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004761 lua_typename(L, lua_type(L, -2)));
4762 WILL_LJMP(lua_error(L));
4763 }
4764 name = lua_tolstring(L, -2, &nlen);
4765
4766 /* We expect an array as -1. */
4767 if (lua_type(L, -1) != LUA_TTABLE) {
4768 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01004769 appctx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004770 name,
4771 lua_typename(L, lua_type(L, -1)));
4772 WILL_LJMP(lua_error(L));
4773 }
4774
4775 /* Browse the table who is on the top of the stack. */
4776 lua_pushnil(L);
4777 while(lua_next(L, -2) != 0) {
4778 int id;
4779
4780 /* We expect a number as -2. */
4781 if (lua_type(L, -2) != LUA_TNUMBER) {
4782 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01004783 appctx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004784 name,
4785 lua_typename(L, lua_type(L, -2)));
4786 WILL_LJMP(lua_error(L));
4787 }
4788 id = lua_tointeger(L, -2);
4789
4790 /* We expect a string as -2. */
4791 if (lua_type(L, -1) != LUA_TSTRING) {
4792 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01004793 appctx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004794 name, id,
4795 lua_typename(L, lua_type(L, -1)));
4796 WILL_LJMP(lua_error(L));
4797 }
4798 value = lua_tolstring(L, -1, &vlen);
4799
4800 /* Simple Protocol checks. */
4801 if (isteqi(ist2(name, nlen), ist("transfer-encoding")))
Christopher Faulet700d9e82020-01-31 12:21:52 +01004802 h1_parse_xfer_enc_header(&h1m, ist2(value, vlen));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004803 else if (isteqi(ist2(name, nlen), ist("content-length"))) {
4804 struct ist v = ist2(value, vlen);
4805 int ret;
4806
4807 ret = h1_parse_cont_len_header(&h1m, &v);
4808 if (ret < 0) {
4809 hlua_pusherror(L, "Lua applet http '%s': Invalid '%s' header.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01004810 appctx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004811 name);
4812 WILL_LJMP(lua_error(L));
4813 }
4814 else if (ret == 0)
4815 goto next; /* Skip it */
4816 }
4817
4818 /* Add a new header */
4819 if (!htx_add_header(htx, ist2(name, nlen), ist2(value, vlen))) {
4820 hlua_pusherror(L, "Lua applet http '%s': Failed to add header '%s' in the response.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01004821 appctx->appctx->rule->arg.hlua_rule->fcn->name,
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004822 name);
4823 WILL_LJMP(lua_error(L));
4824 }
4825 next:
4826 /* Remove the array from the stack, and get next element with a remaining string. */
4827 lua_pop(L, 1);
4828 }
4829
4830 /* Remove the array from the stack, and get next element with a remaining string. */
4831 lua_pop(L, 1);
4832 }
4833
4834 if (h1m.flags & H1_MF_CHNK)
4835 h1m.flags &= ~H1_MF_CLEN;
4836 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
4837 h1m.flags |= H1_MF_XFER_LEN;
4838
4839 /* Uset HTX start-line flags */
4840 if (h1m.flags & H1_MF_XFER_ENC)
4841 flags |= HTX_SL_F_XFER_ENC;
4842 if (h1m.flags & H1_MF_XFER_LEN) {
4843 flags |= HTX_SL_F_XFER_LEN;
4844 if (h1m.flags & H1_MF_CHNK)
4845 flags |= HTX_SL_F_CHNK;
4846 else if (h1m.flags & H1_MF_CLEN)
4847 flags |= HTX_SL_F_CLEN;
4848 if (h1m.body_len == 0)
4849 flags |= HTX_SL_F_BODYLESS;
4850 }
4851 sl->flags |= flags;
4852
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07004853 /* If we don't have a content-length set, and the HTTP version is 1.1
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004854 * and the status code implies the presence of a message body, we must
4855 * announce a transfer encoding chunked. This is required by haproxy
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004856 * for the keepalive compliance. If the applet announces a transfer-encoding
4857 * chunked itself, don't do anything.
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004858 */
4859 if ((flags & (HTX_SL_F_VER_11|HTX_SL_F_XFER_LEN)) == HTX_SL_F_VER_11 &&
4860 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4861 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4862 appctx->appctx->ctx.hlua_apphttp.status != 304) {
4863 /* Add a new header */
4864 sl->flags |= (HTX_SL_F_XFER_ENC|H1_MF_CHNK|H1_MF_XFER_LEN);
4865 if (!htx_add_header(htx, ist("transfer-encoding"), ist("chunked"))) {
4866 hlua_pusherror(L, "Lua applet http '%s': Failed to add header 'transfer-encoding' in the response.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01004867 appctx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004868 WILL_LJMP(lua_error(L));
4869 }
4870 }
4871
4872 /* Finalize headers. */
4873 if (!htx_add_endof(htx, HTX_BLK_EOH)) {
4874 hlua_pusherror(L, "Lua applet http '%s': Failed create the response.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01004875 appctx->appctx->rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004876 WILL_LJMP(lua_error(L));
4877 }
4878
4879 if (htx_used_space(htx) > b_size(&res->buf) - global.tune.maxrewrite) {
4880 b_reset(&res->buf);
4881 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4882 WILL_LJMP(lua_error(L));
4883 }
4884
4885 htx_to_buf(htx, &res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01004886 channel_add_input(res, htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004887
4888 /* Headers sent, set the flag. */
4889 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4890 return 0;
4891
4892}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004893/* We will build the status line and the headers of the HTTP response.
4894 * We will try send at once if its not possible, we give back the hand
4895 * waiting for more room.
4896 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004897__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004898{
4899 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4900 struct stream_interface *si = appctx->appctx->owner;
4901 struct channel *res = si_ic(si);
4902
4903 if (co_data(res)) {
4904 si_rx_room_blk(si);
Christopher Fauleta2097962019-07-15 16:25:33 +02004905 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004906 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004907 return MAY_LJMP(hlua_applet_http_send_response(L));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004908}
4909
4910
Christopher Fauleta2097962019-07-15 16:25:33 +02004911__LJMP static int hlua_applet_http_start_response(lua_State *L)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004912{
Christopher Fauleta2097962019-07-15 16:25:33 +02004913 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004914}
4915
Christopher Fauleta2097962019-07-15 16:25:33 +02004916/*
4917 *
4918 *
4919 * Class HTTP
4920 *
4921 *
Christopher Faulet9c832fc2018-12-14 13:34:05 +01004922 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004923
4924/* Returns a struct hlua_txn if the stack entry "ud" is
4925 * a class stream, otherwise it throws an error.
4926 */
4927__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004928{
Christopher Fauleta2097962019-07-15 16:25:33 +02004929 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
4930}
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004931
Christopher Fauleta2097962019-07-15 16:25:33 +02004932/* This function creates and push in the stack a HTTP object
4933 * according with a current TXN.
4934 */
4935static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4936{
4937 struct hlua_txn *htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004938
Christopher Fauleta2097962019-07-15 16:25:33 +02004939 /* Check stack size. */
4940 if (!lua_checkstack(L, 3))
4941 return 0;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004942
Christopher Fauleta2097962019-07-15 16:25:33 +02004943 /* Create the object: obj[0] = userdata.
4944 * Note that the base of the Converters object is the
4945 * same than the TXN object.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004946 */
Christopher Fauleta2097962019-07-15 16:25:33 +02004947 lua_newtable(L);
4948 htxn = lua_newuserdata(L, sizeof(*htxn));
4949 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004950
4951 htxn->s = txn->s;
4952 htxn->p = txn->p;
Christopher Faulet256b69a2019-05-23 11:14:21 +02004953 htxn->dir = txn->dir;
4954 htxn->flags = txn->flags;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004955
4956 /* Pop a class stream metatable and affect it to the table. */
4957 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4958 lua_setmetatable(L, -2);
4959
4960 return 1;
4961}
4962
4963/* This function creates ans returns an array of HTTP headers.
4964 * This function does not fails. It is used as wrapper with the
4965 * 2 following functions.
4966 */
Christopher Faulet9d1332b2020-02-24 16:46:16 +01004967__LJMP static int hlua_http_get_headers(lua_State *L, struct http_msg *msg)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004968{
Christopher Fauleta2097962019-07-15 16:25:33 +02004969 struct htx *htx;
4970 int32_t pos;
4971
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004972 /* Create the table. */
4973 lua_newtable(L);
4974
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004975
Christopher Fauleta2097962019-07-15 16:25:33 +02004976 htx = htxbuf(&msg->chn->buf);
4977 for (pos = htx_get_first(htx); pos != -1; pos = htx_get_next(htx, pos)) {
4978 struct htx_blk *blk = htx_get_blk(htx, pos);
4979 enum htx_blk_type type = htx_get_blk_type(blk);
4980 struct ist n, v;
4981 int len;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004982
Christopher Fauleta2097962019-07-15 16:25:33 +02004983 if (type == HTX_BLK_HDR) {
4984 n = htx_get_blk_name(htx,blk);
4985 v = htx_get_blk_value(htx, blk);
Christopher Faulet724a12c2018-12-13 22:12:15 +01004986 }
Christopher Fauleta2097962019-07-15 16:25:33 +02004987 else if (type == HTX_BLK_EOH)
4988 break;
4989 else
4990 continue;
Christopher Faulet724a12c2018-12-13 22:12:15 +01004991
Christopher Fauleta2097962019-07-15 16:25:33 +02004992 /* Check for existing entry:
4993 * assume that the table is on the top of the stack, and
4994 * push the key in the stack, the function lua_gettable()
4995 * perform the lookup.
4996 */
4997 lua_pushlstring(L, n.ptr, n.len);
4998 lua_gettable(L, -2);
Christopher Faulet724a12c2018-12-13 22:12:15 +01004999
Christopher Fauleta2097962019-07-15 16:25:33 +02005000 switch (lua_type(L, -1)) {
5001 case LUA_TNIL:
5002 /* Table not found, create it. */
5003 lua_pop(L, 1); /* remove the nil value. */
5004 lua_pushlstring(L, n.ptr, n.len); /* push the header name as key. */
5005 lua_newtable(L); /* create and push empty table. */
5006 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5007 lua_rawseti(L, -2, 0); /* index header value (pop it). */
5008 lua_rawset(L, -3); /* index new table with header name (pop the values). */
Christopher Faulet724a12c2018-12-13 22:12:15 +01005009 break;
Christopher Faulet724a12c2018-12-13 22:12:15 +01005010
Christopher Fauleta2097962019-07-15 16:25:33 +02005011 case LUA_TTABLE:
5012 /* Entry found: push the value in the table. */
5013 len = lua_rawlen(L, -1);
5014 lua_pushlstring(L, v.ptr, v.len); /* push header value. */
5015 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
5016 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
5017 break;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005018
Christopher Fauleta2097962019-07-15 16:25:33 +02005019 default:
5020 /* Other cases are errors. */
5021 hlua_pusherror(L, "internal error during the parsing of headers.");
5022 WILL_LJMP(lua_error(L));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005023 }
5024 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005025 return 1;
5026}
5027
5028__LJMP static int hlua_http_req_get_headers(lua_State *L)
5029{
5030 struct hlua_txn *htxn;
5031
5032 MAY_LJMP(check_args(L, 1, "req_get_headers"));
5033 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5034
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005035 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005036 WILL_LJMP(lua_error(L));
5037
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005038 return hlua_http_get_headers(L, &htxn->s->txn->req);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005039}
5040
5041__LJMP static int hlua_http_res_get_headers(lua_State *L)
5042{
5043 struct hlua_txn *htxn;
5044
5045 MAY_LJMP(check_args(L, 1, "res_get_headers"));
5046 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5047
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005048 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005049 WILL_LJMP(lua_error(L));
5050
Christopher Faulet9d1332b2020-02-24 16:46:16 +01005051 return hlua_http_get_headers(L, &htxn->s->txn->rsp);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005052}
5053
5054/* This function replace full header, or just a value in
5055 * the request or in the response. It is a wrapper fir the
5056 * 4 following functions.
5057 */
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005058__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct http_msg *msg, int full)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005059{
5060 size_t name_len;
5061 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5062 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
5063 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
Christopher Fauleta2097962019-07-15 16:25:33 +02005064 struct htx *htx;
Dragan Dosen26743032019-04-30 15:54:36 +02005065 struct my_regex *re;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005066
Dragan Dosen26743032019-04-30 15:54:36 +02005067 if (!(re = regex_comp(reg, 1, 1, NULL)))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005068 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
5069
Christopher Fauleta2097962019-07-15 16:25:33 +02005070 htx = htxbuf(&msg->chn->buf);
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005071 http_replace_hdrs(chn_strm(msg->chn), htx, ist2(name, name_len), value, re, full);
Dragan Dosen26743032019-04-30 15:54:36 +02005072 regex_free(re);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005073 return 0;
5074}
5075
5076__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
5077{
5078 struct hlua_txn *htxn;
5079
5080 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5081 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5082
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005083 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005084 WILL_LJMP(lua_error(L));
5085
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005086 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005087}
5088
5089__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
5090{
5091 struct hlua_txn *htxn;
5092
5093 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
5094 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5095
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005096 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005097 WILL_LJMP(lua_error(L));
5098
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005099 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005100}
5101
5102__LJMP static int hlua_http_req_rep_val(lua_State *L)
5103{
5104 struct hlua_txn *htxn;
5105
5106 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
5107 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5108
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005109 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005110 WILL_LJMP(lua_error(L));
5111
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005112 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->req, 0));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02005113}
5114
5115__LJMP static int hlua_http_res_rep_val(lua_State *L)
5116{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005117 struct hlua_txn *htxn;
5118
5119 MAY_LJMP(check_args(L, 4, "res_rep_val"));
5120 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5121
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005122 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005123 WILL_LJMP(lua_error(L));
5124
Christopher Fauletd1914aa2020-02-24 16:52:46 +01005125 return MAY_LJMP(hlua_http_rep_hdr(L, &htxn->s->txn->rsp, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005126}
5127
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005128/* This function deletes all the occurrences of an header.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005129 * It is a wrapper for the 2 following functions.
5130 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005131__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005132{
5133 size_t len;
5134 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005135 struct htx *htx = htxbuf(&msg->chn->buf);
5136 struct http_hdr_ctx ctx;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005137
Christopher Fauleta2097962019-07-15 16:25:33 +02005138 ctx.blk = NULL;
5139 while (http_find_header(htx, ist2(name, len), &ctx, 1))
5140 http_remove_header(htx, &ctx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005141 return 0;
5142}
5143
5144__LJMP static int hlua_http_req_del_hdr(lua_State *L)
5145{
5146 struct hlua_txn *htxn;
5147
5148 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
5149 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5150
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005151 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005152 WILL_LJMP(lua_error(L));
5153
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005154 return hlua_http_del_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005155}
5156
5157__LJMP static int hlua_http_res_del_hdr(lua_State *L)
5158{
5159 struct hlua_txn *htxn;
5160
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005161 MAY_LJMP(check_args(L, 2, "res_del_hdr"));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005162 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5163
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005164 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005165 WILL_LJMP(lua_error(L));
5166
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005167 return hlua_http_del_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005168}
5169
5170/* This function adds an header. It is a wrapper used by
5171 * the 2 following functions.
5172 */
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005173__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct http_msg *msg)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005174{
5175 size_t name_len;
5176 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
5177 size_t value_len;
5178 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
Christopher Fauleta2097962019-07-15 16:25:33 +02005179 struct htx *htx = htxbuf(&msg->chn->buf);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005180
Christopher Fauleta2097962019-07-15 16:25:33 +02005181 lua_pushboolean(L, http_add_header(htx, ist2(name, name_len),
5182 ist2(value, value_len)));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005183 return 0;
5184}
5185
5186__LJMP static int hlua_http_req_add_hdr(lua_State *L)
5187{
5188 struct hlua_txn *htxn;
5189
5190 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
5191 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5192
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005193 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005194 WILL_LJMP(lua_error(L));
5195
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005196 return hlua_http_add_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005197}
5198
5199__LJMP static int hlua_http_res_add_hdr(lua_State *L)
5200{
5201 struct hlua_txn *htxn;
5202
5203 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
5204 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5205
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005206 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005207 WILL_LJMP(lua_error(L));
5208
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005209 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005210}
5211
5212static int hlua_http_req_set_hdr(lua_State *L)
5213{
5214 struct hlua_txn *htxn;
5215
5216 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
5217 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5218
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005219 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005220 WILL_LJMP(lua_error(L));
5221
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005222 hlua_http_del_hdr(L, &htxn->s->txn->req);
5223 return hlua_http_add_hdr(L, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005224}
5225
5226static int hlua_http_res_set_hdr(lua_State *L)
5227{
5228 struct hlua_txn *htxn;
5229
5230 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
5231 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5232
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005233 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005234 WILL_LJMP(lua_error(L));
5235
Christopher Fauletd31c7b32020-02-25 09:37:57 +01005236 hlua_http_del_hdr(L, &htxn->s->txn->rsp);
5237 return hlua_http_add_hdr(L, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005238}
5239
5240/* This function set the method. */
5241static int hlua_http_req_set_meth(lua_State *L)
5242{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005243 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005244 size_t name_len;
5245 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005246
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005247 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005248 WILL_LJMP(lua_error(L));
5249
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005250 lua_pushboolean(L, http_req_replace_stline(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005251 return 1;
5252}
5253
5254/* This function set the method. */
5255static int hlua_http_req_set_path(lua_State *L)
5256{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005257 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005258 size_t name_len;
5259 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005260
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005261 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005262 WILL_LJMP(lua_error(L));
5263
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005264 lua_pushboolean(L, http_req_replace_stline(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005265 return 1;
5266}
5267
5268/* This function set the query-string. */
5269static int hlua_http_req_set_query(lua_State *L)
5270{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005271 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005272 size_t name_len;
5273 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005274
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005275 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005276 WILL_LJMP(lua_error(L));
5277
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005278 /* Check length. */
5279 if (name_len > trash.size - 1) {
5280 lua_pushboolean(L, 0);
5281 return 1;
5282 }
5283
5284 /* Add the mark question as prefix. */
5285 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005286 trash.area[trash.data++] = '?';
5287 memcpy(trash.area + trash.data, name, name_len);
5288 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005289
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005290 lua_pushboolean(L,
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005291 http_req_replace_stline(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005292 return 1;
5293}
5294
5295/* This function set the uri. */
5296static int hlua_http_req_set_uri(lua_State *L)
5297{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005298 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005299 size_t name_len;
5300 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005301
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005302 if (htxn->dir != SMP_OPT_DIR_REQ || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005303 WILL_LJMP(lua_error(L));
5304
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005305 lua_pushboolean(L, http_req_replace_stline(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005306 return 1;
5307}
5308
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005309/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005310static int hlua_http_res_set_status(lua_State *L)
5311{
5312 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5313 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Christopher Faulet96bff762019-12-17 13:46:18 +01005314 const char *str = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
5315 const struct ist reason = ist2(str, (str ? strlen(str) : 0));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005316
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005317 if (htxn->dir != SMP_OPT_DIR_RES || !IS_HTX_STRM(htxn->s))
Christopher Faulet84a6d5b2019-07-26 16:17:01 +02005318 WILL_LJMP(lua_error(L));
5319
Christopher Fauletfc9cfe42019-07-16 14:54:53 +02005320 http_res_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005321 return 0;
5322}
5323
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005324/*
5325 *
5326 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005327 * Class TXN
5328 *
5329 *
5330 */
5331
5332/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005333 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005334 */
5335__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5336{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005337 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005338}
5339
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005340__LJMP static int hlua_set_var(lua_State *L)
5341{
5342 struct hlua_txn *htxn;
5343 const char *name;
5344 size_t len;
5345 struct sample smp;
5346
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005347 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
5348 WILL_LJMP(luaL_error(L, "'set_var' needs between 3 and 4 arguments"));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005349
5350 /* It is useles to retrieve the stream, but this function
5351 * runs only in a stream context.
5352 */
5353 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5354 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5355
5356 /* Converts the third argument in a sample. */
Amaury Denoyellebc0af6a2020-10-29 17:21:20 +01005357 memset(&smp, 0, sizeof(smp));
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005358 hlua_lua2smp(L, 3, &smp);
5359
5360 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005361 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus4e172c92020-05-19 13:49:42 +02005362
5363 if (lua_gettop(L) == 4 && lua_toboolean(L, 4))
5364 lua_pushboolean(L, vars_set_by_name_ifexist(name, len, &smp) != 0);
5365 else
5366 lua_pushboolean(L, vars_set_by_name(name, len, &smp) != 0);
5367
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005368 return 1;
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005369}
5370
Christopher Faulet85d79c92016-11-09 16:54:56 +01005371__LJMP static int hlua_unset_var(lua_State *L)
5372{
5373 struct hlua_txn *htxn;
5374 const char *name;
5375 size_t len;
5376 struct sample smp;
5377
5378 MAY_LJMP(check_args(L, 2, "unset_var"));
5379
5380 /* It is useles to retrieve the stream, but this function
5381 * runs only in a stream context.
5382 */
5383 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5384 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5385
5386 /* Unset the variable. */
5387 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Tim Duesterhus84ebc132020-05-19 13:49:41 +02005388 lua_pushboolean(L, vars_unset_by_name_ifexist(name, len, &smp) != 0);
5389 return 1;
Christopher Faulet85d79c92016-11-09 16:54:56 +01005390}
5391
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005392__LJMP static int hlua_get_var(lua_State *L)
5393{
5394 struct hlua_txn *htxn;
5395 const char *name;
5396 size_t len;
5397 struct sample smp;
5398
5399 MAY_LJMP(check_args(L, 2, "get_var"));
5400
5401 /* It is useles to retrieve the stream, but this function
5402 * runs only in a stream context.
5403 */
5404 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5405 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5406
Willy Tarreau7560dd42016-03-10 16:28:58 +01005407 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005408 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005409 lua_pushnil(L);
5410 return 1;
5411 }
5412
5413 return hlua_smp2lua(L, &smp);
5414}
5415
Willy Tarreau59551662015-03-10 14:23:13 +01005416__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005417{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005418 struct hlua *hlua;
5419
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005420 MAY_LJMP(check_args(L, 2, "set_priv"));
5421
Willy Tarreau87b09662015-04-03 00:22:06 +02005422 /* It is useles to retrieve the stream, but this function
5423 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005424 */
5425 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01005426
5427 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005428 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01005429 if (!hlua)
5430 return 0;
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005431
5432 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005433 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005434
5435 /* Get and store new value. */
5436 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5437 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5438
5439 return 0;
5440}
5441
Willy Tarreau59551662015-03-10 14:23:13 +01005442__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005443{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005444 struct hlua *hlua;
5445
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005446 MAY_LJMP(check_args(L, 1, "get_priv"));
5447
Willy Tarreau87b09662015-04-03 00:22:06 +02005448 /* It is useles to retrieve the stream, but this function
5449 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005450 */
5451 MAY_LJMP(hlua_checktxn(L, 1));
Thierry Fournier4234dbd2020-11-28 13:18:23 +01005452
5453 /* Get hlua struct, or NULL if we execute from main lua state */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005454 hlua = hlua_gethlua(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01005455 if (!hlua) {
5456 lua_pushnil(L);
5457 return 1;
5458 }
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005459
5460 /* Push configuration index in the stack. */
5461 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5462
5463 return 1;
5464}
5465
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005466/* Create stack entry containing a class TXN. This function
5467 * return 0 if the stack does not contains free slots,
5468 * otherwise it returns 1.
5469 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005470static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005471{
Willy Tarreaude491382015-04-06 11:04:28 +02005472 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005473
5474 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005475 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005476 return 0;
5477
5478 /* NOTE: The allocation never fails. The failure
5479 * throw an error, and the function never returns.
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08005480 * if the throw is not available, the process is aborted.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005481 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005482 /* Create the object: obj[0] = userdata. */
5483 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005484 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005485 lua_rawseti(L, -2, 0);
5486
Willy Tarreaude491382015-04-06 11:04:28 +02005487 htxn->s = s;
5488 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005489 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005490 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005491
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005492 /* Create the "f" field that contains a list of fetches. */
5493 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005494 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005495 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005496 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005497
5498 /* Create the "sf" field that contains a list of stringsafe fetches. */
5499 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005500 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005501 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005502 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005503
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005504 /* Create the "c" field that contains a list of converters. */
5505 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005506 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005507 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005508 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005509
5510 /* Create the "sc" field that contains a list of stringsafe converters. */
5511 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005512 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005513 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005514 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005515
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005516 /* Create the "req" field that contains the request channel object. */
5517 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005518 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005519 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005520 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005521
5522 /* Create the "res" field that contains the response channel object. */
5523 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005524 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005525 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005526 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005527
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005528 /* Creates the HTTP object is the current proxy allows http. */
5529 lua_pushstring(L, "http");
Christopher Faulet1bb6afa2021-03-08 17:57:53 +01005530 if (IS_HTX_STRM(s)) {
Willy Tarreaude491382015-04-06 11:04:28 +02005531 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005532 return 0;
5533 }
5534 else
5535 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005536 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005537
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005538 /* Pop a class sesison metatable and affect it to the userdata. */
5539 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5540 lua_setmetatable(L, -2);
5541
5542 return 1;
5543}
5544
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005545__LJMP static int hlua_txn_deflog(lua_State *L)
5546{
5547 const char *msg;
5548 struct hlua_txn *htxn;
5549
5550 MAY_LJMP(check_args(L, 2, "deflog"));
5551 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5552 msg = MAY_LJMP(luaL_checkstring(L, 2));
5553
5554 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5555 return 0;
5556}
5557
5558__LJMP static int hlua_txn_log(lua_State *L)
5559{
5560 int level;
5561 const char *msg;
5562 struct hlua_txn *htxn;
5563
5564 MAY_LJMP(check_args(L, 3, "log"));
5565 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5566 level = MAY_LJMP(luaL_checkinteger(L, 2));
5567 msg = MAY_LJMP(luaL_checkstring(L, 3));
5568
5569 if (level < 0 || level >= NB_LOG_LEVELS)
5570 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5571
5572 hlua_sendlog(htxn->s->be, level, msg);
5573 return 0;
5574}
5575
5576__LJMP static int hlua_txn_log_debug(lua_State *L)
5577{
5578 const char *msg;
5579 struct hlua_txn *htxn;
5580
5581 MAY_LJMP(check_args(L, 2, "Debug"));
5582 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5583 msg = MAY_LJMP(luaL_checkstring(L, 2));
5584 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5585 return 0;
5586}
5587
5588__LJMP static int hlua_txn_log_info(lua_State *L)
5589{
5590 const char *msg;
5591 struct hlua_txn *htxn;
5592
5593 MAY_LJMP(check_args(L, 2, "Info"));
5594 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5595 msg = MAY_LJMP(luaL_checkstring(L, 2));
5596 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5597 return 0;
5598}
5599
5600__LJMP static int hlua_txn_log_warning(lua_State *L)
5601{
5602 const char *msg;
5603 struct hlua_txn *htxn;
5604
5605 MAY_LJMP(check_args(L, 2, "Warning"));
5606 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5607 msg = MAY_LJMP(luaL_checkstring(L, 2));
5608 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5609 return 0;
5610}
5611
5612__LJMP static int hlua_txn_log_alert(lua_State *L)
5613{
5614 const char *msg;
5615 struct hlua_txn *htxn;
5616
5617 MAY_LJMP(check_args(L, 2, "Alert"));
5618 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5619 msg = MAY_LJMP(luaL_checkstring(L, 2));
5620 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5621 return 0;
5622}
5623
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005624__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5625{
5626 struct hlua_txn *htxn;
5627 int ll;
5628
5629 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5630 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5631 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5632
5633 if (ll < 0 || ll > 7)
5634 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5635
5636 htxn->s->logs.level = ll;
5637 return 0;
5638}
5639
5640__LJMP static int hlua_txn_set_tos(lua_State *L)
5641{
5642 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005643 int tos;
5644
5645 MAY_LJMP(check_args(L, 2, "set_tos"));
5646 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5647 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5648
Willy Tarreau1a18b542018-12-11 16:37:42 +01005649 conn_set_tos(objt_conn(htxn->s->sess->origin), tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005650 return 0;
5651}
5652
5653__LJMP static int hlua_txn_set_mark(lua_State *L)
5654{
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005655 struct hlua_txn *htxn;
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005656 int mark;
5657
5658 MAY_LJMP(check_args(L, 2, "set_mark"));
5659 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5660 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5661
Lukas Tribus579e3e32019-08-11 18:03:45 +02005662 conn_set_mark(objt_conn(htxn->s->sess->origin), mark);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005663 return 0;
5664}
5665
Patrick Hemmer268a7072018-05-11 12:52:31 -04005666__LJMP static int hlua_txn_set_priority_class(lua_State *L)
5667{
5668 struct hlua_txn *htxn;
5669
5670 MAY_LJMP(check_args(L, 2, "set_priority_class"));
5671 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5672 htxn->s->priority_class = queue_limit_class(MAY_LJMP(luaL_checkinteger(L, 2)));
5673 return 0;
5674}
5675
5676__LJMP static int hlua_txn_set_priority_offset(lua_State *L)
5677{
5678 struct hlua_txn *htxn;
5679
5680 MAY_LJMP(check_args(L, 2, "set_priority_offset"));
5681 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5682 htxn->s->priority_offset = queue_limit_offset(MAY_LJMP(luaL_checkinteger(L, 2)));
5683 return 0;
5684}
5685
Christopher Faulet700d9e82020-01-31 12:21:52 +01005686/* Forward the Reply object to the client. This function converts the reply in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05005687 * HTX an push it to into the response channel. It is response to forward the
Christopher Faulet700d9e82020-01-31 12:21:52 +01005688 * message and terminate the transaction. It returns 1 on success and 0 on
5689 * error. The Reply must be on top of the stack.
5690 */
5691__LJMP static int hlua_txn_forward_reply(lua_State *L, struct stream *s)
5692{
5693 struct htx *htx;
5694 struct htx_sl *sl;
5695 struct h1m h1m;
5696 const char *status, *reason, *body;
5697 size_t status_len, reason_len, body_len;
5698 int ret, code, flags;
5699
5700 code = 200;
5701 status = "200";
5702 status_len = 3;
5703 ret = lua_getfield(L, -1, "status");
5704 if (ret == LUA_TNUMBER) {
5705 code = lua_tointeger(L, -1);
5706 status = lua_tolstring(L, -1, &status_len);
5707 }
5708 lua_pop(L, 1);
5709
5710 reason = http_get_reason(code);
5711 reason_len = strlen(reason);
5712 ret = lua_getfield(L, -1, "reason");
5713 if (ret == LUA_TSTRING)
5714 reason = lua_tolstring(L, -1, &reason_len);
5715 lua_pop(L, 1);
5716
5717 body = NULL;
5718 body_len = 0;
5719 ret = lua_getfield(L, -1, "body");
5720 if (ret == LUA_TSTRING)
5721 body = lua_tolstring(L, -1, &body_len);
5722 lua_pop(L, 1);
5723
5724 /* Prepare the response before inserting the headers */
5725 h1m_init_res(&h1m);
5726 htx = htx_from_buf(&s->res.buf);
5727 channel_htx_truncate(&s->res, htx);
5728 if (s->txn->req.flags & HTTP_MSGF_VER_11) {
5729 flags = (HTX_SL_F_IS_RESP|HTX_SL_F_VER_11);
5730 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.1"),
5731 ist2(status, status_len), ist2(reason, reason_len));
5732 }
5733 else {
5734 flags = HTX_SL_F_IS_RESP;
5735 sl = htx_add_stline(htx, HTX_BLK_RES_SL, flags, ist("HTTP/1.0"),
5736 ist2(status, status_len), ist2(reason, reason_len));
5737 }
5738 if (!sl)
5739 goto fail;
5740 sl->info.res.status = code;
5741
5742 /* Push in the stack the "headers" entry. */
5743 ret = lua_getfield(L, -1, "headers");
5744 if (ret != LUA_TTABLE)
5745 goto skip_headers;
5746
5747 lua_pushnil(L);
5748 while (lua_next(L, -2) != 0) {
5749 struct ist name, value;
5750 const char *n, *v;
5751 size_t nlen, vlen;
5752
5753 if (!lua_isstring(L, -2) || !lua_istable(L, -1)) {
5754 /* Skip element if the key is not a string or if the value is not a table */
5755 goto next_hdr;
5756 }
5757
5758 n = lua_tolstring(L, -2, &nlen);
5759 name = ist2(n, nlen);
5760 if (isteqi(name, ist("content-length"))) {
5761 /* Always skip content-length header. It will be added
5762 * later with the correct len
5763 */
5764 goto next_hdr;
5765 }
5766
5767 /* Loop on header's values */
5768 lua_pushnil(L);
5769 while (lua_next(L, -2)) {
5770 if (!lua_isstring(L, -1)) {
5771 /* Skip the value if it is not a string */
5772 goto next_value;
5773 }
5774
5775 v = lua_tolstring(L, -1, &vlen);
5776 value = ist2(v, vlen);
5777
5778 if (isteqi(name, ist("transfer-encoding")))
5779 h1_parse_xfer_enc_header(&h1m, value);
5780 if (!htx_add_header(htx, ist2(n, nlen), ist2(v, vlen)))
5781 goto fail;
5782
5783 next_value:
5784 lua_pop(L, 1);
5785 }
5786
5787 next_hdr:
5788 lua_pop(L, 1);
5789 }
5790 skip_headers:
5791 lua_pop(L, 1);
5792
5793 /* Update h1m flags: CLEN is set if CHNK is not present */
5794 if (!(h1m.flags & H1_MF_CHNK)) {
5795 const char *clen = ultoa(body_len);
5796
5797 h1m.flags |= H1_MF_CLEN;
5798 if (!htx_add_header(htx, ist("content-length"), ist(clen)))
5799 goto fail;
5800 }
5801 if (h1m.flags & (H1_MF_CLEN|H1_MF_CHNK))
5802 h1m.flags |= H1_MF_XFER_LEN;
5803
5804 /* Update HTX start-line flags */
5805 if (h1m.flags & H1_MF_XFER_ENC)
5806 flags |= HTX_SL_F_XFER_ENC;
5807 if (h1m.flags & H1_MF_XFER_LEN) {
5808 flags |= HTX_SL_F_XFER_LEN;
5809 if (h1m.flags & H1_MF_CHNK)
5810 flags |= HTX_SL_F_CHNK;
5811 else if (h1m.flags & H1_MF_CLEN)
5812 flags |= HTX_SL_F_CLEN;
5813 if (h1m.body_len == 0)
5814 flags |= HTX_SL_F_BODYLESS;
5815 }
5816 sl->flags |= flags;
5817
5818
5819 if (!htx_add_endof(htx, HTX_BLK_EOH) ||
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005820 (body_len && !htx_add_data_atonce(htx, ist2(body, body_len))))
Christopher Faulet700d9e82020-01-31 12:21:52 +01005821 goto fail;
5822
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01005823 htx->flags |= HTX_FL_EOM;
5824
Christopher Faulet700d9e82020-01-31 12:21:52 +01005825 /* Now, forward the response and terminate the transaction */
5826 s->txn->status = code;
5827 htx_to_buf(htx, &s->res.buf);
5828 if (!http_forward_proxy_resp(s, 1))
5829 goto fail;
5830
5831 return 1;
5832
5833 fail:
5834 channel_htx_truncate(&s->res, htx);
5835 return 0;
5836}
5837
5838/* Terminate a transaction if called from a lua action. For TCP streams,
5839 * processing is just aborted. Nothing is returned to the client and all
5840 * arguments are ignored. For HTTP streams, if a reply is passed as argument, it
5841 * is forwarded to the client before terminating the transaction. On success,
5842 * the function exits with ACT_RET_DONE code. If an error occurred, it exits
5843 * with ACT_RET_ERR code. If this function is not called from a lua action, it
5844 * just exits without any processing.
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005845 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005846__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005847{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005848 struct hlua_txn *htxn;
Christopher Faulet700d9e82020-01-31 12:21:52 +01005849 struct stream *s;
5850 int finst;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005851
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005852 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005853
Christopher Faulet700d9e82020-01-31 12:21:52 +01005854 /* If the flags NOTERM is set, we cannot terminate the session, so we
5855 * just end the execution of the current lua code. */
5856 if (htxn->flags & HLUA_TXN_NOTERM)
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005857 WILL_LJMP(hlua_done(L));
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005858
Christopher Faulet700d9e82020-01-31 12:21:52 +01005859 s = htxn->s;
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005860 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01005861 struct channel *req = &s->req;
5862 struct channel *res = &s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005863
Christopher Faulet700d9e82020-01-31 12:21:52 +01005864 channel_auto_read(req);
5865 channel_abort(req);
5866 channel_auto_close(req);
5867 channel_erase(req);
5868
5869 res->wex = tick_add_ifset(now_ms, res->wto);
5870 channel_auto_read(res);
5871 channel_auto_close(res);
5872 channel_shutr_now(res);
5873
5874 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_D);
5875 goto done;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005876 }
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005877
Christopher Faulet700d9e82020-01-31 12:21:52 +01005878 if (lua_gettop(L) == 1 || !lua_istable(L, 2)) {
5879 /* No reply or invalid reply */
5880 s->txn->status = 0;
5881 http_reply_and_close(s, 0, NULL);
5882 }
5883 else {
5884 /* Remove extra args to have the reply on top of the stack */
5885 if (lua_gettop(L) > 2)
5886 lua_pop(L, lua_gettop(L) - 2);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005887
Christopher Faulet700d9e82020-01-31 12:21:52 +01005888 if (!hlua_txn_forward_reply(L, s)) {
5889 if (!(s->flags & SF_ERR_MASK))
5890 s->flags |= SF_ERR_PRXCOND;
5891 lua_pushinteger(L, ACT_RET_ERR);
5892 WILL_LJMP(hlua_done(L));
5893 return 0; /* Never reached */
5894 }
Christopher Faulet4d0e2632019-07-16 10:52:40 +02005895 }
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005896
Christopher Faulet700d9e82020-01-31 12:21:52 +01005897 finst = ((htxn->dir == SMP_OPT_DIR_REQ) ? SF_FINST_R : SF_FINST_H);
5898 if (htxn->dir == SMP_OPT_DIR_REQ) {
5899 /* let's log the request time */
5900 s->logs.tv_request = now;
5901 if (s->sess->fe == s->be) /* report it if the request was intercepted by the frontend */
Willy Tarreau4781b152021-04-06 13:53:36 +02005902 _HA_ATOMIC_INC(&s->sess->fe->fe_counters.intercepted_req);
Christopher Faulet700d9e82020-01-31 12:21:52 +01005903 }
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005904
Christopher Faulet700d9e82020-01-31 12:21:52 +01005905 done:
5906 if (!(s->flags & SF_ERR_MASK))
5907 s->flags |= SF_ERR_LOCAL;
5908 if (!(s->flags & SF_FINST_MASK))
5909 s->flags |= finst;
Christopher Fauletfe6a71b2019-07-26 16:40:24 +02005910
Christopher Faulet4ad73102020-03-05 11:07:31 +01005911 lua_pushinteger(L, ACT_RET_ABRT);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005912 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005913 return 0;
5914}
5915
Christopher Faulet700d9e82020-01-31 12:21:52 +01005916/*
5917 *
5918 *
5919 * Class REPLY
5920 *
5921 *
5922 */
5923
5924/* Pushes the TXN reply onto the top of the stack. If the stask does not have a
5925 * free slots, the function fails and returns 0;
5926 */
5927static int hlua_txn_reply_new(lua_State *L)
5928{
5929 struct hlua_txn *htxn;
5930 const char *reason, *body = NULL;
5931 int ret, status;
5932
5933 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Christopher Fauletd8f0e072020-02-25 09:45:51 +01005934 if (!IS_HTX_STRM(htxn->s)) {
Christopher Faulet700d9e82020-01-31 12:21:52 +01005935 hlua_pusherror(L, "txn object is not an HTTP transaction.");
5936 WILL_LJMP(lua_error(L));
5937 }
5938
5939 /* Default value */
5940 status = 200;
5941 reason = http_get_reason(status);
5942
5943 if (lua_istable(L, 2)) {
5944 /* load status and reason from the table argument at index 2 */
5945 ret = lua_getfield(L, 2, "status");
5946 if (ret == LUA_TNIL)
5947 goto reason;
5948 else if (ret != LUA_TNUMBER) {
5949 /* invalid status: ignore the reason */
5950 goto body;
5951 }
5952 status = lua_tointeger(L, -1);
5953
5954 reason:
5955 lua_pop(L, 1); /* restore the stack: remove status */
5956 ret = lua_getfield(L, 2, "reason");
5957 if (ret == LUA_TSTRING)
5958 reason = lua_tostring(L, -1);
5959
5960 body:
5961 lua_pop(L, 1); /* restore the stack: remove invalid status or reason */
5962 ret = lua_getfield(L, 2, "body");
5963 if (ret == LUA_TSTRING)
5964 body = lua_tostring(L, -1);
5965 lua_pop(L, 1); /* restore the stack: remove body */
5966 }
5967
5968 /* Create the Reply table */
5969 lua_newtable(L);
5970
5971 /* Add status element */
5972 lua_pushstring(L, "status");
5973 lua_pushinteger(L, status);
5974 lua_settable(L, -3);
5975
5976 /* Add reason element */
5977 reason = http_get_reason(status);
5978 lua_pushstring(L, "reason");
5979 lua_pushstring(L, reason);
5980 lua_settable(L, -3);
5981
5982 /* Add body element, nil if undefined */
5983 lua_pushstring(L, "body");
5984 if (body)
5985 lua_pushstring(L, body);
5986 else
5987 lua_pushnil(L);
5988 lua_settable(L, -3);
5989
5990 /* Add headers element */
5991 lua_pushstring(L, "headers");
5992 lua_newtable(L);
5993
5994 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
5995 if (lua_istable(L, 2)) {
5996 /* load headers from the table argument at index 2. If it is a table, copy it. */
5997 ret = lua_getfield(L, 2, "headers");
5998 if (ret == LUA_TTABLE) {
5999 /* stack: [ ... <headers:table>, <table> ] */
6000 lua_pushnil(L);
6001 while (lua_next(L, -2) != 0) {
6002 /* stack: [ ... <headers:table>, <table>, k, v] */
6003 if (!lua_isstring(L, -1) && !lua_istable(L, -1)) {
6004 /* invalid value type, skip it */
6005 lua_pop(L, 1);
6006 continue;
6007 }
6008
6009
6010 /* Duplicate the key and swap it with the value. */
6011 lua_pushvalue(L, -2);
6012 lua_insert(L, -2);
6013 /* stack: [ ... <headers:table>, <table>, k, k, v ] */
6014
6015 lua_newtable(L);
6016 lua_insert(L, -2);
6017 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, v ] */
6018
6019 if (lua_isstring(L, -1)) {
6020 /* push the value in the inner table */
6021 lua_rawseti(L, -2, 1);
6022 }
6023 else { /* table */
6024 lua_pushnil(L);
6025 while (lua_next(L, -2) != 0) {
6026 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2, v2 ] */
6027 if (!lua_isstring(L, -1)) {
6028 /* invalid value type, skip it*/
6029 lua_pop(L, 1);
6030 continue;
6031 }
6032 /* push the value in the inner table */
6033 lua_rawseti(L, -4, lua_rawlen(L, -4) + 1);
6034 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table>, <v:table>, k2 ] */
6035 }
6036 lua_pop(L, 1);
6037 /* stack: [ ... <headers:table>, <table>, k, k, <inner:table> ] */
6038 }
6039
6040 /* push (k,v) on the stack in the headers table:
6041 * stack: [ ... <headers:table>, <table>, k, k, v ]
6042 */
6043 lua_settable(L, -5);
6044 /* stack: [ ... <headers:table>, <table>, k ] */
6045 }
6046 }
6047 lua_pop(L, 1);
6048 }
6049 /* stack: [ txn, <Arg:table>, <Reply:table>, "headers", <headers:table> ] */
6050 lua_settable(L, -3);
6051 /* stack: [ txn, <Arg:table>, <Reply:table> ] */
6052
6053 /* Pop a class sesison metatable and affect it to the userdata. */
6054 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_reply_ref);
6055 lua_setmetatable(L, -2);
6056 return 1;
6057}
6058
6059/* Set the reply status code, and optionally the reason. If no reason is
6060 * provided, the default one corresponding to the status code is used.
6061 */
6062__LJMP static int hlua_txn_reply_set_status(lua_State *L)
6063{
6064 int status = MAY_LJMP(luaL_checkinteger(L, 2));
6065 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
6066
6067 /* First argument (self) must be a table */
6068 luaL_checktype(L, 1, LUA_TTABLE);
6069
6070 if (status < 100 || status > 599) {
6071 lua_pushboolean(L, 0);
6072 return 1;
6073 }
6074 if (!reason)
6075 reason = http_get_reason(status);
6076
6077 lua_pushinteger(L, status);
6078 lua_setfield(L, 1, "status");
6079
6080 lua_pushstring(L, reason);
6081 lua_setfield(L, 1, "reason");
6082
6083 lua_pushboolean(L, 1);
6084 return 1;
6085}
6086
6087/* Add a header into the reply object. Each header name is associated to an
6088 * array of values in the "headers" table. If the header name is not found, a
6089 * new entry is created.
6090 */
6091__LJMP static int hlua_txn_reply_add_header(lua_State *L)
6092{
6093 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
6094 const char *value = MAY_LJMP(luaL_checkstring(L, 3));
6095 int ret;
6096
6097 /* First argument (self) must be a table */
6098 luaL_checktype(L, 1, LUA_TTABLE);
6099
6100 /* Push in the stack the "headers" entry. */
6101 ret = lua_getfield(L, 1, "headers");
6102 if (ret != LUA_TTABLE) {
6103 hlua_pusherror(L, "Reply['headers'] is expected to a an array. %s found", lua_typename(L, ret));
6104 WILL_LJMP(lua_error(L));
6105 }
6106
6107 /* check if the header is already registered. If not, register it. */
6108 ret = lua_getfield(L, -1, name);
6109 if (ret == LUA_TNIL) {
6110 /* Entry not found. */
6111 lua_pop(L, 1); /* remove the nil. The "headers" table is the top of the stack. */
6112
6113 /* Insert the new header name in the array in the top of the stack.
6114 * It left the new array in the top of the stack.
6115 */
6116 lua_newtable(L);
6117 lua_pushstring(L, name);
6118 lua_pushvalue(L, -2);
6119 lua_settable(L, -4);
6120 }
6121 else if (ret != LUA_TTABLE) {
6122 hlua_pusherror(L, "Reply['headers']['%s'] is expected to be an array. %s found", name, lua_typename(L, ret));
6123 WILL_LJMP(lua_error(L));
6124 }
6125
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07006126 /* Now the top of thestack is an array of values. We push
Christopher Faulet700d9e82020-01-31 12:21:52 +01006127 * the header value as new entry.
6128 */
6129 lua_pushstring(L, value);
6130 ret = lua_rawlen(L, -2);
6131 lua_rawseti(L, -2, ret + 1);
6132
6133 lua_pushboolean(L, 1);
6134 return 1;
6135}
6136
6137/* Remove all occurrences of a given header name. */
6138__LJMP static int hlua_txn_reply_del_header(lua_State *L)
6139{
6140 const char *name = MAY_LJMP(luaL_checkstring(L, 2));
6141 int ret;
6142
6143 /* First argument (self) must be a table */
6144 luaL_checktype(L, 1, LUA_TTABLE);
6145
6146 /* Push in the stack the "headers" entry. */
6147 ret = lua_getfield(L, 1, "headers");
6148 if (ret != LUA_TTABLE) {
6149 hlua_pusherror(L, "Reply['headers'] is expected to be an array. %s found", lua_typename(L, ret));
6150 WILL_LJMP(lua_error(L));
6151 }
6152
6153 lua_pushstring(L, name);
6154 lua_pushnil(L);
6155 lua_settable(L, -3);
6156
6157 lua_pushboolean(L, 1);
6158 return 1;
6159}
6160
6161/* Set the reply's body. Overwrite any existing entry. */
6162__LJMP static int hlua_txn_reply_set_body(lua_State *L)
6163{
6164 const char *payload = MAY_LJMP(luaL_checkstring(L, 2));
6165
6166 /* First argument (self) must be a table */
6167 luaL_checktype(L, 1, LUA_TTABLE);
6168
6169 lua_pushstring(L, payload);
6170 lua_setfield(L, 1, "body");
6171
6172 lua_pushboolean(L, 1);
6173 return 1;
6174}
6175
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01006176__LJMP static int hlua_log(lua_State *L)
6177{
6178 int level;
6179 const char *msg;
6180
6181 MAY_LJMP(check_args(L, 2, "log"));
6182 level = MAY_LJMP(luaL_checkinteger(L, 1));
6183 msg = MAY_LJMP(luaL_checkstring(L, 2));
6184
6185 if (level < 0 || level >= NB_LOG_LEVELS)
6186 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
6187
6188 hlua_sendlog(NULL, level, msg);
6189 return 0;
6190}
6191
6192__LJMP static int hlua_log_debug(lua_State *L)
6193{
6194 const char *msg;
6195
6196 MAY_LJMP(check_args(L, 1, "debug"));
6197 msg = MAY_LJMP(luaL_checkstring(L, 1));
6198 hlua_sendlog(NULL, LOG_DEBUG, msg);
6199 return 0;
6200}
6201
6202__LJMP static int hlua_log_info(lua_State *L)
6203{
6204 const char *msg;
6205
6206 MAY_LJMP(check_args(L, 1, "info"));
6207 msg = MAY_LJMP(luaL_checkstring(L, 1));
6208 hlua_sendlog(NULL, LOG_INFO, msg);
6209 return 0;
6210}
6211
6212__LJMP static int hlua_log_warning(lua_State *L)
6213{
6214 const char *msg;
6215
6216 MAY_LJMP(check_args(L, 1, "warning"));
6217 msg = MAY_LJMP(luaL_checkstring(L, 1));
6218 hlua_sendlog(NULL, LOG_WARNING, msg);
6219 return 0;
6220}
6221
6222__LJMP static int hlua_log_alert(lua_State *L)
6223{
6224 const char *msg;
6225
6226 MAY_LJMP(check_args(L, 1, "alert"));
6227 msg = MAY_LJMP(luaL_checkstring(L, 1));
6228 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01006229 return 0;
6230}
6231
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006232__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006233{
6234 int wakeup_ms = lua_tointeger(L, -1);
6235 if (now_ms < wakeup_ms)
Willy Tarreau9635e032018-10-16 17:52:55 +02006236 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006237 return 0;
6238}
6239
6240__LJMP static int hlua_sleep(lua_State *L)
6241{
6242 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006243 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006244
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006245 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006246
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006247 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006248 wakeup_ms = tick_add(now_ms, delay);
6249 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006250
Willy Tarreau9635e032018-10-16 17:52:55 +02006251 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006252 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006253}
6254
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006255__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006256{
6257 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006258 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006259
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006260 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006261
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006262 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006263 wakeup_ms = tick_add(now_ms, delay);
6264 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006265
Willy Tarreau9635e032018-10-16 17:52:55 +02006266 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006267 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01006268}
6269
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006270/* This functionis an LUA binding. it permits to give back
6271 * the hand at the HAProxy scheduler. It is used when the
6272 * LUA processing consumes a lot of time.
6273 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01006274__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006275{
6276 return 0;
6277}
6278
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006279__LJMP static int hlua_yield(lua_State *L)
6280{
Willy Tarreau9635e032018-10-16 17:52:55 +02006281 MAY_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01006282 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01006283}
6284
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006285/* This function change the nice of the currently executed
6286 * task. It is used set low or high priority at the current
6287 * task.
6288 */
Willy Tarreau59551662015-03-10 14:23:13 +01006289__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006290{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006291 struct hlua *hlua;
6292 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006293
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006294 MAY_LJMP(check_args(L, 1, "set_nice"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006295 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006296
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006297 /* Get hlua struct, or NULL if we execute from main lua state */
6298 hlua = hlua_gethlua(L);
6299
6300 /* If the task is not set, I'm in a start mode. */
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006301 if (!hlua || !hlua->task)
6302 return 0;
6303
6304 if (nice < -1024)
6305 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01006306 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01006307 nice = 1024;
6308
6309 hlua->task->nice = nice;
6310 return 0;
6311}
6312
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006313/* This function is used as a callback of a task. It is called by the
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006314 * HAProxy task subsystem when the task is awaked. The LUA runtime can
6315 * return an E_AGAIN signal, the emmiter of this signal must set a
6316 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006317 *
6318 * Task wrapper are longjmp safe because the only one Lua code
6319 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006320 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01006321struct task *hlua_process_task(struct task *task, void *context, unsigned int state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006322{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006323 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006324 enum hlua_exec status;
6325
Christopher Faulet5bc99722018-04-25 10:34:45 +02006326 if (task->thread_mask == MAX_THREADS_MASK)
6327 task_set_affinity(task, tid_bit);
6328
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006329 /* If it is the first call to the task, we must initialize the
6330 * execution timeouts.
6331 */
6332 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006333 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006334
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006335 /* Execute the Lua code. */
6336 status = hlua_ctx_resume(hlua, 1);
6337
6338 switch (status) {
6339 /* finished or yield */
6340 case HLUA_E_OK:
6341 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006342 task_destroy(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02006343 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006344 break;
6345
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006346 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01006347 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02006348 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006349 break;
6350
6351 /* finished with error. */
6352 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006353 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006354 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006355 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006356 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006357 break;
6358
6359 case HLUA_E_ERR:
6360 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006361 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006362 hlua_ctx_destroy(hlua);
Olivier Houchard3f795f72019-04-17 22:51:06 +02006363 task_destroy(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02006364 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006365 break;
6366 }
Emeric Brun253e53e2017-10-17 18:58:40 +02006367 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006368}
6369
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006370/* This function is an LUA binding that register LUA function to be
6371 * executed after the HAProxy configuration parsing and before the
6372 * HAProxy scheduler starts. This function expect only one LUA
6373 * argument that is a function. This function returns nothing, but
6374 * throws if an error is encountered.
6375 */
6376__LJMP static int hlua_register_init(lua_State *L)
6377{
6378 struct hlua_init_function *init;
6379 int ref;
6380
6381 MAY_LJMP(check_args(L, 1, "register_init"));
6382
6383 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6384
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006385 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006386 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006387 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006388
6389 init->function_ref = ref;
Thierry Fournierc7492592020-11-28 23:57:24 +01006390 LIST_ADDQ(&hlua_init_functions[hlua_state_id], &init->l);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01006391 return 0;
6392}
6393
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006394/* This functio is an LUA binding. It permits to register a task
6395 * executed in parallel of the main HAroxy activity. The task is
6396 * created and it is set in the HAProxy scheduler. It can be called
6397 * from the "init" section, "post init" or during the runtime.
6398 *
6399 * Lua prototype:
6400 *
6401 * <none> core.register_task(<function>)
6402 */
6403static int hlua_register_task(lua_State *L)
6404{
Christopher Faulet5294ec02021-04-12 12:24:47 +02006405 struct hlua *hlua = NULL;
6406 struct task *task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006407 int ref;
Thierry Fournier021d9862020-11-28 23:42:03 +01006408 int state_id;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006409
6410 MAY_LJMP(check_args(L, 1, "register_task"));
6411
6412 ref = MAY_LJMP(hlua_checkfunction(L, 1));
6413
Thierry Fournier75fc0292020-11-28 13:18:56 +01006414 /* Get the reference state. If the reference is NULL, L is the master
6415 * state, otherwise hlua->T is.
6416 */
6417 hlua = hlua_gethlua(L);
6418 if (hlua)
Thierry Fournier021d9862020-11-28 23:42:03 +01006419 /* we are in runtime processing */
6420 state_id = hlua->state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01006421 else
Thierry Fournier021d9862020-11-28 23:42:03 +01006422 /* we are in initialization mode */
Thierry Fournierc7492592020-11-28 23:57:24 +01006423 state_id = hlua_state_id;
Thierry Fournier75fc0292020-11-28 13:18:56 +01006424
Willy Tarreaubafbe012017-11-24 17:34:44 +01006425 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006426 if (!hlua)
Christopher Faulet5294ec02021-04-12 12:24:47 +02006427 goto alloc_error;
Christopher Faulet1e8433f2021-03-24 15:03:01 +01006428 HLUA_INIT(hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006429
Thierry Fournier59f11be2020-11-29 00:37:41 +01006430 /* We are in the common lua state, execute the task anywhere,
6431 * otherwise, inherit the current thread identifier
6432 */
6433 if (state_id == 0)
6434 task = task_new(MAX_THREADS_MASK);
6435 else
6436 task = task_new(tid_bit);
Willy Tarreaue09101e2018-10-16 17:37:12 +02006437 if (!task)
Christopher Faulet5294ec02021-04-12 12:24:47 +02006438 goto alloc_error;
Willy Tarreaue09101e2018-10-16 17:37:12 +02006439
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006440 task->context = hlua;
6441 task->process = hlua_process_task;
6442
Thierry Fournier021d9862020-11-28 23:42:03 +01006443 if (!hlua_ctx_init(hlua, state_id, task, 1))
Christopher Faulet5294ec02021-04-12 12:24:47 +02006444 goto alloc_error;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006445
6446 /* Restore the function in the stack. */
6447 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
6448 hlua->nargs = 0;
6449
6450 /* Schedule task. */
6451 task_schedule(task, now_ms);
6452
6453 return 0;
Christopher Faulet5294ec02021-04-12 12:24:47 +02006454
6455 alloc_error:
6456 task_destroy(task);
6457 hlua_ctx_destroy(hlua);
6458 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6459 return 0; /* Never reached */
Thierry FOURNIER24f33532015-01-23 12:13:00 +01006460}
6461
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006462/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
6463 * doesn't allow "yield" functions because the HAProxy engine cannot
6464 * resume converters.
6465 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006466static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006467{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006468 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006469 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006470 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006471
Willy Tarreaube508f12016-03-10 11:47:01 +01006472 if (!stream)
6473 return 0;
6474
Willy Tarreau87b09662015-04-03 00:22:06 +02006475 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006476 * Lua context can be not initialized. This behavior
6477 * permits to save performances because a systematic
6478 * Lua initialization cause 5% performances loss.
6479 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006480 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01006481 struct hlua *hlua;
6482
6483 hlua = pool_alloc(pool_head_hlua);
6484 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006485 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6486 return 0;
6487 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01006488 HLUA_INIT(hlua);
6489 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01006490 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006491 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
6492 return 0;
6493 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006494 }
6495
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006496 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006497 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006498
6499 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006500 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006501 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6502 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006503 else
6504 error = "critical error";
6505 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006506 return 0;
6507 }
6508
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006509 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006510 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006511 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006512 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006513 return 0;
6514 }
6515
6516 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01006517 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006518
6519 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006520 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006521 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006522 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006523 return 0;
6524 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006525 hlua_smp2lua(stream->hlua->T, smp);
6526 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006527
6528 /* push keywords in the stack. */
6529 if (arg_p) {
6530 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006531 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006532 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006533 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006534 return 0;
6535 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006536 hlua_arg2lua(stream->hlua->T, arg_p);
6537 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006538 }
6539 }
6540
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006541 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006542 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006543
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006544 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006545 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006546 }
6547
6548 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006549 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006550 /* finished. */
6551 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006552 /* If the stack is empty, the function fails. */
6553 if (lua_gettop(stream->hlua->T) <= 0)
6554 return 0;
6555
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006556 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006557 hlua_lua2smp(stream->hlua->T, -1, smp);
6558 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006559 return 1;
6560
6561 /* yield. */
6562 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006563 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006564 return 0;
6565
6566 /* finished with error. */
6567 case HLUA_E_ERRMSG:
6568 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006569 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006570 fcn->name, lua_tostring(stream->hlua->T, -1));
6571 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006572 return 0;
6573
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006574 case HLUA_E_ETMOUT:
6575 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
6576 return 0;
6577
6578 case HLUA_E_NOMEM:
6579 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
6580 return 0;
6581
6582 case HLUA_E_YIELD:
6583 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
6584 return 0;
6585
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006586 case HLUA_E_ERR:
6587 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006588 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02006589 /* fall through */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006590
6591 default:
6592 return 0;
6593 }
6594}
6595
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006596/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
6597 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01006598 * resume sample-fetches. This function will be called by the sample
6599 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006600 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02006601static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
6602 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006603{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006604 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02006605 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006606 const char *error;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006607 unsigned int hflags = HLUA_TXN_NOTERM;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006608
Willy Tarreaube508f12016-03-10 11:47:01 +01006609 if (!stream)
6610 return 0;
Christopher Fauletafd8f102018-11-08 11:34:21 +01006611
Willy Tarreau87b09662015-04-03 00:22:06 +02006612 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006613 * Lua context can be not initialized. This behavior
6614 * permits to save performances because a systematic
6615 * Lua initialization cause 5% performances loss.
6616 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006617 if (!stream->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01006618 struct hlua *hlua;
6619
6620 hlua = pool_alloc(pool_head_hlua);
6621 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006622 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6623 return 0;
6624 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01006625 hlua->T = NULL;
6626 stream->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01006627 if (!hlua_ctx_init(stream->hlua, fcn_ref_to_stack_id(fcn), stream->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006628 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
6629 return 0;
6630 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006631 }
6632
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006633 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006634 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006635
6636 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006637 if (!SET_SAFE_LJMP(stream->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006638 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
6639 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006640 else
6641 error = "critical error";
6642 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006643 return 0;
6644 }
6645
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006646 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006647 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006648 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006649 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006650 return 0;
6651 }
6652
6653 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01006654 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[stream->hlua->state_id]);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006655
6656 /* push arguments in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006657 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006658 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006659 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006660 return 0;
6661 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006662 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006663
6664 /* push keywords in the stack. */
6665 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
6666 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006667 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006668 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006669 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006670 return 0;
6671 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006672 hlua_arg2lua(stream->hlua->T, arg_p);
6673 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006674 }
6675
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006676 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006677 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006678
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006679 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006680 RESET_SAFE_LJMP(stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006681 }
6682
6683 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006684 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006685 /* finished. */
6686 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02006687 /* If the stack is empty, the function fails. */
6688 if (lua_gettop(stream->hlua->T) <= 0)
6689 return 0;
6690
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006691 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006692 hlua_lua2smp(stream->hlua->T, -1, smp);
6693 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006694
6695 /* Set the end of execution flag. */
6696 smp->flags &= ~SMP_F_MAY_CHANGE;
6697 return 1;
6698
6699 /* yield. */
6700 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006701 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006702 return 0;
6703
6704 /* finished with error. */
6705 case HLUA_E_ERRMSG:
6706 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006707 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006708 fcn->name, lua_tostring(stream->hlua->T, -1));
6709 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006710 return 0;
6711
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006712 case HLUA_E_ETMOUT:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006713 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
6714 return 0;
6715
6716 case HLUA_E_NOMEM:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006717 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
6718 return 0;
6719
6720 case HLUA_E_YIELD:
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006721 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
6722 return 0;
6723
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006724 case HLUA_E_ERR:
6725 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006726 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Tim Duesterhus588b3142020-05-29 14:35:51 +02006727 /* fall through */
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006728
6729 default:
6730 return 0;
6731 }
6732}
6733
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006734/* This function is an LUA binding used for registering
6735 * "sample-conv" functions. It expects a converter name used
6736 * in the haproxy configuration file, and an LUA function.
6737 */
6738__LJMP static int hlua_register_converters(lua_State *L)
6739{
6740 struct sample_conv_kw_list *sck;
6741 const char *name;
6742 int ref;
6743 int len;
Christopher Fauletaa224302021-04-12 14:08:21 +02006744 struct hlua_function *fcn = NULL;
Thierry Fournierf67442e2020-11-28 20:41:07 +01006745 struct sample_conv *sc;
6746 struct buffer *trash;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006747
6748 MAY_LJMP(check_args(L, 2, "register_converters"));
6749
6750 /* First argument : converter name. */
6751 name = MAY_LJMP(luaL_checkstring(L, 1));
6752
6753 /* Second argument : lua function. */
6754 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6755
Thierry Fournierf67442e2020-11-28 20:41:07 +01006756 /* Check if the converter is already registered */
6757 trash = get_trash_chunk();
6758 chunk_printf(trash, "lua.%s", name);
6759 sc = find_sample_conv(trash->area, trash->data);
6760 if (sc != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01006761 fcn = sc->private;
6762 if (fcn->function_ref[hlua_state_id] != -1) {
6763 ha_warning("Trying to register converter 'lua.%s' more than once. "
6764 "This will become a hard error in version 2.5.\n", name);
6765 }
6766 fcn->function_ref[hlua_state_id] = ref;
6767 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01006768 }
6769
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006770 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006771 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006772 if (!sck)
Christopher Fauletaa224302021-04-12 14:08:21 +02006773 goto alloc_error;
Thierry Fournier62a22aa2020-11-28 21:06:35 +01006774 fcn = new_hlua_function();
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006775 if (!fcn)
Christopher Fauletaa224302021-04-12 14:08:21 +02006776 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006777
6778 /* Fill fcn. */
6779 fcn->name = strdup(name);
6780 if (!fcn->name)
Christopher Fauletaa224302021-04-12 14:08:21 +02006781 goto alloc_error;
Thierry Fournierc7492592020-11-28 23:57:24 +01006782 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006783
6784 /* List head */
6785 sck->list.n = sck->list.p = NULL;
6786
6787 /* converter keyword. */
6788 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006789 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006790 if (!sck->kw[0].kw)
Christopher Fauletaa224302021-04-12 14:08:21 +02006791 goto alloc_error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006792
6793 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6794 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006795 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 +01006796 sck->kw[0].val_args = NULL;
6797 sck->kw[0].in_type = SMP_T_STR;
6798 sck->kw[0].out_type = SMP_T_STR;
6799 sck->kw[0].private = fcn;
6800
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006801 /* Register this new converter */
6802 sample_register_convs(sck);
6803
6804 return 0;
Christopher Fauletaa224302021-04-12 14:08:21 +02006805
6806 alloc_error:
6807 release_hlua_function(fcn);
6808 ha_free(&sck);
6809 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
6810 return 0; /* Never reached */
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006811}
6812
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08006813/* This function is an LUA binding used for registering
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006814 * "sample-fetch" functions. It expects a converter name used
6815 * in the haproxy configuration file, and an LUA function.
6816 */
6817__LJMP static int hlua_register_fetches(lua_State *L)
6818{
6819 const char *name;
6820 int ref;
6821 int len;
6822 struct sample_fetch_kw_list *sfk;
6823 struct hlua_function *fcn;
Thierry Fournierf67442e2020-11-28 20:41:07 +01006824 struct sample_fetch *sf;
6825 struct buffer *trash;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006826
6827 MAY_LJMP(check_args(L, 2, "register_fetches"));
6828
6829 /* First argument : sample-fetch name. */
6830 name = MAY_LJMP(luaL_checkstring(L, 1));
6831
6832 /* Second argument : lua function. */
6833 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6834
Thierry Fournierf67442e2020-11-28 20:41:07 +01006835 /* Check if the sample-fetch is already registered */
6836 trash = get_trash_chunk();
6837 chunk_printf(trash, "lua.%s", name);
6838 sf = find_sample_fetch(trash->area, trash->data);
6839 if (sf != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01006840 fcn = sf->private;
6841 if (fcn->function_ref[hlua_state_id] != -1) {
6842 ha_warning("Trying to register sample-fetch 'lua.%s' more than once. "
6843 "This will become a hard error in version 2.5.\n", name);
6844 }
6845 fcn->function_ref[hlua_state_id] = ref;
6846 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01006847 }
6848
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006849 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006850 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006851 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006852 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry Fournier62a22aa2020-11-28 21:06:35 +01006853 fcn = new_hlua_function();
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006854 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006855 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006856
6857 /* Fill fcn. */
6858 fcn->name = strdup(name);
6859 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006860 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry Fournierc7492592020-11-28 23:57:24 +01006861 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006862
6863 /* List head */
6864 sfk->list.n = sfk->list.p = NULL;
6865
6866 /* sample-fetch keyword. */
6867 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006868 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006869 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006870 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006871
6872 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6873 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006874 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 +01006875 sfk->kw[0].val_args = NULL;
6876 sfk->kw[0].out_type = SMP_T_STR;
6877 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6878 sfk->kw[0].val = 0;
6879 sfk->kw[0].private = fcn;
6880
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006881 /* Register this new fetch. */
6882 sample_register_fetches(sfk);
6883
6884 return 0;
6885}
6886
Christopher Faulet501465d2020-02-26 14:54:16 +01006887/* This function is a lua binding to set the wake_time.
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006888 */
Christopher Faulet501465d2020-02-26 14:54:16 +01006889__LJMP static int hlua_set_wake_time(lua_State *L)
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006890{
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006891 struct hlua *hlua;
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006892 unsigned int delay;
6893 unsigned int wakeup_ms;
6894
Thierry Fournier4234dbd2020-11-28 13:18:23 +01006895 /* Get hlua struct, or NULL if we execute from main lua state */
6896 hlua = hlua_gethlua(L);
6897 if (!hlua) {
6898 return 0;
6899 }
6900
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01006901 MAY_LJMP(check_args(L, 1, "wake_time"));
6902
6903 delay = MAY_LJMP(luaL_checkinteger(L, 1));
6904 wakeup_ms = tick_add(now_ms, delay);
6905 hlua->wake_time = wakeup_ms;
6906 return 0;
6907}
6908
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006909/* This function is a wrapper to execute each LUA function declared as an action
6910 * wrapper during the initialisation period. This function may return any
6911 * ACT_RET_* value. On error ACT_RET_CONT is returned and the action is
6912 * ignored. If the lua action yields, ACT_RET_YIELD is returned. On success, the
6913 * return value is the first element on the stack.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006914 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006915static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006916 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006917{
6918 char **arg;
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006919 unsigned int hflags = 0;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006920 int dir, act_ret = ACT_RET_CONT;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006921 const char *error;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006922
6923 switch (rule->from) {
Christopher Fauletd8f0e072020-02-25 09:45:51 +01006924 case ACT_F_TCP_REQ_CNT: dir = SMP_OPT_DIR_REQ; break;
6925 case ACT_F_TCP_RES_CNT: dir = SMP_OPT_DIR_RES; break;
6926 case ACT_F_HTTP_REQ: dir = SMP_OPT_DIR_REQ; break;
6927 case ACT_F_HTTP_RES: dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006928 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006929 SEND_ERR(px, "Lua: internal error while execute action.\n");
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006930 goto end;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006931 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006932
Willy Tarreau87b09662015-04-03 00:22:06 +02006933 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006934 * Lua context can be not initialized. This behavior
6935 * permits to save performances because a systematic
6936 * Lua initialization cause 5% performances loss.
6937 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006938 if (!s->hlua) {
Christopher Faulet1e8433f2021-03-24 15:03:01 +01006939 struct hlua *hlua;
6940
6941 hlua = pool_alloc(pool_head_hlua);
6942 if (!hlua) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006943 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01006944 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006945 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006946 }
Christopher Faulet1e8433f2021-03-24 15:03:01 +01006947 HLUA_INIT(hlua);
6948 s->hlua = hlua;
Thierry Fournierc7492592020-11-28 23:57:24 +01006949 if (!hlua_ctx_init(s->hlua, fcn_ref_to_stack_id(rule->arg.hlua_rule->fcn), s->task, 0)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006950 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01006951 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006952 goto end;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006953 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006954 }
6955
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006956 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006957 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006958
6959 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006960 if (!SET_SAFE_LJMP(s->hlua)) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006961 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6962 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006963 else
6964 error = "critical error";
6965 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01006966 rule->arg.hlua_rule->fcn->name, error);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006967 goto end;
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006968 }
6969
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006970 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006971 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006972 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01006973 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006974 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006975 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006976 }
6977
6978 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01006979 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn->function_ref[s->hlua->state_id]);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006980
Willy Tarreau87b09662015-04-03 00:22:06 +02006981 /* Create and and push object stream in the stack. */
Christopher Fauletbfab2dd2019-07-26 15:09:53 +02006982 if (!hlua_txn_new(s->hlua->T, s, px, dir, hflags)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006983 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01006984 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006985 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006986 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006987 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006988 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006989
6990 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006991 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006992 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006993 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01006994 rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01006995 RESET_SAFE_LJMP(s->hlua);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01006996 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006997 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006998 lua_pushstring(s->hlua->T, *arg);
6999 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007000 }
7001
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007002 /* Now the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007003 RESET_SAFE_LJMP(s->hlua);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007004
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007005 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01007006 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007007 }
7008
7009 /* Execute the function. */
Christopher Faulet105ba6c2019-12-18 14:41:51 +01007010 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_OPT_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007011 /* finished. */
7012 case HLUA_E_OK:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007013 /* Catch the return value */
7014 if (lua_gettop(s->hlua->T) > 0)
7015 act_ret = lua_tointeger(s->hlua->T, -1);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007016
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007017 /* Set timeout in the required channel. */
Christopher Faulet498c4832020-07-28 11:59:58 +02007018 if (act_ret == ACT_RET_YIELD) {
7019 if (flags & ACT_OPT_FINAL)
7020 goto err_yield;
7021
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007022 if (dir == SMP_OPT_DIR_REQ)
7023 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
7024 s->hlua->wake_time);
7025 else
7026 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
7027 s->hlua->wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01007028 }
7029 goto end;
7030
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007031 /* yield. */
7032 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01007033 /* Set timeout in the required channel. */
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007034 if (dir == SMP_OPT_DIR_REQ)
7035 s->req.analyse_exp = tick_first((tick_is_expired(s->req.analyse_exp, now_ms) ? 0 : s->req.analyse_exp),
7036 s->hlua->wake_time);
7037 else
7038 s->res.analyse_exp = tick_first((tick_is_expired(s->res.analyse_exp, now_ms) ? 0 : s->res.analyse_exp),
7039 s->hlua->wake_time);
7040
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007041 /* Some actions can be wake up when a "write" event
7042 * is detected on a response channel. This is useful
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007043 * only for actions targeted on the requests.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007044 */
Christopher Faulet51fa3582019-07-26 14:54:52 +02007045 if (HLUA_IS_WAKERESWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01007046 s->res.flags |= CF_WAKE_WRITE;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01007047 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01007048 s->req.flags |= CF_WAKE_WRITE;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007049 act_ret = ACT_RET_YIELD;
7050 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007051
7052 /* finished with error. */
7053 case HLUA_E_ERRMSG:
7054 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007055 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007056 rule->arg.hlua_rule->fcn->name, lua_tostring(s->hlua->T, -1));
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01007057 lua_pop(s->hlua->T, 1);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007058 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007059
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007060 case HLUA_E_ETMOUT:
Thierry Fournierad5345f2020-11-29 02:05:57 +01007061 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007062 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007063
7064 case HLUA_E_NOMEM:
Thierry Fournierad5345f2020-11-29 02:05:57 +01007065 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007066 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007067
7068 case HLUA_E_YIELD:
Christopher Faulet498c4832020-07-28 11:59:58 +02007069 err_yield:
7070 act_ret = ACT_RET_CONT;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007071 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007072 rule->arg.hlua_rule->fcn->name);
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007073 goto end;
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007074
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007075 case HLUA_E_ERR:
7076 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02007077 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007078 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007079
7080 default:
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007081 goto end;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007082 }
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007083
7084 end:
Christopher Faulet2361fd92020-07-30 10:40:58 +02007085 if (act_ret != ACT_RET_YIELD && s->hlua)
Christopher Faulet8f587ea2020-07-28 12:01:55 +02007086 s->hlua->wake_time = TICK_ETERNITY;
Christopher Faulet7716cdf2020-01-29 11:53:30 +01007087 return act_ret;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007088}
7089
Willy Tarreau144f84a2021-03-02 16:09:26 +01007090struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned int state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007091{
Olivier Houchard9f6af332018-05-25 14:04:04 +02007092 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007093
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007094 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02007095 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02007096 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007097}
7098
7099static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7100{
7101 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007102 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007103 struct task *task;
7104 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007105 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007106
Willy Tarreaubafbe012017-11-24 17:34:44 +01007107 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007108 if (!hlua) {
7109 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007110 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007111 return 0;
7112 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007113 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007114 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007115 ctx->ctx.hlua_apptcp.flags = 0;
7116
7117 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007118 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007119 if (!task) {
7120 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007121 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007122 return 0;
7123 }
7124 task->nice = 0;
7125 task->context = ctx;
7126 task->process = hlua_applet_wakeup;
7127 ctx->ctx.hlua_apptcp.task = task;
7128
7129 /* In the execution wrappers linked with a stream, the
7130 * Lua context can be not initialized. This behavior
7131 * permits to save performances because a systematic
7132 * Lua initialization cause 5% performances loss.
7133 */
Thierry Fournierc7492592020-11-28 23:57:24 +01007134 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007135 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007136 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007137 return 0;
7138 }
7139
7140 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007141 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007142
7143 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007144 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007145 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7146 error = lua_tostring(hlua->T, -1);
7147 else
7148 error = "critical error";
7149 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007150 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007151 return 0;
7152 }
7153
7154 /* Check stack available size. */
7155 if (!lua_checkstack(hlua->T, 1)) {
7156 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007157 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007158 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007159 return 0;
7160 }
7161
7162 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01007163 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007164
7165 /* Create and and push object stream in the stack. */
7166 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
7167 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007168 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007169 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007170 return 0;
7171 }
7172 hlua->nargs = 1;
7173
7174 /* push keywords in the stack. */
7175 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7176 if (!lua_checkstack(hlua->T, 1)) {
7177 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007178 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007179 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007180 return 0;
7181 }
7182 lua_pushstring(hlua->T, *arg);
7183 hlua->nargs++;
7184 }
7185
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007186 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007187
7188 /* Wakeup the applet ASAP. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007189 si_cant_get(si);
Willy Tarreau3367d412018-11-15 10:57:41 +01007190 si_rx_endp_more(si);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007191
7192 return 1;
7193}
7194
Willy Tarreau60409db2019-08-21 14:14:50 +02007195void hlua_applet_tcp_fct(struct appctx *ctx)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007196{
7197 struct stream_interface *si = ctx->owner;
7198 struct stream *strm = si_strm(si);
7199 struct channel *res = si_ic(si);
7200 struct act_rule *rule = ctx->rule;
7201 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007202 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007203
7204 /* The applet execution is already done. */
Olivier Houchard594c8c52018-08-28 14:41:31 +02007205 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE) {
7206 /* eat the whole request */
7207 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007208 return;
Olivier Houchard594c8c52018-08-28 14:41:31 +02007209 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007210
7211 /* If the stream is disconnect or closed, ldo nothing. */
7212 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7213 return;
7214
7215 /* Execute the function. */
7216 switch (hlua_ctx_resume(hlua, 1)) {
7217 /* finished. */
7218 case HLUA_E_OK:
7219 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7220
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007221 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02007222 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007223 res->flags |= CF_READ_NULL;
7224 si_shutr(si);
7225 return;
7226
7227 /* yield. */
7228 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01007229 if (hlua->wake_time != TICK_ETERNITY)
7230 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007231 return;
7232
7233 /* finished with error. */
7234 case HLUA_E_ERRMSG:
7235 /* Display log. */
7236 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007237 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007238 lua_pop(hlua->T, 1);
7239 goto error;
7240
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007241 case HLUA_E_ETMOUT:
7242 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007243 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007244 goto error;
7245
7246 case HLUA_E_NOMEM:
7247 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007248 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007249 goto error;
7250
7251 case HLUA_E_YIELD: /* unexpected */
7252 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007253 rule->arg.hlua_rule->fcn->name);
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007254 goto error;
7255
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007256 case HLUA_E_ERR:
7257 /* Display log. */
7258 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007259 rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007260 goto error;
7261
7262 default:
7263 goto error;
7264 }
7265
7266error:
7267
7268 /* For all other cases, just close the stream. */
7269 si_shutw(si);
7270 si_shutr(si);
7271 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
7272}
7273
7274static void hlua_applet_tcp_release(struct appctx *ctx)
7275{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007276 task_destroy(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007277 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007278 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007279 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007280}
7281
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007282/* The function returns 1 if the initialisation is complete, 0 if
7283 * an errors occurs and -1 if more data are required for initializing
7284 * the applet.
7285 */
7286static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
7287{
7288 struct stream_interface *si = ctx->owner;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007289 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007290 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007291 char **arg;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007292 struct task *task;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007293 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007294
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007295 txn = strm->txn;
Willy Tarreaubafbe012017-11-24 17:34:44 +01007296 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007297 if (!hlua) {
7298 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007299 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007300 return 0;
7301 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007302 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007303 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007304 ctx->ctx.hlua_apphttp.left_bytes = -1;
7305 ctx->ctx.hlua_apphttp.flags = 0;
7306
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01007307 if (txn->req.flags & HTTP_MSGF_VER_11)
7308 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
7309
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007310 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007311 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007312 if (!task) {
7313 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007314 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007315 return 0;
7316 }
7317 task->nice = 0;
7318 task->context = ctx;
7319 task->process = hlua_applet_wakeup;
7320 ctx->ctx.hlua_apphttp.task = task;
7321
7322 /* In the execution wrappers linked with a stream, the
7323 * Lua context can be not initialized. This behavior
7324 * permits to save performances because a systematic
7325 * Lua initialization cause 5% performances loss.
7326 */
Thierry Fournierc7492592020-11-28 23:57:24 +01007327 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(ctx->rule->arg.hlua_rule->fcn), task, 0)) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007328 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007329 ctx->rule->arg.hlua_rule->fcn->name);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007330 return 0;
7331 }
7332
7333 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02007334 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007335
7336 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007337 if (!SET_SAFE_LJMP(hlua)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007338 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7339 error = lua_tostring(hlua->T, -1);
7340 else
7341 error = "critical error";
7342 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007343 ctx->rule->arg.hlua_rule->fcn->name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007344 return 0;
7345 }
7346
7347 /* Check stack available size. */
7348 if (!lua_checkstack(hlua->T, 1)) {
7349 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007350 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007351 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007352 return 0;
7353 }
7354
7355 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01007356 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn->function_ref[hlua->state_id]);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007357
7358 /* Create and and push object stream in the stack. */
7359 if (!hlua_applet_http_new(hlua->T, ctx)) {
7360 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007361 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007362 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007363 return 0;
7364 }
7365 hlua->nargs = 1;
7366
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007367 /* push keywords in the stack. */
7368 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
7369 if (!lua_checkstack(hlua->T, 1)) {
7370 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007371 ctx->rule->arg.hlua_rule->fcn->name);
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007372 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007373 return 0;
7374 }
7375 lua_pushstring(hlua->T, *arg);
7376 hlua->nargs++;
7377 }
7378
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007379 RESET_SAFE_LJMP(hlua);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007380
7381 /* Wakeup the applet when data is ready for read. */
Willy Tarreau0cd3bd62018-11-06 18:46:37 +01007382 si_cant_get(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007383
7384 return 1;
7385}
7386
Willy Tarreau60409db2019-08-21 14:14:50 +02007387void hlua_applet_http_fct(struct appctx *ctx)
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007388{
7389 struct stream_interface *si = ctx->owner;
7390 struct stream *strm = si_strm(si);
7391 struct channel *req = si_oc(si);
7392 struct channel *res = si_ic(si);
7393 struct act_rule *rule = ctx->rule;
7394 struct proxy *px = strm->be;
7395 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
7396 struct htx *req_htx, *res_htx;
7397
7398 res_htx = htx_from_buf(&res->buf);
7399
7400 /* If the stream is disconnect or closed, ldo nothing. */
7401 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7402 goto out;
7403
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007404 /* Check if the input buffer is available. */
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007405 if (!b_size(&res->buf)) {
7406 si_rx_room_blk(si);
7407 goto out;
7408 }
7409 /* check that the output is not closed */
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007410 if (res->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_SHUTR))
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007411 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7412
7413 /* Set the currently running flag. */
7414 if (!HLUA_IS_RUNNING(hlua) &&
7415 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7416 struct htx_blk *blk;
7417 size_t count = co_data(req);
7418
7419 if (!count) {
7420 si_cant_get(si);
7421 goto out;
7422 }
7423
7424 /* We need to flush the request header. This left the body for
7425 * the Lua.
7426 */
7427 req_htx = htx_from_buf(&req->buf);
Christopher Fauleta3f15502019-05-13 15:27:23 +02007428 blk = htx_get_first_blk(req_htx);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007429 while (count && blk) {
7430 enum htx_blk_type type = htx_get_blk_type(blk);
7431 uint32_t sz = htx_get_blksz(blk);
7432
7433 if (sz > count) {
7434 si_cant_get(si);
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007435 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007436 goto out;
7437 }
7438
7439 count -= sz;
7440 co_set_data(req, co_data(req) - sz);
7441 blk = htx_remove_blk(req_htx, blk);
7442
7443 if (type == HTX_BLK_EOH)
7444 break;
7445 }
Christopher Faulet0ae79d02019-02-27 21:36:59 +01007446 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007447 }
7448
7449 /* Executes The applet if it is not done. */
7450 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
7451
7452 /* Execute the function. */
7453 switch (hlua_ctx_resume(hlua, 1)) {
7454 /* finished. */
7455 case HLUA_E_OK:
7456 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7457 break;
7458
7459 /* yield. */
7460 case HLUA_E_AGAIN:
7461 if (hlua->wake_time != TICK_ETERNITY)
7462 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007463 goto out;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007464
7465 /* finished with error. */
7466 case HLUA_E_ERRMSG:
7467 /* Display log. */
7468 SEND_ERR(px, "Lua applet http '%s': %s.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007469 rule->arg.hlua_rule->fcn->name, lua_tostring(hlua->T, -1));
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007470 lua_pop(hlua->T, 1);
7471 goto error;
7472
7473 case HLUA_E_ETMOUT:
7474 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007475 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007476 goto error;
7477
7478 case HLUA_E_NOMEM:
7479 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007480 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007481 goto error;
7482
7483 case HLUA_E_YIELD: /* unexpected */
7484 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007485 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007486 goto error;
7487
7488 case HLUA_E_ERR:
7489 /* Display log. */
7490 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
Thierry Fournierad5345f2020-11-29 02:05:57 +01007491 rule->arg.hlua_rule->fcn->name);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007492 goto error;
7493
7494 default:
7495 goto error;
7496 }
7497 }
7498
7499 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007500 if (ctx->ctx.hlua_apphttp.flags & APPLET_RSP_SENT)
7501 goto done;
7502
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007503 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT))
7504 goto error;
7505
Christopher Fauletd1ac2b92020-12-02 19:12:22 +01007506 /* no more data are expected. Don't add TLR because mux-h1 will take care of it */
7507 res_htx->flags |= HTX_FL_EOM;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007508 strm->txn->status = ctx->ctx.hlua_apphttp.status;
7509 ctx->ctx.hlua_apphttp.flags |= APPLET_RSP_SENT;
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007510 }
7511
7512 done:
7513 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007514 if (!(res->flags & CF_SHUTR)) {
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007515 res->flags |= CF_READ_NULL;
Christopher Faulet56a3d6e2019-02-27 22:06:23 +01007516 si_shutr(si);
7517 }
7518
7519 /* eat the whole request */
7520 if (co_data(req)) {
7521 req_htx = htx_from_buf(&req->buf);
7522 co_htx_skip(req, req_htx, co_data(req));
7523 htx_to_buf(req_htx, &req->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007524 }
7525 }
7526
7527 out:
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007528 htx_to_buf(res_htx, &res->buf);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007529 return;
7530
7531 error:
7532
7533 /* If we are in HTTP mode, and we are not send any
7534 * data, return a 500 server error in best effort:
7535 * if there is no room available in the buffer,
7536 * just close the connection.
7537 */
7538 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
Christopher Fauletf7346382019-07-17 22:02:08 +02007539 struct buffer *err = &http_err_chunks[HTTP_ERR_500];
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007540
7541 channel_erase(res);
7542 res->buf.data = b_data(err);
7543 memcpy(res->buf.area, b_head(err), b_data(err));
7544 res_htx = htx_from_buf(&res->buf);
Christopher Fauletf6cce3f2019-02-27 21:20:09 +01007545 channel_add_input(res, res_htx->data);
Christopher Faulet9c832fc2018-12-14 13:34:05 +01007546 }
7547 if (!(strm->flags & SF_ERR_MASK))
7548 strm->flags |= SF_ERR_RESOURCE;
7549 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
7550 goto done;
7551}
7552
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007553static void hlua_applet_http_release(struct appctx *ctx)
7554{
Olivier Houchard3f795f72019-04-17 22:51:06 +02007555 task_destroy(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007556 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007557 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007558 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007559}
7560
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007561/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007562 * success case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007563 *
7564 * This function can fail with an abort() due to an Lua critical error.
7565 * We are in the configuration parsing process of HAProxy, this abort() is
7566 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007567 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007568static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
7569 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007570{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007571 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007572 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007573
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007574 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007575 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007576 if (!rule->arg.hlua_rule) {
7577 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007578 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007579 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007580
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007581 /* Memory for arguments. */
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02007582 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1,
7583 sizeof(*rule->arg.hlua_rule->args));
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007584 if (!rule->arg.hlua_rule->args) {
7585 memprintf(err, "out of memory error");
7586 return ACT_RET_PRS_ERR;
7587 }
7588
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007589 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01007590 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007591
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007592 /* Expect some arguments */
7593 for (i = 0; i < fcn->nargs; i++) {
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007594 if (*args[*cur_arg] == '\0') {
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007595 memprintf(err, "expect %d arguments", fcn->nargs);
7596 return ACT_RET_PRS_ERR;
7597 }
Thierry FOURNIER1725c2e2019-01-06 19:38:49 +01007598 rule->arg.hlua_rule->args[i] = strdup(args[*cur_arg]);
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007599 if (!rule->arg.hlua_rule->args[i]) {
7600 memprintf(err, "out of memory error");
7601 return ACT_RET_PRS_ERR;
7602 }
7603 (*cur_arg)++;
7604 }
7605 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007606
Thierry FOURNIER42148732015-09-02 17:17:33 +02007607 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02007608 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02007609 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01007610}
7611
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007612static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
7613 struct act_rule *rule, char **err)
7614{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007615 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007616
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007617 /* HTTP applets are forbidden in tcp-request rules.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007618 * HTTP applet request requires everything initialized by
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007619 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05007620 * The applet will be immediately initialized, but its before
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01007621 * the call of this analyzer.
7622 */
7623 if (rule->from != ACT_F_HTTP_REQ) {
7624 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
7625 return ACT_RET_PRS_ERR;
7626 }
7627
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007628 /* Memory for the rule. */
7629 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7630 if (!rule->arg.hlua_rule) {
7631 memprintf(err, "out of memory error");
7632 return ACT_RET_PRS_ERR;
7633 }
7634
7635 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01007636 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007637
7638 /* TODO: later accept arguments. */
7639 rule->arg.hlua_rule->args = NULL;
7640
7641 /* Add applet pointer in the rule. */
7642 rule->applet.obj_type = OBJ_TYPE_APPLET;
7643 rule->applet.name = fcn->name;
7644 rule->applet.init = hlua_applet_http_init;
7645 rule->applet.fct = hlua_applet_http_fct;
7646 rule->applet.release = hlua_applet_http_release;
7647 rule->applet.timeout = hlua_timeout_applet;
7648
7649 return ACT_RET_PRS_OK;
7650}
7651
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007652/* This function is an LUA binding used for registering
7653 * "sample-conv" functions. It expects a converter name used
7654 * in the haproxy configuration file, and an LUA function.
7655 */
7656__LJMP static int hlua_register_action(lua_State *L)
7657{
7658 struct action_kw_list *akl;
7659 const char *name;
7660 int ref;
7661 int len;
7662 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007663 int nargs;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007664 struct buffer *trash;
7665 struct action_kw *akw;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007666
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007667 /* Initialise the number of expected arguments at 0. */
7668 nargs = 0;
7669
7670 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
7671 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007672
7673 /* First argument : converter name. */
7674 name = MAY_LJMP(luaL_checkstring(L, 1));
7675
7676 /* Second argument : environment. */
7677 if (lua_type(L, 2) != LUA_TTABLE)
7678 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7679
7680 /* Third argument : lua function. */
7681 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7682
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007683 /* Fourth argument : number of mandatory arguments expected on the configuration line. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007684 if (lua_gettop(L) >= 4)
7685 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
7686
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08007687 /* browse the second argument as an array. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007688 lua_pushnil(L);
7689 while (lua_next(L, 2) != 0) {
7690 if (lua_type(L, -1) != LUA_TSTRING)
7691 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
7692
Thierry Fournierf67442e2020-11-28 20:41:07 +01007693 /* Check if action exists */
7694 trash = get_trash_chunk();
7695 chunk_printf(trash, "lua.%s", name);
7696 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0) {
7697 akw = tcp_req_cont_action(trash->area);
7698 } else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0) {
7699 akw = tcp_res_cont_action(trash->area);
7700 } else if (strcmp(lua_tostring(L, -1), "http-req") == 0) {
7701 akw = action_http_req_custom(trash->area);
7702 } else if (strcmp(lua_tostring(L, -1), "http-res") == 0) {
7703 akw = action_http_res_custom(trash->area);
7704 } else {
7705 akw = NULL;
7706 }
7707 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01007708 fcn = akw->private;
7709 if (fcn->function_ref[hlua_state_id] != -1) {
7710 ha_warning("Trying to register action 'lua.%s' more than once. "
7711 "This will become a hard error in version 2.5.\n", name);
7712 }
7713 fcn->function_ref[hlua_state_id] = ref;
7714
7715 /* pop the environment string. */
7716 lua_pop(L, 1);
7717 continue;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007718 }
7719
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007720 /* Check required environment. Only accepted "http" or "tcp". */
7721 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007722 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007723 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007724 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry Fournier62a22aa2020-11-28 21:06:35 +01007725 fcn = new_hlua_function();
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007726 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007727 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007728
7729 /* Fill fcn. */
7730 fcn->name = strdup(name);
7731 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007732 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry Fournierc7492592020-11-28 23:57:24 +01007733 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007734
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07007735 /* Set the expected number of arguments. */
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01007736 fcn->nargs = nargs;
7737
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007738 /* List head */
7739 akl->list.n = akl->list.p = NULL;
7740
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007741 /* action keyword. */
7742 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02007743 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007744 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007745 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007746
7747 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7748
7749 akl->kw[0].match_pfx = 0;
7750 akl->kw[0].private = fcn;
7751 akl->kw[0].parse = action_register_lua;
7752
7753 /* select the action registering point. */
7754 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
7755 tcp_req_cont_keywords_register(akl);
7756 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
7757 tcp_res_cont_keywords_register(akl);
7758 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
7759 http_req_keywords_register(akl);
7760 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
7761 http_res_keywords_register(akl);
7762 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007763 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007764 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
7765 "are expected.", lua_tostring(L, -1)));
7766
7767 /* pop the environment string. */
7768 lua_pop(L, 1);
7769 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007770 return ACT_RET_PRS_OK;
7771}
7772
7773static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
7774 struct act_rule *rule, char **err)
7775{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02007776 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007777
Christopher Faulet280f85b2019-07-15 15:02:04 +02007778 if (px->mode == PR_MODE_HTTP) {
7779 memprintf(err, "Lua TCP services cannot be used on HTTP proxies");
Christopher Fauletafd8f102018-11-08 11:34:21 +01007780 return ACT_RET_PRS_ERR;
7781 }
7782
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007783 /* Memory for the rule. */
7784 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
7785 if (!rule->arg.hlua_rule) {
7786 memprintf(err, "out of memory error");
7787 return ACT_RET_PRS_ERR;
7788 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007789
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007790 /* Reference the Lua function and store the reference. */
Thierry Fournierad5345f2020-11-29 02:05:57 +01007791 rule->arg.hlua_rule->fcn = fcn;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007792
7793 /* TODO: later accept arguments. */
7794 rule->arg.hlua_rule->args = NULL;
7795
7796 /* Add applet pointer in the rule. */
7797 rule->applet.obj_type = OBJ_TYPE_APPLET;
7798 rule->applet.name = fcn->name;
7799 rule->applet.init = hlua_applet_tcp_init;
7800 rule->applet.fct = hlua_applet_tcp_fct;
7801 rule->applet.release = hlua_applet_tcp_release;
7802 rule->applet.timeout = hlua_timeout_applet;
7803
7804 return 0;
7805}
7806
7807/* This function is an LUA binding used for registering
7808 * "sample-conv" functions. It expects a converter name used
7809 * in the haproxy configuration file, and an LUA function.
7810 */
7811__LJMP static int hlua_register_service(lua_State *L)
7812{
7813 struct action_kw_list *akl;
7814 const char *name;
7815 const char *env;
7816 int ref;
7817 int len;
7818 struct hlua_function *fcn;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007819 struct buffer *trash;
7820 struct action_kw *akw;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007821
7822 MAY_LJMP(check_args(L, 3, "register_service"));
7823
7824 /* First argument : converter name. */
7825 name = MAY_LJMP(luaL_checkstring(L, 1));
7826
7827 /* Second argument : environment. */
7828 env = MAY_LJMP(luaL_checkstring(L, 2));
7829
7830 /* Third argument : lua function. */
7831 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7832
Thierry Fournierf67442e2020-11-28 20:41:07 +01007833 /* Check for service already registered */
7834 trash = get_trash_chunk();
7835 chunk_printf(trash, "lua.%s", name);
7836 akw = service_find(trash->area);
7837 if (akw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01007838 fcn = akw->private;
7839 if (fcn->function_ref[hlua_state_id] != -1) {
7840 ha_warning("Trying to register service 'lua.%s' more than once. "
7841 "This will become a hard error in version 2.5.\n", name);
7842 }
7843 fcn->function_ref[hlua_state_id] = ref;
7844 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01007845 }
7846
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007847 /* Allocate and fill the sample fetch keyword struct. */
7848 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7849 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007850 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry Fournier62a22aa2020-11-28 21:06:35 +01007851 fcn = new_hlua_function();
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007852 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007853 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007854
7855 /* Fill fcn. */
7856 len = strlen("<lua.>") + strlen(name) + 1;
7857 fcn->name = calloc(1, len);
7858 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007859 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007860 snprintf((char *)fcn->name, len, "<lua.%s>", name);
Thierry Fournierc7492592020-11-28 23:57:24 +01007861 fcn->function_ref[hlua_state_id] = ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007862
7863 /* List head */
7864 akl->list.n = akl->list.p = NULL;
7865
7866 /* converter keyword. */
7867 len = strlen("lua.") + strlen(name) + 1;
7868 akl->kw[0].kw = calloc(1, len);
7869 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007870 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007871
7872 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7873
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007874 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007875 if (strcmp(env, "tcp") == 0)
7876 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007877 else if (strcmp(env, "http") == 0)
7878 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007879 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007880 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007881 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007882
7883 akl->kw[0].match_pfx = 0;
7884 akl->kw[0].private = fcn;
7885
7886 /* End of array. */
7887 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7888
7889 /* Register this new converter */
7890 service_keywords_register(akl);
7891
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007892 return 0;
7893}
7894
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007895/* This function initialises Lua cli handler. It copies the
7896 * arguments in the Lua stack and create channel IO objects.
7897 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007898static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007899{
7900 struct hlua *hlua;
7901 struct hlua_function *fcn;
7902 int i;
7903 const char *error;
7904
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007905 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007906 appctx->ctx.hlua_cli.fcn = private;
7907
Willy Tarreaubafbe012017-11-24 17:34:44 +01007908 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007909 if (!hlua) {
7910 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007911 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007912 }
7913 HLUA_INIT(hlua);
7914 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007915
7916 /* Create task used by signal to wakeup applets.
Ilya Shipitsind4259502020-04-08 01:07:56 +05007917 * We use the same wakeup function than the Lua applet_tcp and
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007918 * applet_http. It is absolutely compatible.
7919 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007920 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007921 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007922 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007923 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007924 }
7925 appctx->ctx.hlua_cli.task->nice = 0;
7926 appctx->ctx.hlua_cli.task->context = appctx;
7927 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7928
7929 /* Initialises the Lua context */
Thierry Fournierc7492592020-11-28 23:57:24 +01007930 if (!hlua_ctx_init(hlua, fcn_ref_to_stack_id(fcn), appctx->ctx.hlua_cli.task, 0)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007931 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007932 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007933 }
7934
7935 /* The following Lua calls can fail. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007936 if (!SET_SAFE_LJMP(hlua)) {
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007937 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7938 error = lua_tostring(hlua->T, -1);
7939 else
7940 error = "critical error";
7941 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7942 goto error;
7943 }
7944
7945 /* Check stack available size. */
7946 if (!lua_checkstack(hlua->T, 2)) {
7947 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7948 goto error;
7949 }
7950
7951 /* Restore the function in the stack. */
Thierry Fournierc7492592020-11-28 23:57:24 +01007952 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref[hlua->state_id]);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007953
7954 /* Once the arguments parsed, the CLI is like an AppletTCP,
7955 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007956 */
7957 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7958 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7959 goto error;
7960 }
7961 hlua->nargs = 1;
7962
7963 /* push keywords in the stack. */
7964 for (i = 0; *args[i]; i++) {
7965 /* Check stack available size. */
7966 if (!lua_checkstack(hlua->T, 1)) {
7967 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7968 goto error;
7969 }
7970 lua_pushstring(hlua->T, args[i]);
7971 hlua->nargs++;
7972 }
7973
7974 /* We must initialize the execution timeouts. */
7975 hlua->max_time = hlua_timeout_session;
7976
7977 /* At this point the execution is safe. */
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007978 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007979
7980 /* It's ok */
7981 return 0;
7982
7983 /* It's not ok. */
7984error:
Thierry Fournier7cbe5042020-11-28 17:02:21 +01007985 RESET_SAFE_LJMP(hlua);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007986 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007987 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007988 return 1;
7989}
7990
7991static int hlua_cli_io_handler_fct(struct appctx *appctx)
7992{
7993 struct hlua *hlua;
7994 struct stream_interface *si;
7995 struct hlua_function *fcn;
7996
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007997 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007998 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007999 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008000
8001 /* If the stream is disconnect or closed, ldo nothing. */
8002 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
8003 return 1;
8004
8005 /* Execute the function. */
8006 switch (hlua_ctx_resume(hlua, 1)) {
8007
8008 /* finished. */
8009 case HLUA_E_OK:
8010 return 1;
8011
8012 /* yield. */
8013 case HLUA_E_AGAIN:
8014 /* We want write. */
8015 if (HLUA_IS_WAKERESWR(hlua))
Willy Tarreaudb398432018-11-15 11:08:52 +01008016 si_rx_room_blk(si);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008017 /* Set the timeout. */
8018 if (hlua->wake_time != TICK_ETERNITY)
8019 task_schedule(hlua->task, hlua->wake_time);
8020 return 0;
8021
8022 /* finished with error. */
8023 case HLUA_E_ERRMSG:
8024 /* Display log. */
8025 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
8026 fcn->name, lua_tostring(hlua->T, -1));
8027 lua_pop(hlua->T, 1);
8028 return 1;
8029
Thierry Fournierd5b073c2018-05-21 19:42:47 +02008030 case HLUA_E_ETMOUT:
8031 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
8032 fcn->name);
8033 return 1;
8034
8035 case HLUA_E_NOMEM:
8036 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
8037 fcn->name);
8038 return 1;
8039
8040 case HLUA_E_YIELD: /* unexpected */
8041 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
8042 fcn->name);
8043 return 1;
8044
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008045 case HLUA_E_ERR:
8046 /* Display log. */
8047 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
8048 fcn->name);
8049 return 1;
8050
8051 default:
8052 return 1;
8053 }
8054
8055 return 1;
8056}
8057
8058static void hlua_cli_io_release_fct(struct appctx *appctx)
8059{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008060 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01008061 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008062}
8063
8064/* This function is an LUA binding used for registering
8065 * new keywords in the cli. It expects a list of keywords
8066 * which are the "path". It is limited to 5 keywords. A
8067 * description of the command, a function to be executed
8068 * for the parsing and a function for io handlers.
8069 */
8070__LJMP static int hlua_register_cli(lua_State *L)
8071{
8072 struct cli_kw_list *cli_kws;
8073 const char *message;
8074 int ref_io;
8075 int len;
8076 struct hlua_function *fcn;
8077 int index;
8078 int i;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008079 struct buffer *trash;
8080 const char *kw[5];
8081 struct cli_kw *cli_kw;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008082
8083 MAY_LJMP(check_args(L, 3, "register_cli"));
8084
8085 /* First argument : an array of maximum 5 keywords. */
8086 if (!lua_istable(L, 1))
8087 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
8088
8089 /* Second argument : string with contextual message. */
8090 message = MAY_LJMP(luaL_checkstring(L, 2));
8091
8092 /* Third and fourth argument : lua function. */
8093 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
8094
Thierry Fournierf67442e2020-11-28 20:41:07 +01008095 /* Check for CLI service already registered */
8096 trash = get_trash_chunk();
8097 index = 0;
8098 lua_pushnil(L);
8099 memset(kw, 0, sizeof(kw));
8100 while (lua_next(L, 1) != 0) {
8101 if (index >= CLI_PREFIX_KW_NB)
8102 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8103 if (lua_type(L, -1) != LUA_TSTRING)
8104 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8105 kw[index] = lua_tostring(L, -1);
8106 if (index == 0)
8107 chunk_printf(trash, "%s", kw[index]);
8108 else
8109 chunk_appendf(trash, " %s", kw[index]);
8110 index++;
8111 lua_pop(L, 1);
8112 }
8113 cli_kw = cli_find_kw_exact((char **)kw);
8114 if (cli_kw != NULL) {
Thierry Fournier59f11be2020-11-29 00:37:41 +01008115 fcn = cli_kw->private;
8116 if (fcn->function_ref[hlua_state_id] != -1) {
8117 ha_warning("Trying to register CLI keyword 'lua.%s' more than once. "
8118 "This will become a hard error in version 2.5.\n", trash->area);
8119 }
8120 fcn->function_ref[hlua_state_id] = ref_io;
8121 return 0;
Thierry Fournierf67442e2020-11-28 20:41:07 +01008122 }
8123
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008124 /* Allocate and fill the sample fetch keyword struct. */
8125 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
8126 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008127 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry Fournier62a22aa2020-11-28 21:06:35 +01008128 fcn = new_hlua_function();
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008129 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008130 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008131
8132 /* Fill path. */
8133 index = 0;
8134 lua_pushnil(L);
8135 while(lua_next(L, 1) != 0) {
8136 if (index >= 5)
8137 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
8138 if (lua_type(L, -1) != LUA_TSTRING)
8139 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
8140 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
8141 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008142 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008143 index++;
8144 lua_pop(L, 1);
8145 }
8146
8147 /* Copy help message. */
8148 cli_kws->kw[0].usage = strdup(message);
8149 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008150 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008151
8152 /* Fill fcn io handler. */
8153 len = strlen("<lua.cli>") + 1;
8154 for (i = 0; i < index; i++)
8155 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
8156 fcn->name = calloc(1, len);
8157 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01008158 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008159 strncat((char *)fcn->name, "<lua.cli", len);
8160 for (i = 0; i < index; i++) {
8161 strncat((char *)fcn->name, ".", len);
8162 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
8163 }
8164 strncat((char *)fcn->name, ">", len);
Thierry Fournierc7492592020-11-28 23:57:24 +01008165 fcn->function_ref[hlua_state_id] = ref_io;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01008166
8167 /* Fill last entries. */
8168 cli_kws->kw[0].private = fcn;
8169 cli_kws->kw[0].parse = hlua_cli_parse_fct;
8170 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
8171 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
8172
8173 /* Register this new converter */
8174 cli_register_kw(cli_kws);
8175
8176 return 0;
8177}
8178
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008179static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008180 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008181 char **err, unsigned int *timeout)
8182{
8183 const char *error;
8184
8185 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
Willy Tarreau9faebe32019-06-07 19:00:37 +02008186 if (error == PARSE_TIME_OVER) {
8187 memprintf(err, "timer overflow in argument <%s> to <%s> (maximum value is 2147483647 ms or ~24.8 days)",
8188 args[1], args[0]);
8189 return -1;
8190 }
8191 else if (error == PARSE_TIME_UNDER) {
8192 memprintf(err, "timer underflow in argument <%s> to <%s> (minimum non-null value is 1 ms)",
8193 args[1], args[0]);
8194 return -1;
8195 }
8196 else if (error) {
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008197 memprintf(err, "%s: invalid timeout", args[0]);
8198 return -1;
8199 }
8200 return 0;
8201}
8202
8203static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008204 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008205 char **err)
8206{
8207 return hlua_read_timeout(args, section_type, curpx, defpx,
8208 file, line, err, &hlua_timeout_session);
8209}
8210
8211static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008212 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008213 char **err)
8214{
8215 return hlua_read_timeout(args, section_type, curpx, defpx,
8216 file, line, err, &hlua_timeout_task);
8217}
8218
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008219static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008220 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02008221 char **err)
8222{
8223 return hlua_read_timeout(args, section_type, curpx, defpx,
8224 file, line, err, &hlua_timeout_applet);
8225}
8226
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008227static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008228 const struct proxy *defpx, const char *file, int line,
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008229 char **err)
8230{
8231 char *error;
8232
8233 hlua_nb_instruction = strtoll(args[1], &error, 10);
8234 if (*error != '\0') {
8235 memprintf(err, "%s: invalid number", args[0]);
8236 return -1;
8237 }
8238 return 0;
8239}
8240
Willy Tarreau32f61e22015-03-18 17:54:59 +01008241static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008242 const struct proxy *defpx, const char *file, int line,
Willy Tarreau32f61e22015-03-18 17:54:59 +01008243 char **err)
8244{
8245 char *error;
8246
8247 if (*(args[1]) == 0) {
8248 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
8249 return -1;
8250 }
8251 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
8252 if (*error != '\0') {
8253 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
8254 return -1;
8255 }
8256 return 0;
8257}
8258
8259
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008260/* This function is called by the main configuration key "lua-load". It loads and
8261 * execute an lua file during the parsing of the HAProxy configuration file. It is
8262 * the main lua entry point.
8263 *
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008264 * This function runs with the HAProxy keywords API. It returns -1 if an error
8265 * occurs, otherwise it returns 0.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008266 *
8267 * In some error case, LUA set an error message in top of the stack. This function
8268 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008269 *
8270 * This function can fail with an abort() due to an Lua critical error.
8271 * We are in the configuration parsing process of HAProxy, this abort() is
8272 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008273 */
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008274static int hlua_load_state(char *filename, lua_State *L, char **err)
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008275{
8276 int error;
8277
8278 /* Just load and compile the file. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008279 error = luaL_loadfile(L, filename);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008280 if (error) {
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008281 memprintf(err, "error in Lua file '%s': %s", filename, lua_tostring(L, -1));
8282 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008283 return -1;
8284 }
8285
8286 /* If no syntax error where detected, execute the code. */
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008287 error = lua_pcall(L, 0, LUA_MULTRET, 0);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008288 switch (error) {
8289 case LUA_OK:
8290 break;
8291 case LUA_ERRRUN:
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008292 memprintf(err, "Lua runtime error: %s\n", lua_tostring(L, -1));
8293 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008294 return -1;
8295 case LUA_ERRMEM:
Thierry Fournierde6145f2020-11-29 00:55:53 +01008296 memprintf(err, "Lua out of memory error\n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008297 return -1;
8298 case LUA_ERRERR:
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008299 memprintf(err, "Lua message handler error: %s\n", lua_tostring(L, -1));
8300 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008301 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +02008302#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM <= 503
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008303 case LUA_ERRGCMM:
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008304 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(L, -1));
8305 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008306 return -1;
Christopher Faulet08ed98f2020-07-28 10:33:25 +02008307#endif
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008308 default:
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008309 memprintf(err, "Lua unknown error: %s\n", lua_tostring(L, -1));
8310 lua_pop(L, 1);
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008311 return -1;
8312 }
8313
8314 return 0;
8315}
8316
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008317static int hlua_load(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008318 const struct proxy *defpx, const char *file, int line,
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008319 char **err)
8320{
8321 if (*(args[1]) == 0) {
8322 memprintf(err, "'%s' expects a file name as parameter.\n", args[0]);
8323 return -1;
8324 }
8325
Thierry Fournier59f11be2020-11-29 00:37:41 +01008326 /* loading for global state */
Thierry Fournierc7492592020-11-28 23:57:24 +01008327 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008328 ha_set_tid(0);
Thierry Fournierafc63e22020-11-28 17:06:51 +01008329 return hlua_load_state(args[1], hlua_states[0], err);
Thierry Fournierc93c15c2020-11-28 15:02:13 +01008330}
8331
Thierry Fournier59f11be2020-11-29 00:37:41 +01008332static int hlua_load_per_thread(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008333 const struct proxy *defpx, const char *file, int line,
Thierry Fournier59f11be2020-11-29 00:37:41 +01008334 char **err)
8335{
8336 int len;
8337
8338 if (*(args[1]) == 0) {
8339 memprintf(err, "'%s' expects a file as parameter.\n", args[0]);
8340 return -1;
8341 }
8342
8343 if (per_thread_load == NULL) {
8344 /* allocate the first entry large enough to store the final NULL */
8345 per_thread_load = calloc(1, sizeof(*per_thread_load));
8346 if (per_thread_load == NULL) {
8347 memprintf(err, "out of memory error");
8348 return -1;
8349 }
8350 }
8351
8352 /* count used entries */
8353 for (len = 0; per_thread_load[len] != NULL; len++)
8354 ;
8355
8356 per_thread_load = realloc(per_thread_load, (len + 2) * sizeof(*per_thread_load));
8357 if (per_thread_load == NULL) {
8358 memprintf(err, "out of memory error");
8359 return -1;
8360 }
8361
8362 per_thread_load[len] = strdup(args[1]);
8363 per_thread_load[len + 1] = NULL;
8364
8365 if (per_thread_load[len] == NULL) {
8366 memprintf(err, "out of memory error");
8367 return -1;
8368 }
8369
8370 /* loading for thread 1 only */
8371 hlua_state_id = 1;
8372 ha_set_tid(0);
8373 return hlua_load_state(args[1], hlua_states[1], err);
8374}
8375
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01008376/* Prepend the given <path> followed by a semicolon to the `package.<type>` variable
8377 * in the given <ctx>.
8378 */
Thierry Fournier3fb9e512020-11-28 10:13:12 +01008379static int hlua_prepend_path(lua_State *L, char *type, char *path)
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01008380{
Thierry Fournier3fb9e512020-11-28 10:13:12 +01008381 lua_getglobal(L, "package"); /* push package variable */
8382 lua_pushstring(L, path); /* push given path */
8383 lua_pushstring(L, ";"); /* push semicolon */
8384 lua_getfield(L, -3, type); /* push old path */
8385 lua_concat(L, 3); /* concatenate to new path */
8386 lua_setfield(L, -2, type); /* store new path */
8387 lua_pop(L, 1); /* pop package variable */
Tim Duesterhusc9fc9f22020-01-12 13:55:39 +01008388
8389 return 0;
8390}
8391
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008392static int hlua_config_prepend_path(char **args, int section_type, struct proxy *curpx,
Willy Tarreau01825162021-03-09 09:53:46 +01008393 const struct proxy *defpx, const char *file, int line,
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008394 char **err)
8395{
8396 char *path;
8397 char *type = "path";
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008398 struct prepend_path *p = NULL;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008399
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008400 if (too_many_args(2, args, err, NULL)) {
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008401 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008402 }
8403
8404 if (!(*args[1])) {
8405 memprintf(err, "'%s' expects to receive a <path> as argument", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008406 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008407 }
8408 path = args[1];
8409
8410 if (*args[2]) {
8411 if (strcmp(args[2], "path") != 0 && strcmp(args[2], "cpath") != 0) {
8412 memprintf(err, "'%s' expects <type> to either be 'path' or 'cpath'", args[0]);
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008413 goto err;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008414 }
8415 type = args[2];
8416 }
8417
Thierry Fournier59f11be2020-11-29 00:37:41 +01008418 p = calloc(1, sizeof(*p));
8419 if (p == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +01008420 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008421 goto err;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008422 }
8423 p->path = strdup(path);
8424 if (p->path == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +01008425 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008426 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008427 }
8428 p->type = strdup(type);
8429 if (p->type == NULL) {
Tim Duesterhusf89d43a2021-01-03 20:04:37 +01008430 memprintf(err, "memory allocation failed");
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008431 goto err2;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008432 }
8433 LIST_ADDQ(&prepend_path_list, &p->l);
8434
8435 hlua_prepend_path(hlua_states[0], type, path);
8436 hlua_prepend_path(hlua_states[1], type, path);
8437 return 0;
Tim Duesterhus621e74a2021-01-03 20:04:36 +01008438
8439err2:
8440 free(p->type);
8441 free(p->path);
8442err:
8443 free(p);
8444 return -1;
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008445}
8446
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008447/* configuration keywords declaration */
8448static struct cfg_kw_list cfg_kws = {{ },{
Tim Duesterhusdd74b5f2020-01-12 13:55:40 +01008449 { CFG_GLOBAL, "lua-prepend-path", hlua_config_prepend_path },
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008450 { CFG_GLOBAL, "lua-load", hlua_load },
Thierry Fournier59f11be2020-11-29 00:37:41 +01008451 { CFG_GLOBAL, "lua-load-per-thread", hlua_load_per_thread },
Thierry FOURNIERbd413492015-03-03 16:52:26 +01008452 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
8453 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02008454 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01008455 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01008456 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01008457 { 0, NULL, NULL },
8458}};
8459
Willy Tarreau0108d902018-11-25 19:14:37 +01008460INITCALL1(STG_REGISTER, cfg_register_keywords, &cfg_kws);
8461
Christopher Fauletafd8f102018-11-08 11:34:21 +01008462
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008463/* This function can fail with an abort() due to an Lua critical error.
8464 * We are in the initialisation process of HAProxy, this abort() is
8465 * tolerated.
8466 */
Thierry Fournierb8cef172020-11-28 15:37:17 +01008467int hlua_post_init_state(lua_State *L)
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008468{
8469 struct hlua_init_function *init;
8470 const char *msg;
8471 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008472 const char *error;
Thierry Fournier670db242020-11-28 10:49:59 +01008473 const char *kind;
8474 const char *trace;
8475 int return_status = 1;
8476#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
8477 int nres;
8478#endif
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008479
Willy Tarreaucdb53462020-12-02 12:12:00 +01008480 /* disable memory limit checks if limit is not set */
8481 if (!hlua_global_allocator.limit)
8482 hlua_global_allocator.limit = ~hlua_global_allocator.limit;
8483
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05008484 /* Call post initialisation function in safe environment. */
Thierry Fournier3c539322020-11-28 16:05:05 +01008485 if (setjmp(safe_ljmp_env) != 0) {
8486 lua_atpanic(L, hlua_panic_safe);
Thierry Fournierb8cef172020-11-28 15:37:17 +01008487 if (lua_type(L, -1) == LUA_TSTRING)
8488 error = lua_tostring(L, -1);
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008489 else
8490 error = "critical error";
8491 fprintf(stderr, "Lua post-init: %s.\n", error);
8492 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +01008493 } else {
8494 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008495 }
Frédéric Lécaille54f2bcf2018-08-29 13:46:24 +02008496
Thierry Fournierb8cef172020-11-28 15:37:17 +01008497 hlua_fcn_post_init(L);
Thierry Fournier3d4a6752016-02-19 20:53:30 +01008498
Thierry Fournierc7492592020-11-28 23:57:24 +01008499 list_for_each_entry(init, &hlua_init_functions[hlua_state_id], l) {
Thierry Fournierb8cef172020-11-28 15:37:17 +01008500 lua_rawgeti(L, LUA_REGISTRYINDEX, init->function_ref);
Thierry Fournier670db242020-11-28 10:49:59 +01008501
8502#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 504
Thierry Fournierb8cef172020-11-28 15:37:17 +01008503 ret = lua_resume(L, L, 0, &nres);
Thierry Fournier670db242020-11-28 10:49:59 +01008504#else
Thierry Fournierb8cef172020-11-28 15:37:17 +01008505 ret = lua_resume(L, L, 0);
Thierry Fournier670db242020-11-28 10:49:59 +01008506#endif
8507 kind = NULL;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008508 switch (ret) {
Thierry Fournier670db242020-11-28 10:49:59 +01008509
8510 case LUA_OK:
Thierry Fournierb8cef172020-11-28 15:37:17 +01008511 lua_pop(L, -1);
Thierry Fournier13d08b72020-11-28 11:02:58 +01008512 break;
Thierry Fournier670db242020-11-28 10:49:59 +01008513
8514 case LUA_ERRERR:
8515 kind = "message handler error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008516 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +01008517 case LUA_ERRRUN:
8518 if (!kind)
8519 kind = "runtime error";
Thierry Fournierb8cef172020-11-28 15:37:17 +01008520 msg = lua_tostring(L, -1);
8521 lua_settop(L, 0); /* Empty the stack. */
8522 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01008523 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +01008524 if (msg)
8525 ha_alert("Lua init: %s: '%s' from %s\n", kind, msg, trace);
8526 else
8527 ha_alert("Lua init: unknown %s from %s\n", kind, trace);
8528 return_status = 0;
8529 break;
8530
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008531 default:
Thierry Fournier670db242020-11-28 10:49:59 +01008532 /* Unknown error */
8533 kind = "Unknown error";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008534 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +01008535 case LUA_YIELD:
8536 /* yield is not configured at this step, this state doesn't happen */
8537 if (!kind)
8538 kind = "yield not allowed";
Thayne McCombs8f0cc5c2021-01-07 21:35:52 -07008539 /* Fall through */
Thierry Fournier670db242020-11-28 10:49:59 +01008540 case LUA_ERRMEM:
8541 if (!kind)
8542 kind = "out of memory error";
Thierry Fournierb8cef172020-11-28 15:37:17 +01008543 lua_settop(L, 0);
8544 lua_pop(L, 1);
Christopher Fauletd09cc512021-03-24 14:48:45 +01008545 trace = hlua_traceback(L, ", ");
Thierry Fournier670db242020-11-28 10:49:59 +01008546 ha_alert("Lua init: %s: %s\n", kind, trace);
8547 return_status = 0;
8548 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008549 }
Thierry Fournier670db242020-11-28 10:49:59 +01008550 if (!return_status)
8551 break;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008552 }
Thierry Fournier3c539322020-11-28 16:05:05 +01008553
8554 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier670db242020-11-28 10:49:59 +01008555 return return_status;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008556}
8557
Thierry Fournierb8cef172020-11-28 15:37:17 +01008558int hlua_post_init()
8559{
Thierry Fournier59f11be2020-11-29 00:37:41 +01008560 int ret;
8561 int i;
8562 int errors;
8563 char *err = NULL;
8564 struct hlua_function *fcn;
8565
Thierry Fournierb8cef172020-11-28 15:37:17 +01008566#if USE_OPENSSL
8567 /* Initialize SSL server. */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01008568 if (socket_ssl->xprt->prepare_srv) {
Thierry Fournierb8cef172020-11-28 15:37:17 +01008569 int saved_used_backed = global.ssl_used_backend;
8570 // don't affect maxconn automatic computation
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01008571 socket_ssl->xprt->prepare_srv(socket_ssl);
Thierry Fournierb8cef172020-11-28 15:37:17 +01008572 global.ssl_used_backend = saved_used_backed;
8573 }
8574#endif
8575
Thierry Fournierc7492592020-11-28 23:57:24 +01008576 /* Perform post init of common thread */
8577 hlua_state_id = 0;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008578 ha_set_tid(0);
8579 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
8580 if (ret == 0)
8581 return 0;
8582
8583 /* init remaining lua states and load files */
8584 for (hlua_state_id = 2; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
8585
8586 /* set thread context */
8587 ha_set_tid(hlua_state_id - 1);
8588
8589 /* Init lua state */
8590 hlua_states[hlua_state_id] = hlua_init_state(hlua_state_id);
8591
8592 /* Load lua files */
8593 for (i = 0; per_thread_load && per_thread_load[i]; i++) {
8594 ret = hlua_load_state(per_thread_load[i], hlua_states[hlua_state_id], &err);
8595 if (ret != 0) {
8596 ha_alert("Lua init: %s\n", err);
8597 return 0;
8598 }
8599 }
8600 }
8601
8602 /* Reset thread context */
8603 ha_set_tid(0);
8604
8605 /* Execute post init for all states */
8606 for (hlua_state_id = 1; hlua_state_id < global.nbthread + 1; hlua_state_id++) {
8607
8608 /* set thread context */
8609 ha_set_tid(hlua_state_id - 1);
8610
8611 /* run post init */
8612 ret = hlua_post_init_state(hlua_states[hlua_state_id]);
8613 if (ret == 0)
8614 return 0;
8615 }
8616
8617 /* Reset thread context */
8618 ha_set_tid(0);
8619
8620 /* control functions registering. Each function must have:
8621 * - only the function_ref[0] set positive and all other to -1
8622 * - only the function_ref[0] set to -1 and all other positive
8623 * This ensure a same reference is not used both in shared
8624 * lua state and thread dedicated lua state. Note: is the case
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05008625 * reach, the shared state is priority, but the bug will be
Thierry Fournier59f11be2020-11-29 00:37:41 +01008626 * complicated to found for the end user.
8627 */
8628 errors = 0;
8629 list_for_each_entry(fcn, &referenced_functions, l) {
8630 ret = 0;
8631 for (i = 1; i < global.nbthread + 1; i++) {
8632 if (fcn->function_ref[i] == -1)
8633 ret--;
8634 else
8635 ret++;
8636 }
8637 if (abs(ret) != global.nbthread) {
8638 ha_alert("Lua function '%s' is not referenced in all thread. "
8639 "Expect function in all thread or in none thread.\n", fcn->name);
8640 errors++;
8641 continue;
8642 }
8643
8644 if ((fcn->function_ref[0] == -1) == (ret < 0)) {
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05008645 ha_alert("Lua function '%s' is referenced both ins shared Lua context (through lua-load) "
8646 "and per-thread Lua context (through lua-load-per-thread). these two context "
Thierry Fournier59f11be2020-11-29 00:37:41 +01008647 "exclusive.\n", fcn->name);
8648 errors++;
8649 }
8650 }
8651
8652 if (errors > 0)
8653 return 0;
8654
Ilya Shipitsinb8888ab2021-01-06 21:20:16 +05008655 /* after this point, this global will no longer be used, so set to
Thierry Fournier59f11be2020-11-29 00:37:41 +01008656 * -1 in order to have probably a segfault if someone use it
8657 */
8658 hlua_state_id = -1;
8659
8660 return 1;
Thierry Fournierb8cef172020-11-28 15:37:17 +01008661}
8662
Willy Tarreau32f61e22015-03-18 17:54:59 +01008663/* The memory allocator used by the Lua stack. <ud> is a pointer to the
8664 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
8665 * is the previously allocated size or the kind of object in case of a new
Willy Tarreaud36c7fa2020-12-02 12:26:29 +01008666 * allocation. <nsize> is the requested new size. A new allocation is
8667 * indicated by <ptr> being NULL. A free is indicated by <nsize> being
Willy Tarreaucdb53462020-12-02 12:12:00 +01008668 * zero. This one verifies that the limits are respected but is optimized
8669 * for the fast case where limits are not used, hence stats are not updated.
Willy Tarreau32f61e22015-03-18 17:54:59 +01008670 */
8671static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
8672{
8673 struct hlua_mem_allocator *zone = ud;
Willy Tarreaucdb53462020-12-02 12:12:00 +01008674 size_t limit, old, new;
8675
Tim Duesterhus22586522021-01-08 10:35:33 +01008676 if (unlikely(!ptr && !nsize))
8677 return NULL;
8678
Willy Tarreaucdb53462020-12-02 12:12:00 +01008679 /* a limit of ~0 means unlimited and boot complete, so there's no need
8680 * for accounting anymore.
8681 */
Christopher Fauletcc2c4f82021-03-24 14:52:24 +01008682 if (likely(~zone->limit == 0))
8683 return realloc(ptr, nsize);
Willy Tarreau32f61e22015-03-18 17:54:59 +01008684
Willy Tarreaud36c7fa2020-12-02 12:26:29 +01008685 if (!ptr)
8686 osize = 0;
Willy Tarreau32f61e22015-03-18 17:54:59 +01008687
Willy Tarreaucdb53462020-12-02 12:12:00 +01008688 /* enforce strict limits across all threads */
8689 limit = zone->limit;
8690 old = _HA_ATOMIC_LOAD(&zone->allocated);
8691 do {
8692 new = old + nsize - osize;
8693 if (unlikely(nsize && limit && new > limit))
8694 return NULL;
8695 } while (!_HA_ATOMIC_CAS(&zone->allocated, &old, new));
Willy Tarreau32f61e22015-03-18 17:54:59 +01008696
8697 ptr = realloc(ptr, nsize);
Willy Tarreaucdb53462020-12-02 12:12:00 +01008698
8699 if (unlikely(!ptr && nsize)) // failed
8700 _HA_ATOMIC_SUB(&zone->allocated, nsize - osize);
8701
8702 __ha_barrier_atomic_store();
Willy Tarreau32f61e22015-03-18 17:54:59 +01008703 return ptr;
8704}
8705
Thierry Fournierecb83c22020-11-28 15:49:44 +01008706/* This function can fail with an abort() due to a Lua critical error.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008707 * We are in the initialisation process of HAProxy, this abort() is
8708 * tolerated.
8709 */
Thierry Fournierecb83c22020-11-28 15:49:44 +01008710lua_State *hlua_init_state(int thread_num)
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008711{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008712 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008713 int idx;
8714 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008715 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008716 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01008717 const char *error_msg;
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008718 void **context;
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008719 lua_State *L;
Thierry Fournier59f11be2020-11-29 00:37:41 +01008720 struct prepend_path *pp;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008721
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008722 /* Init main lua stack. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008723 L = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008724
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008725 /* Initialise Lua context to NULL */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008726 context = lua_getextraspace(L);
Thierry Fournier4234dbd2020-11-28 13:18:23 +01008727 *context = NULL;
8728
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08008729 /* From this point, until the end of the initialisation function,
Thierry FOURNIERbabae282015-09-17 11:36:37 +02008730 * the Lua function can fail with an abort. We are in the initialisation
8731 * process of HAProxy, this abort() is tolerated.
8732 */
8733
Thierry Fournier3c539322020-11-28 16:05:05 +01008734 /* Call post initialisation function in safe environment. */
8735 if (setjmp(safe_ljmp_env) != 0) {
8736 lua_atpanic(L, hlua_panic_safe);
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008737 if (lua_type(L, -1) == LUA_TSTRING)
8738 error_msg = lua_tostring(L, -1);
Thierry Fournier2f05cc62020-11-28 16:08:02 +01008739 else
8740 error_msg = "critical error";
8741 fprintf(stderr, "Lua init: %s.\n", error_msg);
8742 exit(1);
Thierry Fournier3c539322020-11-28 16:05:05 +01008743 } else {
8744 lua_atpanic(L, hlua_panic_ljmp);
Thierry Fournier2f05cc62020-11-28 16:08:02 +01008745 }
8746
Thierry FOURNIER380d0932015-01-23 14:27:52 +01008747 /* Initialise lua. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008748 luaL_openlibs(L);
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01008749#define HLUA_PREPEND_PATH_TOSTRING1(x) #x
8750#define HLUA_PREPEND_PATH_TOSTRING(x) HLUA_PREPEND_PATH_TOSTRING1(x)
8751#ifdef HLUA_PREPEND_PATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008752 hlua_prepend_path(L, "path", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_PATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01008753#endif
8754#ifdef HLUA_PREPEND_CPATH
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008755 hlua_prepend_path(L, "cpath", HLUA_PREPEND_PATH_TOSTRING(HLUA_PREPEND_CPATH));
Tim Duesterhus541fe1e2020-01-12 13:55:41 +01008756#endif
8757#undef HLUA_PREPEND_PATH_TOSTRING
8758#undef HLUA_PREPEND_PATH_TOSTRING1
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008759
Thierry Fournier59f11be2020-11-29 00:37:41 +01008760 /* Apply configured prepend path */
8761 list_for_each_entry(pp, &prepend_path_list, l)
8762 hlua_prepend_path(L, pp->type, pp->path);
8763
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008764 /*
8765 *
8766 * Create "core" object.
8767 *
8768 */
8769
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01008770 /* This table entry is the object "core" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008771 lua_newtable(L);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008772
Thierry Fournierecb83c22020-11-28 15:49:44 +01008773 /* set the thread id */
8774 hlua_class_const_int(L, "thread", thread_num);
8775
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008776 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01008777 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008778 hlua_class_const_int(L, log_levels[i], i);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01008779
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008780 /* Register special functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008781 hlua_class_function(L, "register_init", hlua_register_init);
8782 hlua_class_function(L, "register_task", hlua_register_task);
8783 hlua_class_function(L, "register_fetches", hlua_register_fetches);
8784 hlua_class_function(L, "register_converters", hlua_register_converters);
8785 hlua_class_function(L, "register_action", hlua_register_action);
8786 hlua_class_function(L, "register_service", hlua_register_service);
8787 hlua_class_function(L, "register_cli", hlua_register_cli);
8788 hlua_class_function(L, "yield", hlua_yield);
8789 hlua_class_function(L, "set_nice", hlua_set_nice);
8790 hlua_class_function(L, "sleep", hlua_sleep);
8791 hlua_class_function(L, "msleep", hlua_msleep);
8792 hlua_class_function(L, "add_acl", hlua_add_acl);
8793 hlua_class_function(L, "del_acl", hlua_del_acl);
8794 hlua_class_function(L, "set_map", hlua_set_map);
8795 hlua_class_function(L, "del_map", hlua_del_map);
8796 hlua_class_function(L, "tcp", hlua_socket_new);
8797 hlua_class_function(L, "log", hlua_log);
8798 hlua_class_function(L, "Debug", hlua_log_debug);
8799 hlua_class_function(L, "Info", hlua_log_info);
8800 hlua_class_function(L, "Warning", hlua_log_warning);
8801 hlua_class_function(L, "Alert", hlua_log_alert);
8802 hlua_class_function(L, "done", hlua_done);
8803 hlua_fcn_reg_core_fcn(L);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01008804
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008805 lua_setglobal(L, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008806
8807 /*
8808 *
Christopher Faulet0f3c8902020-01-31 18:57:12 +01008809 * Create "act" object.
8810 *
8811 */
8812
8813 /* This table entry is the object "act" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008814 lua_newtable(L);
Christopher Faulet0f3c8902020-01-31 18:57:12 +01008815
8816 /* push action return constants */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008817 hlua_class_const_int(L, "CONTINUE", ACT_RET_CONT);
8818 hlua_class_const_int(L, "STOP", ACT_RET_STOP);
8819 hlua_class_const_int(L, "YIELD", ACT_RET_YIELD);
8820 hlua_class_const_int(L, "ERROR", ACT_RET_ERR);
8821 hlua_class_const_int(L, "DONE", ACT_RET_DONE);
8822 hlua_class_const_int(L, "DENY", ACT_RET_DENY);
8823 hlua_class_const_int(L, "ABORT", ACT_RET_ABRT);
8824 hlua_class_const_int(L, "INVALID", ACT_RET_INV);
Christopher Faulet0f3c8902020-01-31 18:57:12 +01008825
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008826 hlua_class_function(L, "wake_time", hlua_set_wake_time);
Christopher Faulet2c2c2e32020-01-31 19:07:52 +01008827
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008828 lua_setglobal(L, "act");
Christopher Faulet0f3c8902020-01-31 18:57:12 +01008829
8830 /*
8831 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008832 * Register class Map
8833 *
8834 */
8835
8836 /* This table entry is the object "Map" base. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008837 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008838
8839 /* register pattern types. */
8840 for (i=0; i<PAT_MATCH_NUM; i++)
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008841 hlua_class_const_int(L, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008842 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008843 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008844 hlua_class_const_int(L, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01008845 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008846
8847 /* register constructor. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008848 hlua_class_function(L, "new", hlua_map_new);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008849
8850 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008851 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008852
Ilya Shipitsind4259502020-04-08 01:07:56 +05008853 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008854 lua_pushstring(L, "__index");
8855 lua_newtable(L);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008856
8857 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008858 hlua_class_function(L, "lookup", hlua_map_lookup);
8859 hlua_class_function(L, "slookup", hlua_map_slookup);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008860
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008861 lua_rawset(L, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008862
Thierry Fournier45e78d72016-02-19 18:34:46 +01008863 /* Register previous table in the registry with reference and named entry.
8864 * The function hlua_register_metatable() pops the stack, so we
8865 * previously create a copy of the table.
8866 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008867 lua_pushvalue(L, -1); /* Copy the -1 entry and push it on the stack. */
8868 class_map_ref = hlua_register_metatable(L, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008869
8870 /* Assign the metatable to the mai Map object. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008871 lua_setmetatable(L, -2);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008872
8873 /* Set a name to the table. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008874 lua_setglobal(L, "Map");
Thierry FOURNIER3def3932015-04-07 11:27:54 +02008875
8876 /*
8877 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008878 * Register class Channel
8879 *
8880 */
8881
8882 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008883 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008884
Ilya Shipitsind4259502020-04-08 01:07:56 +05008885 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008886 lua_pushstring(L, "__index");
8887 lua_newtable(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008888
8889 /* Register . */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008890 hlua_class_function(L, "get", hlua_channel_get);
8891 hlua_class_function(L, "dup", hlua_channel_dup);
8892 hlua_class_function(L, "getline", hlua_channel_getline);
8893 hlua_class_function(L, "set", hlua_channel_set);
8894 hlua_class_function(L, "append", hlua_channel_append);
8895 hlua_class_function(L, "send", hlua_channel_send);
8896 hlua_class_function(L, "forward", hlua_channel_forward);
8897 hlua_class_function(L, "get_in_len", hlua_channel_get_in_len);
8898 hlua_class_function(L, "get_out_len", hlua_channel_get_out_len);
8899 hlua_class_function(L, "is_full", hlua_channel_is_full);
8900 hlua_class_function(L, "is_resp", hlua_channel_is_resp);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008901
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008902 lua_rawset(L, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008903
8904 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008905 class_channel_ref = hlua_register_metatable(L, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01008906
8907 /*
8908 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008909 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008910 *
8911 */
8912
8913 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008914 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008915
Ilya Shipitsind4259502020-04-08 01:07:56 +05008916 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008917 lua_pushstring(L, "__index");
8918 lua_newtable(L);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01008919
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008920 /* Browse existing fetches and create the associated
8921 * object method.
8922 */
8923 sf = NULL;
8924 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008925 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8926 * by an underscore.
8927 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008928 strncpy(trash.area, sf->kw, trash.size);
8929 trash.area[trash.size - 1] = '\0';
8930 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008931 if (*p == '.' || *p == '-' || *p == '+')
8932 *p = '_';
8933
8934 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008935 lua_pushstring(L, trash.area);
8936 lua_pushlightuserdata(L, sf);
8937 lua_pushcclosure(L, hlua_run_sample_fetch, 1);
8938 lua_rawset(L, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01008939 }
8940
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008941 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008942
8943 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008944 class_fetches_ref = hlua_register_metatable(L, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01008945
8946 /*
8947 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008948 * Register class Converters
8949 *
8950 */
8951
8952 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008953 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008954
8955 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008956 lua_pushstring(L, "__index");
8957 lua_newtable(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008958
8959 /* Browse existing converters and create the associated
8960 * object method.
8961 */
8962 sc = NULL;
8963 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008964 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
8965 * by an underscore.
8966 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02008967 strncpy(trash.area, sc->kw, trash.size);
8968 trash.area[trash.size - 1] = '\0';
8969 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008970 if (*p == '.' || *p == '-' || *p == '+')
8971 *p = '_';
8972
8973 /* Register the function. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008974 lua_pushstring(L, trash.area);
8975 lua_pushlightuserdata(L, sc);
8976 lua_pushcclosure(L, hlua_run_sample_conv, 1);
8977 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008978 }
8979
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008980 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008981
8982 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008983 class_converters_ref = hlua_register_metatable(L, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01008984
8985 /*
8986 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008987 * Register class HTTP
8988 *
8989 */
8990
8991 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008992 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008993
Ilya Shipitsind4259502020-04-08 01:07:56 +05008994 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008995 lua_pushstring(L, "__index");
8996 lua_newtable(L);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01008997
8998 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01008999 hlua_class_function(L, "req_get_headers",hlua_http_req_get_headers);
9000 hlua_class_function(L, "req_del_header", hlua_http_req_del_hdr);
9001 hlua_class_function(L, "req_rep_header", hlua_http_req_rep_hdr);
9002 hlua_class_function(L, "req_rep_value", hlua_http_req_rep_val);
9003 hlua_class_function(L, "req_add_header", hlua_http_req_add_hdr);
9004 hlua_class_function(L, "req_set_header", hlua_http_req_set_hdr);
9005 hlua_class_function(L, "req_set_method", hlua_http_req_set_meth);
9006 hlua_class_function(L, "req_set_path", hlua_http_req_set_path);
9007 hlua_class_function(L, "req_set_query", hlua_http_req_set_query);
9008 hlua_class_function(L, "req_set_uri", hlua_http_req_set_uri);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009009
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009010 hlua_class_function(L, "res_get_headers",hlua_http_res_get_headers);
9011 hlua_class_function(L, "res_del_header", hlua_http_res_del_hdr);
9012 hlua_class_function(L, "res_rep_header", hlua_http_res_rep_hdr);
9013 hlua_class_function(L, "res_rep_value", hlua_http_res_rep_val);
9014 hlua_class_function(L, "res_add_header", hlua_http_res_add_hdr);
9015 hlua_class_function(L, "res_set_header", hlua_http_res_set_hdr);
9016 hlua_class_function(L, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009017
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009018 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009019
9020 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009021 class_http_ref = hlua_register_metatable(L, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01009022
9023 /*
9024 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009025 * Register class AppletTCP
9026 *
9027 */
9028
9029 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009030 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009031
Ilya Shipitsind4259502020-04-08 01:07:56 +05009032 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009033 lua_pushstring(L, "__index");
9034 lua_newtable(L);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009035
9036 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009037 hlua_class_function(L, "getline", hlua_applet_tcp_getline);
9038 hlua_class_function(L, "receive", hlua_applet_tcp_recv);
9039 hlua_class_function(L, "send", hlua_applet_tcp_send);
9040 hlua_class_function(L, "set_priv", hlua_applet_tcp_set_priv);
9041 hlua_class_function(L, "get_priv", hlua_applet_tcp_get_priv);
9042 hlua_class_function(L, "set_var", hlua_applet_tcp_set_var);
9043 hlua_class_function(L, "unset_var", hlua_applet_tcp_unset_var);
9044 hlua_class_function(L, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009045
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009046 lua_settable(L, -3);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009047
9048 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009049 class_applet_tcp_ref = hlua_register_metatable(L, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02009050
9051 /*
9052 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009053 * Register class AppletHTTP
9054 *
9055 */
9056
9057 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009058 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009059
Ilya Shipitsind4259502020-04-08 01:07:56 +05009060 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009061 lua_pushstring(L, "__index");
9062 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009063
9064 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009065 hlua_class_function(L, "set_priv", hlua_applet_http_set_priv);
9066 hlua_class_function(L, "get_priv", hlua_applet_http_get_priv);
9067 hlua_class_function(L, "set_var", hlua_applet_http_set_var);
9068 hlua_class_function(L, "unset_var", hlua_applet_http_unset_var);
9069 hlua_class_function(L, "get_var", hlua_applet_http_get_var);
9070 hlua_class_function(L, "getline", hlua_applet_http_getline);
9071 hlua_class_function(L, "receive", hlua_applet_http_recv);
9072 hlua_class_function(L, "send", hlua_applet_http_send);
9073 hlua_class_function(L, "add_header", hlua_applet_http_addheader);
9074 hlua_class_function(L, "set_status", hlua_applet_http_status);
9075 hlua_class_function(L, "start_response", hlua_applet_http_start_response);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009076
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009077 lua_settable(L, -3);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009078
9079 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009080 class_applet_http_ref = hlua_register_metatable(L, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02009081
9082 /*
9083 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009084 * Register class TXN
9085 *
9086 */
9087
9088 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009089 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009090
Ilya Shipitsind4259502020-04-08 01:07:56 +05009091 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009092 lua_pushstring(L, "__index");
9093 lua_newtable(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01009094
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01009095 /* Register Lua functions. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009096 hlua_class_function(L, "set_priv", hlua_set_priv);
9097 hlua_class_function(L, "get_priv", hlua_get_priv);
9098 hlua_class_function(L, "set_var", hlua_set_var);
9099 hlua_class_function(L, "unset_var", hlua_unset_var);
9100 hlua_class_function(L, "get_var", hlua_get_var);
9101 hlua_class_function(L, "done", hlua_txn_done);
9102 hlua_class_function(L, "reply", hlua_txn_reply_new);
9103 hlua_class_function(L, "set_loglevel", hlua_txn_set_loglevel);
9104 hlua_class_function(L, "set_tos", hlua_txn_set_tos);
9105 hlua_class_function(L, "set_mark", hlua_txn_set_mark);
9106 hlua_class_function(L, "set_priority_class", hlua_txn_set_priority_class);
9107 hlua_class_function(L, "set_priority_offset", hlua_txn_set_priority_offset);
9108 hlua_class_function(L, "deflog", hlua_txn_deflog);
9109 hlua_class_function(L, "log", hlua_txn_log);
9110 hlua_class_function(L, "Debug", hlua_txn_log_debug);
9111 hlua_class_function(L, "Info", hlua_txn_log_info);
9112 hlua_class_function(L, "Warning", hlua_txn_log_warning);
9113 hlua_class_function(L, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01009114
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009115 lua_rawset(L, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01009116
9117 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009118 class_txn_ref = hlua_register_metatable(L, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009119
9120 /*
9121 *
Christopher Faulet700d9e82020-01-31 12:21:52 +01009122 * Register class reply
9123 *
9124 */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009125 lua_newtable(L);
9126 lua_pushstring(L, "__index");
9127 lua_newtable(L);
9128 hlua_class_function(L, "set_status", hlua_txn_reply_set_status);
9129 hlua_class_function(L, "add_header", hlua_txn_reply_add_header);
9130 hlua_class_function(L, "del_header", hlua_txn_reply_del_header);
9131 hlua_class_function(L, "set_body", hlua_txn_reply_set_body);
9132 lua_settable(L, -3); /* Sets the __index entry. */
9133 class_txn_reply_ref = luaL_ref(L, LUA_REGISTRYINDEX);
Christopher Faulet700d9e82020-01-31 12:21:52 +01009134
9135
9136 /*
9137 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009138 * Register class Socket
9139 *
9140 */
9141
9142 /* Create and fill the metatable. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009143 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009144
Ilya Shipitsind4259502020-04-08 01:07:56 +05009145 /* Create and fill the __index entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009146 lua_pushstring(L, "__index");
9147 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009148
Baptiste Assmann84bb4932015-03-02 21:40:06 +01009149#ifdef USE_OPENSSL
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009150 hlua_class_function(L, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01009151#endif
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009152 hlua_class_function(L, "connect", hlua_socket_connect);
9153 hlua_class_function(L, "send", hlua_socket_send);
9154 hlua_class_function(L, "receive", hlua_socket_receive);
9155 hlua_class_function(L, "close", hlua_socket_close);
9156 hlua_class_function(L, "getpeername", hlua_socket_getpeername);
9157 hlua_class_function(L, "getsockname", hlua_socket_getsockname);
9158 hlua_class_function(L, "setoption", hlua_socket_setoption);
9159 hlua_class_function(L, "settimeout", hlua_socket_settimeout);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009160
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009161 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009162
9163 /* Register the garbage collector entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009164 lua_pushstring(L, "__gc");
9165 lua_pushcclosure(L, hlua_socket_gc, 0);
9166 lua_rawset(L, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009167
9168 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier1eac28f2020-11-28 12:26:24 +01009169 class_socket_ref = hlua_register_metatable(L, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009170
Thierry Fournieraafc7772020-12-04 11:47:47 +01009171 lua_atpanic(L, hlua_panic_safe);
9172
9173 return L;
9174}
9175
9176void hlua_init(void) {
9177 int i;
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01009178 char *errmsg;
Thierry Fournieraafc7772020-12-04 11:47:47 +01009179#ifdef USE_OPENSSL
9180 struct srv_kw *kw;
9181 int tmp_error;
9182 char *error;
9183 char *args[] = { /* SSL client configuration. */
9184 "ssl",
9185 "verify",
9186 "none",
9187 NULL
9188 };
9189#endif
9190
9191 /* Init post init function list head */
9192 for (i = 0; i < MAX_THREADS + 1; i++)
9193 LIST_INIT(&hlua_init_functions[i]);
9194
9195 /* Init state for common/shared lua parts */
9196 hlua_state_id = 0;
9197 ha_set_tid(0);
9198 hlua_states[0] = hlua_init_state(0);
9199
9200 /* Init state 1 for thread 0. We have at least one thread. */
9201 hlua_state_id = 1;
9202 ha_set_tid(0);
9203 hlua_states[1] = hlua_init_state(1);
9204
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009205 /* Proxy and server configuration initialisation. */
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01009206 socket_proxy = alloc_new_proxy("LUA-SOCKET", PR_CAP_FE|PR_CAP_BE|PR_CAP_LUA, &errmsg);
9207 if (!socket_proxy) {
9208 fprintf(stderr, "Lua init: %s\n", errmsg);
9209 exit(1);
9210 }
9211 proxy_preset_defaults(socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009212
9213 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009214 socket_tcp = new_server(socket_proxy);
9215 if (!socket_tcp) {
9216 fprintf(stderr, "Lua init: failed to allocate tcp server socket\n");
9217 exit(1);
9218 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009219
9220#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009221 /* Init TCP server: unchanged parameters */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009222 socket_ssl = new_server(socket_proxy);
9223 if (!socket_ssl) {
9224 fprintf(stderr, "Lua init: failed to allocate ssl server socket\n");
9225 exit(1);
9226 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009227
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009228 socket_ssl->use_ssl = 1;
9229 socket_ssl->xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009230
Bertrand Jacquin80839ff2021-01-21 19:14:46 +00009231 for (i = 0; args[i] != NULL; i++) {
9232 if ((kw = srv_find_kw(args[i])) != NULL) { /* Maybe it's registered server keyword */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009233 /*
9234 *
9235 * If the keyword is not known, we can search in the registered
Joseph Herlantb8f9c5e2018-11-15 10:06:08 -08009236 * server keywords. This is useful to configure special SSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009237 * features like client certificates and ssl_verify.
9238 *
9239 */
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009240 tmp_error = kw->parse(args, &i, socket_proxy, socket_ssl, &error);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009241 if (tmp_error != 0) {
9242 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
9243 abort(); /* This must be never arrives because the command line
9244 not editable by the user. */
9245 }
Bertrand Jacquin80839ff2021-01-21 19:14:46 +00009246 i += kw->skip;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009247 }
9248 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01009249#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01009250
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01009251}
Willy Tarreaubb57d942016-12-21 19:04:56 +01009252
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +02009253static void hlua_deinit()
9254{
Willy Tarreau186f3762020-12-04 11:48:12 +01009255 int thr;
9256
9257 for (thr = 0; thr < MAX_THREADS+1; thr++) {
9258 if (hlua_states[thr])
9259 lua_close(hlua_states[thr]);
9260 }
Willy Tarreau430bf4a2021-03-04 09:45:32 +01009261
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009262 free_server(socket_tcp);
Willy Tarreau430bf4a2021-03-04 09:45:32 +01009263
Willy Tarreau0f143af2021-03-05 10:41:48 +01009264#ifdef USE_OPENSSL
Amaury Denoyelle704ba1d2021-03-24 17:57:47 +01009265 free_server(socket_ssl);
Willy Tarreau0f143af2021-03-05 10:41:48 +01009266#endif
Amaury Denoyelle239fdbf2021-03-24 10:22:03 +01009267
9268 free_proxy(socket_proxy);
Tim Duesterhusd0c0ca22020-07-04 11:53:26 +02009269}
9270
9271REGISTER_POST_DEINIT(hlua_deinit);
9272
Willy Tarreau80713382018-11-26 10:19:54 +01009273static void hlua_register_build_options(void)
9274{
Willy Tarreaubb57d942016-12-21 19:04:56 +01009275 char *ptr = NULL;
Willy Tarreau80713382018-11-26 10:19:54 +01009276
Willy Tarreaubb57d942016-12-21 19:04:56 +01009277 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
9278 hap_register_build_opts(ptr, 1);
9279}
Willy Tarreau80713382018-11-26 10:19:54 +01009280
9281INITCALL0(STG_REGISTER, hlua_register_build_options);