blob: 4d42b1fec8b777848ecd133ba9c4abe7b5168e5b [file] [log] [blame]
Thierry Fourniere726b142016-02-11 17:57:57 +01001/*
2 * Lua unsafe core engine
3 *
4 * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010013#include <ctype.h>
Mark Lakes56cc1252018-03-27 09:48:06 +020014#include <limits.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020015#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010016
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010017#include <lauxlib.h>
18#include <lua.h>
19#include <lualib.h>
20
Thierry FOURNIER463119c2015-03-10 00:35:36 +010021#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
22#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010023#endif
24
Thierry FOURNIER380d0932015-01-23 14:27:52 +010025#include <ebpttree.h>
26
27#include <common/cfgparse.h>
Thierry FOURNIER2da788e2017-09-11 18:37:23 +020028#include <common/xref.h>
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +020029#include <common/hathreads.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010030
William Lallemand9ed62032016-11-21 17:49:11 +010031#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010032#include <types/hlua.h>
33#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010034#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010035
Thierry FOURNIER55da1652015-01-23 11:36:30 +010036#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020037#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010038#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010039#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010040#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010041#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010042#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010043#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010044#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020045#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010046#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010047#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010048#include <proto/payload.h>
49#include <proto/proto_http.h>
50#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010051#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020052#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020053#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010054#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010055#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010056#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020057#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010058
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010059/* Lua uses longjmp to perform yield or throwing errors. This
60 * macro is used only for identifying the function that can
61 * not return because a longjmp is executed.
62 * __LJMP marks a prototype of hlua file that can use longjmp.
63 * WILL_LJMP() marks an lua function that will use longjmp.
64 * MAY_LJMP() marks an lua function that may use longjmp.
65 */
66#define __LJMP
67#define WILL_LJMP(func) func
68#define MAY_LJMP(func) func
69
Thierry FOURNIERbabae282015-09-17 11:36:37 +020070/* This couple of function executes securely some Lua calls outside of
71 * the lua runtime environment. Each Lua call can return a longjmp
72 * if it encounter a memory error.
73 *
74 * Lua documentation extract:
75 *
76 * If an error happens outside any protected environment, Lua calls
77 * a panic function (see lua_atpanic) and then calls abort, thus
78 * exiting the host application. Your panic function can avoid this
79 * exit by never returning (e.g., doing a long jump to your own
80 * recovery point outside Lua).
81 *
82 * The panic function runs as if it were a message handler (see
83 * §2.3); in particular, the error message is at the top of the
84 * stack. However, there is no guarantee about stack space. To push
85 * anything on the stack, the panic function must first check the
86 * available space (see §4.2).
87 *
88 * We must check all the Lua entry point. This includes:
89 * - The include/proto/hlua.h exported functions
90 * - the task wrapper function
91 * - The action wrapper function
92 * - The converters wrapper function
93 * - The sample-fetch wrapper functions
94 *
95 * It is tolerated that the initilisation function returns an abort.
96 * Before each Lua abort, an error message is writed on stderr.
97 *
98 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
99 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
100 * because they must be exists in the program stack when the longjmp
101 * is called.
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +0200102 *
103 * Note that the Lua processing is not really thread safe. It provides
104 * heavy system which consists to add our own lock function in the Lua
105 * code and recompile the library. This system will probably not accepted
106 * by maintainers of various distribs.
107 *
108 * Our main excution point of the Lua is the function lua_resume(). A
109 * quick looking on the Lua sources displays a lua_lock() a the start
110 * of function and a lua_unlock() at the end of the function. So I
111 * conclude that the Lua thread safe mode just perform a mutex around
112 * all execution. So I prefer to do this in the HAProxy code, it will be
113 * easier for distro maintainers.
114 *
115 * Note that the HAProxy lua functions rounded by the macro SET_SAFE_LJMP
116 * and RESET_SAFE_LJMP manipulates the Lua stack, so it will be careful
117 * to set mutex around these functions.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200118 */
Christopher Faulet9dcf9b62017-11-13 10:34:01 +0100119__decl_hathreads(HA_SPINLOCK_T hlua_global_lock);
Thierry FOURNIERffbad792017-07-12 11:39:04 +0200120THREAD_LOCAL jmp_buf safe_ljmp_env;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200121static int hlua_panic_safe(lua_State *L) { return 0; }
122static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
123
124#define SET_SAFE_LJMP(__L) \
125 ({ \
126 int ret; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100127 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200128 if (setjmp(safe_ljmp_env) != 0) { \
129 lua_atpanic(__L, hlua_panic_safe); \
130 ret = 0; \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100131 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200132 } else { \
133 lua_atpanic(__L, hlua_panic_ljmp); \
134 ret = 1; \
135 } \
136 ret; \
137 })
138
139/* If we are the last function catching Lua errors, we
140 * must reset the panic function.
141 */
142#define RESET_SAFE_LJMP(__L) \
143 do { \
144 lua_atpanic(__L, hlua_panic_safe); \
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100145 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock); \
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200146 } while(0)
147
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200148/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200149#define APPLET_DONE 0x01 /* applet processing is done. */
150#define APPLET_100C 0x02 /* 100 continue expected. */
151#define APPLET_HDR_SENT 0x04 /* Response header sent. */
152#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
153#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100154#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200155
156#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200157
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100158/* The main Lua execution context. */
159struct hlua gL;
160
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100161/* This is the memory pool containing struct lua for applets
162 * (including cli).
163 */
Willy Tarreaubafbe012017-11-24 17:34:44 +0100164struct pool_head *pool_head_hlua;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100165
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100166/* Used for Socket connection. */
167static struct proxy socket_proxy;
168static struct server socket_tcp;
169#ifdef USE_OPENSSL
170static struct server socket_ssl;
171#endif
172
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100173/* List head of the function called at the initialisation time. */
174struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
175
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100176/* The following variables contains the reference of the different
177 * Lua classes. These references are useful for identify metadata
178 * associated with an object.
179 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100180static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100181static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100182static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100183static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100184static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100185static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200186static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200187static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200188static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100189
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100190/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200191 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100192 * short timeout. Lua linked with tasks doesn't have a timeout
193 * because a task may remain alive during all the haproxy execution.
194 */
195static unsigned int hlua_timeout_session = 4000; /* session timeout. */
196static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200197static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100198
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100199/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
200 * it is used for preventing infinite loops.
201 *
202 * I test the scheer with an infinite loop containing one incrementation
203 * and one test. I run this loop between 10 seconds, I raise a ceil of
204 * 710M loops from one interrupt each 9000 instructions, so I fix the value
205 * to one interrupt each 10 000 instructions.
206 *
207 * configured | Number of
208 * instructions | loops executed
209 * between two | in milions
210 * forced yields |
211 * ---------------+---------------
212 * 10 | 160
213 * 500 | 670
214 * 1000 | 680
215 * 5000 | 700
216 * 7000 | 700
217 * 8000 | 700
218 * 9000 | 710 <- ceil
219 * 10000 | 710
220 * 100000 | 710
221 * 1000000 | 710
222 *
223 */
224static unsigned int hlua_nb_instruction = 10000;
225
Willy Tarreau32f61e22015-03-18 17:54:59 +0100226/* Descriptor for the memory allocation state. If limit is not null, it will
227 * be enforced on any memory allocation.
228 */
229struct hlua_mem_allocator {
230 size_t allocated;
231 size_t limit;
232};
233
234static struct hlua_mem_allocator hlua_global_allocator;
235
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200236static const char error_500[] =
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200237 "HTTP/1.0 500 Internal Server Error\r\n"
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200238 "Cache-Control: no-cache\r\n"
239 "Connection: close\r\n"
240 "Content-Type: text/html\r\n"
241 "\r\n"
Jarno Huuskonen16ad94a2017-01-09 14:17:10 +0200242 "<html><body><h1>500 Internal Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200243
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100244/* These functions converts types between HAProxy internal args or
245 * sample and LUA types. Another function permits to check if the
246 * LUA stack contains arguments according with an required ARG_T
247 * format.
248 */
249static int hlua_arg2lua(lua_State *L, const struct arg *arg);
250static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100251__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100252 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100253static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100254static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100255static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
256
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200257__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
258
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200259#define SEND_ERR(__be, __fmt, __args...) \
260 do { \
261 send_log(__be, LOG_ERR, __fmt, ## __args); \
262 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
Christopher Faulet767a84b2017-11-24 16:50:31 +0100263 ha_alert(__fmt, ## __args); \
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200264 } while (0)
265
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100266/* Used to check an Lua function type in the stack. It creates and
267 * returns a reference of the function. This function throws an
268 * error if the rgument is not a "function".
269 */
270__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
271{
272 if (!lua_isfunction(L, argno)) {
Thierry FOURNIERfd1e9552018-02-23 18:41:18 +0100273 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, argno));
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100274 WILL_LJMP(luaL_argerror(L, argno, msg));
275 }
276 lua_pushvalue(L, argno);
277 return luaL_ref(L, LUA_REGISTRYINDEX);
278}
279
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200280/* Return the string that is of the top of the stack. */
281const char *hlua_get_top_error_string(lua_State *L)
282{
283 if (lua_gettop(L) < 1)
284 return "unknown error";
285 if (lua_type(L, -1) != LUA_TSTRING)
286 return "unknown error";
287 return lua_tostring(L, -1);
288}
289
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200290__LJMP static const char *hlua_traceback(lua_State *L)
291{
292 lua_Debug ar;
293 int level = 0;
Willy Tarreau83061a82018-07-13 11:56:34 +0200294 struct buffer *msg = get_trash_chunk();
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200295 int filled = 0;
296
297 while (lua_getstack(L, level++, &ar)) {
298
299 /* Add separator */
300 if (filled)
301 chunk_appendf(msg, ", ");
302 filled = 1;
303
304 /* Fill fields:
305 * 'S': fills in the fields source, short_src, linedefined, lastlinedefined, and what;
306 * 'l': fills in the field currentline;
307 * 'n': fills in the field name and namewhat;
308 * 't': fills in the field istailcall;
309 */
310 lua_getinfo(L, "Slnt", &ar);
311
312 /* Append code localisation */
313 if (ar.currentline > 0)
314 chunk_appendf(msg, "%s:%d ", ar.short_src, ar.currentline);
315 else
316 chunk_appendf(msg, "%s ", ar.short_src);
317
318 /*
319 * Get function name
320 *
321 * if namewhat is no empty, name is defined.
322 * what contains "Lua" for Lua function, "C" for C function,
323 * or "main" for main code.
324 */
325 if (*ar.namewhat != '\0' && ar.name != NULL) /* is there a name from code? */
326 chunk_appendf(msg, "%s '%s'", ar.namewhat, ar.name); /* use it */
327
328 else if (*ar.what == 'm') /* "main", the code is not executed in a function */
329 chunk_appendf(msg, "main chunk");
330
331 else if (*ar.what != 'C') /* for Lua functions, use <file:line> */
332 chunk_appendf(msg, "C function line %d", ar.linedefined);
333
334 else /* nothing left... */
335 chunk_appendf(msg, "?");
336
337
338 /* Display tailed call */
339 if (ar.istailcall)
340 chunk_appendf(msg, " ...");
341 }
342
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200343 return msg->area;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +0200344}
345
346
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100347/* This function check the number of arguments available in the
348 * stack. If the number of arguments available is not the same
349 * then <nb> an error is throwed.
350 */
351__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
352{
353 if (lua_gettop(L) == nb)
354 return;
355 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
356}
357
Mark Lakes22154b42018-01-29 14:38:40 -0800358/* This function pushes an error string prefixed by the file name
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100359 * and the line number where the error is encountered.
360 */
361static int hlua_pusherror(lua_State *L, const char *fmt, ...)
362{
363 va_list argp;
364 va_start(argp, fmt);
365 luaL_where(L, 1);
366 lua_pushvfstring(L, fmt, argp);
367 va_end(argp);
368 lua_concat(L, 2);
369 return 1;
370}
371
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100372/* This functions is used with sample fetch and converters. It
373 * converts the HAProxy configuration argument in a lua stack
374 * values.
375 *
376 * It takes an array of "arg", and each entry of the array is
377 * converted and pushed in the LUA stack.
378 */
379static int hlua_arg2lua(lua_State *L, const struct arg *arg)
380{
381 switch (arg->type) {
382 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100383 case ARGT_TIME:
384 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100385 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100386 break;
387
388 case ARGT_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200389 lua_pushlstring(L, arg->data.str.area, arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100390 break;
391
392 case ARGT_IPV4:
393 case ARGT_IPV6:
394 case ARGT_MSK4:
395 case ARGT_MSK6:
396 case ARGT_FE:
397 case ARGT_BE:
398 case ARGT_TAB:
399 case ARGT_SRV:
400 case ARGT_USR:
401 case ARGT_MAP:
402 default:
403 lua_pushnil(L);
404 break;
405 }
406 return 1;
407}
408
409/* This function take one entrie in an LUA stack at the index "ud",
410 * and try to convert it in an HAProxy argument entry. This is useful
411 * with sample fetch wrappers. The input arguments are gived to the
412 * lua wrapper and converted as arg list by thi function.
413 */
414static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
415{
416 switch (lua_type(L, ud)) {
417
418 case LUA_TNUMBER:
419 case LUA_TBOOLEAN:
420 arg->type = ARGT_SINT;
421 arg->data.sint = lua_tointeger(L, ud);
422 break;
423
424 case LUA_TSTRING:
425 arg->type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200426 arg->data.str.area = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100427 break;
428
429 case LUA_TUSERDATA:
430 case LUA_TNIL:
431 case LUA_TTABLE:
432 case LUA_TFUNCTION:
433 case LUA_TTHREAD:
434 case LUA_TLIGHTUSERDATA:
435 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200436 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100437 break;
438 }
439 return 1;
440}
441
442/* the following functions are used to convert a struct sample
443 * in Lua type. This useful to convert the return of the
444 * fetchs or converters.
445 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100446static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100447{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200448 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100449 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100450 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200451 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100452 break;
453
454 case SMP_T_BIN:
455 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200456 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100457 break;
458
459 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200460 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100461 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
462 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
463 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
464 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
465 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
466 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
467 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
468 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
469 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200470 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100471 break;
472 default:
473 lua_pushnil(L);
474 break;
475 }
476 break;
477
478 case SMP_T_IPV4:
479 case SMP_T_IPV6:
480 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200481 if (sample_casts[smp->data.type][SMP_T_STR] &&
482 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200483 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100484 else
485 lua_pushnil(L);
486 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100487 default:
488 lua_pushnil(L);
489 break;
490 }
491 return 1;
492}
493
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100494/* the following functions are used to convert a struct sample
495 * in Lua strings. This is useful to convert the return of the
496 * fetchs or converters.
497 */
498static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
499{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200500 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100501
502 case SMP_T_BIN:
503 case SMP_T_STR:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200504 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100505 break;
506
507 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200508 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100509 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
510 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
511 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
512 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
513 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
514 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
515 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
516 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
517 case HTTP_METH_OTHER:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200518 lua_pushlstring(L, smp->data.u.meth.str.area, smp->data.u.meth.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100519 break;
520 default:
521 lua_pushstring(L, "");
522 break;
523 }
524 break;
525
526 case SMP_T_SINT:
527 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100528 case SMP_T_IPV4:
529 case SMP_T_IPV6:
530 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200531 if (sample_casts[smp->data.type][SMP_T_STR] &&
532 sample_casts[smp->data.type][SMP_T_STR](smp))
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200533 lua_pushlstring(L, smp->data.u.str.area, smp->data.u.str.data);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100534 else
535 lua_pushstring(L, "");
536 break;
537 default:
538 lua_pushstring(L, "");
539 break;
540 }
541 return 1;
542}
543
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100544/* the following functions are used to convert an Lua type in a
545 * struct sample. This is useful to provide data from a converter
546 * to the LUA code.
547 */
548static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
549{
550 switch (lua_type(L, ud)) {
551
552 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200553 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200554 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100555 break;
556
557
558 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200559 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200560 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100561 break;
562
563 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200564 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100565 smp->flags |= SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200566 smp->data.u.str.area = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.data);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100567 break;
568
569 case LUA_TUSERDATA:
570 case LUA_TNIL:
571 case LUA_TTABLE:
572 case LUA_TFUNCTION:
573 case LUA_TTHREAD:
574 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200575 case LUA_TNONE:
576 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200577 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200578 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100579 break;
580 }
581 return 1;
582}
583
584/* This function check the "argp" builded by another conversion function
585 * is in accord with the expected argp defined by the "mask". The fucntion
586 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100587 *
588 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
589 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100590 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100591__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100592 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100593{
594 int min_arg;
595 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100596 struct proxy *px;
597 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100598
599 idx = 0;
600 min_arg = ARGM(mask);
601 mask >>= ARGM_BITS;
602
603 while (1) {
604
605 /* Check oversize. */
606 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100607 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100608 }
609
610 /* Check for mandatory arguments. */
611 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100612 if (idx < min_arg) {
613
614 /* If miss other argument than the first one, we return an error. */
615 if (idx > 0)
616 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
617
618 /* If first argument have a certain type, some default values
619 * may be used. See the function smp_resolve_args().
620 */
621 switch (mask & ARGT_MASK) {
622
623 case ARGT_FE:
624 if (!(p->cap & PR_CAP_FE))
625 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
626 argp[idx].data.prx = p;
627 argp[idx].type = ARGT_FE;
628 argp[idx+1].type = ARGT_STOP;
629 break;
630
631 case ARGT_BE:
632 if (!(p->cap & PR_CAP_BE))
633 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
634 argp[idx].data.prx = p;
635 argp[idx].type = ARGT_BE;
636 argp[idx+1].type = ARGT_STOP;
637 break;
638
639 case ARGT_TAB:
640 argp[idx].data.prx = p;
641 argp[idx].type = ARGT_TAB;
642 argp[idx+1].type = ARGT_STOP;
643 break;
644
645 default:
646 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
647 break;
648 }
649 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100650 return 0;
651 }
652
653 /* Check for exceed the number of requiered argument. */
654 if ((mask & ARGT_MASK) == ARGT_STOP &&
655 argp[idx].type != ARGT_STOP) {
656 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
657 }
658
659 if ((mask & ARGT_MASK) == ARGT_STOP &&
660 argp[idx].type == ARGT_STOP) {
661 return 0;
662 }
663
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100664 /* Convert some argument types. */
665 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100666 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100667 if (argp[idx].type != ARGT_SINT)
668 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
669 argp[idx].type = ARGT_SINT;
670 break;
671
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100672 case ARGT_TIME:
673 if (argp[idx].type != ARGT_SINT)
674 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200675 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100676 break;
677
678 case ARGT_SIZE:
679 if (argp[idx].type != ARGT_SINT)
680 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200681 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100682 break;
683
684 case ARGT_FE:
685 if (argp[idx].type != ARGT_STR)
686 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200687 memcpy(trash.area, argp[idx].data.str.area,
688 argp[idx].data.str.data);
689 trash.area[argp[idx].data.str.data] = 0;
690 argp[idx].data.prx = proxy_fe_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100691 if (!argp[idx].data.prx)
692 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
693 argp[idx].type = ARGT_FE;
694 break;
695
696 case ARGT_BE:
697 if (argp[idx].type != ARGT_STR)
698 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200699 memcpy(trash.area, argp[idx].data.str.area,
700 argp[idx].data.str.data);
701 trash.area[argp[idx].data.str.data] = 0;
702 argp[idx].data.prx = proxy_be_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100703 if (!argp[idx].data.prx)
704 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
705 argp[idx].type = ARGT_BE;
706 break;
707
708 case ARGT_TAB:
709 if (argp[idx].type != ARGT_STR)
710 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200711 memcpy(trash.area, argp[idx].data.str.area,
712 argp[idx].data.str.data);
713 trash.area[argp[idx].data.str.data] = 0;
714 argp[idx].data.prx = proxy_tbl_by_name(trash.area);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100715 if (!argp[idx].data.prx)
716 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
717 argp[idx].type = ARGT_TAB;
718 break;
719
720 case ARGT_SRV:
721 if (argp[idx].type != ARGT_STR)
722 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200723 memcpy(trash.area, argp[idx].data.str.area,
724 argp[idx].data.str.data);
725 trash.area[argp[idx].data.str.data] = 0;
726 sname = strrchr(trash.area, '/');
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100727 if (sname) {
728 *sname++ = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200729 pname = trash.area;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200730 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100731 if (!px)
732 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
733 }
734 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200735 sname = trash.area;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100736 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100737 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100738 argp[idx].data.srv = findserver(px, sname);
739 if (!argp[idx].data.srv)
740 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
741 argp[idx].type = ARGT_SRV;
742 break;
743
744 case ARGT_IPV4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200745 memcpy(trash.area, argp[idx].data.str.area,
746 argp[idx].data.str.data);
747 trash.area[argp[idx].data.str.data] = 0;
748 if (inet_pton(AF_INET, trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100749 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
750 argp[idx].type = ARGT_IPV4;
751 break;
752
753 case ARGT_MSK4:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200754 memcpy(trash.area, argp[idx].data.str.area,
755 argp[idx].data.str.data);
756 trash.area[argp[idx].data.str.data] = 0;
757 if (!str2mask(trash.area, &argp[idx].data.ipv4))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100758 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
759 argp[idx].type = ARGT_MSK4;
760 break;
761
762 case ARGT_IPV6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200763 memcpy(trash.area, argp[idx].data.str.area,
764 argp[idx].data.str.data);
765 trash.area[argp[idx].data.str.data] = 0;
766 if (inet_pton(AF_INET6, trash.area, &argp[idx].data.ipv6))
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100767 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
768 argp[idx].type = ARGT_IPV6;
769 break;
770
771 case ARGT_MSK6:
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200772 memcpy(trash.area, argp[idx].data.str.area,
773 argp[idx].data.str.data);
774 trash.area[argp[idx].data.str.data] = 0;
775 if (!str2mask6(trash.area, &argp[idx].data.ipv6))
Tim Duesterhusb814da62018-01-25 16:24:50 +0100776 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 mask"));
777 argp[idx].type = ARGT_MSK6;
778 break;
779
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100780 case ARGT_MAP:
781 case ARGT_REG:
782 case ARGT_USR:
783 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100784 break;
785 }
786
787 /* Check for type of argument. */
788 if ((mask & ARGT_MASK) != argp[idx].type) {
789 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
790 arg_type_names[(mask & ARGT_MASK)],
791 arg_type_names[argp[idx].type & ARGT_MASK]);
792 WILL_LJMP(luaL_argerror(L, first + idx, msg));
793 }
794
795 /* Next argument. */
796 mask >>= ARGT_BITS;
797 idx++;
798 }
799}
800
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100801/*
802 * The following functions are used to make correspondance between the the
803 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100804 *
805 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100806 * - hlua_sethlua : create the association between hlua context and lua_state.
807 */
808static inline struct hlua *hlua_gethlua(lua_State *L)
809{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100810 struct hlua **hlua = lua_getextraspace(L);
811 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100812}
813static inline void hlua_sethlua(struct hlua *hlua)
814{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100815 struct hlua **hlua_store = lua_getextraspace(hlua->T);
816 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100817}
818
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100819/* This function is used to send logs. It try to send on screen (stderr)
820 * and on the default syslog server.
821 */
822static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
823{
824 struct tm tm;
825 char *p;
826
827 /* Cleanup the log message. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200828 p = trash.area;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100829 for (; *msg != '\0'; msg++, p++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200830 if (p >= trash.area + trash.size - 1) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200831 /* Break the message if exceed the buffer size. */
832 *(p-4) = ' ';
833 *(p-3) = '.';
834 *(p-2) = '.';
835 *(p-1) = '.';
836 break;
837 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100838 if (isprint(*msg))
839 *p = *msg;
840 else
841 *p = '.';
842 }
843 *p = '\0';
844
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200845 send_log(px, level, "%s\n", trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100846 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200847 get_localtime(date.tv_sec, &tm);
848 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100849 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200850 (int)getpid(), trash.area);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100851 fflush(stderr);
852 }
853}
854
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100855/* This function just ensure that the yield will be always
856 * returned with a timeout and permit to set some flags
857 */
858__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100859 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100860{
861 struct hlua *hlua = hlua_gethlua(L);
862
863 /* Set the wake timeout. If timeout is required, we set
864 * the expiration time.
865 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200866 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100867
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100868 hlua->flags |= flags;
869
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100870 /* Process the yield. */
871 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
872}
873
Willy Tarreau87b09662015-04-03 00:22:06 +0200874/* This function initialises the Lua environment stored in the stream.
875 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100876 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200877 *
878 * This function is particular. it initialises a new Lua thread. If the
879 * initialisation fails (example: out of memory error), the lua function
880 * throws an error (longjmp).
881 *
882 * This function manipulates two Lua stack: the main and the thread. Only
883 * the main stack can fail. The thread is not manipulated. This function
884 * MUST NOT manipulate the created thread stack state, because is not
885 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100886 */
887int hlua_ctx_init(struct hlua *lua, struct task *task)
888{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200889 if (!SET_SAFE_LJMP(gL.T)) {
890 lua->Tref = LUA_REFNIL;
891 return 0;
892 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100893 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100894 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100895 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100896 lua->T = lua_newthread(gL.T);
897 if (!lua->T) {
898 lua->Tref = LUA_REFNIL;
Thierry FOURNIER0a976202017-07-12 11:18:00 +0200899 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100900 return 0;
901 }
902 hlua_sethlua(lua);
903 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
904 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200905 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100906 return 1;
907}
908
Willy Tarreau87b09662015-04-03 00:22:06 +0200909/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100910 * is destroyed. The destroy also the memory context. The struct "lua"
911 * is not freed.
912 */
913void hlua_ctx_destroy(struct hlua *lua)
914{
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100915 if (!lua)
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100916 return;
917
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100918 if (!lua->T)
919 goto end;
920
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100921 /* Purge all the pending signals. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +0200922 notification_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100923
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200924 if (!SET_SAFE_LJMP(lua->T))
925 return;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100926 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200927 RESET_SAFE_LJMP(lua->T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200928
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200929 if (!SET_SAFE_LJMP(gL.T))
930 return;
931 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
932 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200933 /* Forces a garbage collecting process. If the Lua program is finished
934 * without error, we run the GC on the thread pointer. Its freed all
935 * the unused memory.
936 * If the thread is finnish with an error or is currently yielded,
937 * it seems that the GC applied on the thread doesn't clean anything,
938 * so e run the GC on the main thread.
939 * NOTE: maybe this action locks all the Lua threads untiml the en of
940 * the garbage collection.
941 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200942 if (lua->flags & HLUA_MUST_GC) {
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200943 if (!SET_SAFE_LJMP(gL.T))
Thierry FOURNIER75d02082017-07-12 13:41:33 +0200944 return;
Thierry FOURNIER7bd10d52017-07-17 00:44:40 +0200945 lua_gc(gL.T, LUA_GCCOLLECT, 0);
946 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200947 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200948
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200949 lua->T = NULL;
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +0100950
951end:
Willy Tarreaubafbe012017-11-24 17:34:44 +0100952 pool_free(pool_head_hlua, lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100953}
954
955/* This function is used to restore the Lua context when a coroutine
956 * fails. This function copy the common memory between old coroutine
957 * and the new coroutine. The old coroutine is destroyed, and its
958 * replaced by the new coroutine.
959 * If the flag "keep_msg" is set, the last entry of the old is assumed
960 * as string error message and it is copied in the new stack.
961 */
962static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
963{
964 lua_State *T;
965 int new_ref;
966
967 /* Renew the main LUA stack doesn't have sense. */
968 if (lua == &gL)
969 return 0;
970
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100971 /* New Lua coroutine. */
972 T = lua_newthread(gL.T);
973 if (!T)
974 return 0;
975
976 /* Copy last error message. */
977 if (keep_msg)
978 lua_xmove(lua->T, T, 1);
979
980 /* Copy data between the coroutines. */
981 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
982 lua_xmove(lua->T, T, 1);
983 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
984
985 /* Destroy old data. */
986 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
987
988 /* The thread is garbage collected by Lua. */
989 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
990
991 /* Fill the struct with the new coroutine values. */
992 lua->Mref = new_ref;
993 lua->T = T;
994 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
995
996 /* Set context. */
997 hlua_sethlua(lua);
998
999 return 1;
1000}
1001
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001002void hlua_hook(lua_State *L, lua_Debug *ar)
1003{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001004 struct hlua *hlua = hlua_gethlua(L);
1005
1006 /* Lua cannot yield when its returning from a function,
1007 * so, we can fix the interrupt hook to 1 instruction,
1008 * expecting that the function is finnished.
1009 */
1010 if (lua_gethookmask(L) & LUA_MASKRET) {
1011 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
1012 return;
1013 }
1014
1015 /* restore the interrupt condition. */
1016 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1017
1018 /* If we interrupt the Lua processing in yieldable state, we yield.
1019 * If the state is not yieldable, trying yield causes an error.
1020 */
1021 if (lua_isyieldable(L))
1022 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
1023
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +01001024 /* If we cannot yield, update the clock and check the timeout. */
1025 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001026 hlua->run_time += now_ms - hlua->start_time;
1027 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001028 lua_pushfstring(L, "execution timeout");
1029 WILL_LJMP(lua_error(L));
1030 }
1031
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001032 /* Update the start time. */
1033 hlua->start_time = now_ms;
1034
Thierry FOURNIERcae49c92015-03-06 14:05:24 +01001035 /* Try to interrupt the process at the end of the current
1036 * unyieldable function.
1037 */
1038 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001039}
1040
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001041/* This function start or resumes the Lua stack execution. If the flag
1042 * "yield_allowed" if no set and the LUA stack execution returns a yield
1043 * The function return an error.
1044 *
1045 * The function can returns 4 values:
1046 * - HLUA_E_OK : The execution is terminated without any errors.
1047 * - HLUA_E_AGAIN : The execution must continue at the next associated
1048 * task wakeup.
1049 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1050 * the top of the stack.
1051 * - HLUA_E_ERR : An error has occured without error message.
1052 *
1053 * If an error occured, the stack is renewed and it is ready to run new
1054 * LUA code.
1055 */
1056static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1057{
1058 int ret;
1059 const char *msg;
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001060 const char *trace;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001061
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001062 /* Initialise run time counter. */
1063 if (!HLUA_IS_RUNNING(lua))
1064 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001065
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001066 /* Lock the whole Lua execution. This lock must be before the
1067 * label "resume_execution".
1068 */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001069 HA_SPIN_LOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001070
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001071resume_execution:
1072
1073 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1074 * instructions. it is used for preventing infinite loops.
1075 */
1076 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1077
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001078 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001079 HLUA_SET_RUN(lua);
1080 HLUA_CLR_CTRLYIELD(lua);
1081 HLUA_CLR_WAKERESWR(lua);
1082 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001083
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001084 /* Update the start time. */
1085 lua->start_time = now_ms;
1086
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001087 /* Call the function. */
1088 ret = lua_resume(lua->T, gL.T, lua->nargs);
1089 switch (ret) {
1090
1091 case LUA_OK:
1092 ret = HLUA_E_OK;
1093 break;
1094
1095 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001096 /* Check if the execution timeout is expired. It it is the case, we
1097 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001098 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001099 tv_update_date(0, 1);
1100 lua->run_time += now_ms - lua->start_time;
1101 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001102 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001103 ret = HLUA_E_ETMOUT;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001104 break;
1105 }
1106 /* Process the forced yield. if the general yield is not allowed or
1107 * if no task were associated this the current Lua execution
1108 * coroutine, we resume the execution. Else we want to return in the
1109 * scheduler and we want to be waked up again, to continue the
1110 * current Lua execution. So we schedule our own task.
1111 */
1112 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001113 if (!yield_allowed || !lua->task)
1114 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001115 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001116 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001117 if (!yield_allowed) {
1118 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001119 ret = HLUA_E_YIELD;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001120 break;
1121 }
1122 ret = HLUA_E_AGAIN;
1123 break;
1124
1125 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001126
1127 /* Special exit case. The traditionnal exit is returned as an error
1128 * because the errors ares the only one mean to return immediately
1129 * from and lua execution.
1130 */
1131 if (lua->flags & HLUA_EXIT) {
1132 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001133 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001134 break;
1135 }
1136
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001137 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001138 if (!lua_checkstack(lua->T, 1)) {
1139 ret = HLUA_E_ERR;
1140 break;
1141 }
1142 msg = lua_tostring(lua->T, -1);
1143 lua_settop(lua->T, 0); /* Empty the stack. */
1144 lua_pop(lua->T, 1);
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001145 trace = hlua_traceback(lua->T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001146 if (msg)
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001147 lua_pushfstring(lua->T, "runtime error: %s from %s", msg, trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001148 else
Thierry FOURNIERfc044c92018-06-07 14:40:48 +02001149 lua_pushfstring(lua->T, "unknown runtime error from %s", trace);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001150 ret = HLUA_E_ERRMSG;
1151 break;
1152
1153 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001154 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001155 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001156 ret = HLUA_E_NOMEM;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001157 break;
1158
1159 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001160 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001161 if (!lua_checkstack(lua->T, 1)) {
1162 ret = HLUA_E_ERR;
1163 break;
1164 }
1165 msg = lua_tostring(lua->T, -1);
1166 lua_settop(lua->T, 0); /* Empty the stack. */
1167 lua_pop(lua->T, 1);
1168 if (msg)
1169 lua_pushfstring(lua->T, "message handler error: %s", msg);
1170 else
1171 lua_pushfstring(lua->T, "message handler error");
1172 ret = HLUA_E_ERRMSG;
1173 break;
1174
1175 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001176 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001177 lua_settop(lua->T, 0); /* Empty the stack. */
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001178 ret = HLUA_E_ERR;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001179 break;
1180 }
1181
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001182 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001183 if (lua->flags & HLUA_MUST_GC &&
1184 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001185 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1186
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001187 switch (ret) {
1188 case HLUA_E_AGAIN:
1189 break;
1190
1191 case HLUA_E_ERRMSG:
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001192 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001193 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001194 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001195 break;
1196
Thierry Fournierd5b073c2018-05-21 19:42:47 +02001197 case HLUA_E_ETMOUT:
1198 case HLUA_E_NOMEM:
1199 case HLUA_E_YIELD:
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001200 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001201 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001202 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001203 hlua_ctx_renew(lua, 0);
1204 break;
1205
1206 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001207 HLUA_CLR_RUN(lua);
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001208 notification_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001209 break;
1210 }
1211
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001212 /* This is the main exit point, remove the Lua lock. */
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001213 HA_SPIN_UNLOCK(LUA_LOCK, &hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02001214
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001215 return ret;
1216}
1217
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001218/* This function exit the current code. */
1219__LJMP static int hlua_done(lua_State *L)
1220{
1221 struct hlua *hlua = hlua_gethlua(L);
1222
1223 hlua->flags |= HLUA_EXIT;
1224 WILL_LJMP(lua_error(L));
1225
1226 return 0;
1227}
1228
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001229/* This function is an LUA binding. It provides a function
1230 * for deleting ACL from a referenced ACL file.
1231 */
1232__LJMP static int hlua_del_acl(lua_State *L)
1233{
1234 const char *name;
1235 const char *key;
1236 struct pat_ref *ref;
1237
1238 MAY_LJMP(check_args(L, 2, "del_acl"));
1239
1240 name = MAY_LJMP(luaL_checkstring(L, 1));
1241 key = MAY_LJMP(luaL_checkstring(L, 2));
1242
1243 ref = pat_ref_lookup(name);
1244 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001245 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001246
1247 pat_ref_delete(ref, key);
1248 return 0;
1249}
1250
1251/* This function is an LUA binding. It provides a function
1252 * for deleting map entry from a referenced map file.
1253 */
1254static int hlua_del_map(lua_State *L)
1255{
1256 const char *name;
1257 const char *key;
1258 struct pat_ref *ref;
1259
1260 MAY_LJMP(check_args(L, 2, "del_map"));
1261
1262 name = MAY_LJMP(luaL_checkstring(L, 1));
1263 key = MAY_LJMP(luaL_checkstring(L, 2));
1264
1265 ref = pat_ref_lookup(name);
1266 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001267 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001268
1269 pat_ref_delete(ref, key);
1270 return 0;
1271}
1272
1273/* This function is an LUA binding. It provides a function
1274 * for adding ACL pattern from a referenced ACL file.
1275 */
1276static int hlua_add_acl(lua_State *L)
1277{
1278 const char *name;
1279 const char *key;
1280 struct pat_ref *ref;
1281
1282 MAY_LJMP(check_args(L, 2, "add_acl"));
1283
1284 name = MAY_LJMP(luaL_checkstring(L, 1));
1285 key = MAY_LJMP(luaL_checkstring(L, 2));
1286
1287 ref = pat_ref_lookup(name);
1288 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001289 WILL_LJMP(luaL_error(L, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001290
1291 if (pat_ref_find_elt(ref, key) == NULL)
1292 pat_ref_add(ref, key, NULL, NULL);
1293 return 0;
1294}
1295
1296/* This function is an LUA binding. It provides a function
1297 * for setting map pattern and sample from a referenced map
1298 * file.
1299 */
1300static int hlua_set_map(lua_State *L)
1301{
1302 const char *name;
1303 const char *key;
1304 const char *value;
1305 struct pat_ref *ref;
1306
1307 MAY_LJMP(check_args(L, 3, "set_map"));
1308
1309 name = MAY_LJMP(luaL_checkstring(L, 1));
1310 key = MAY_LJMP(luaL_checkstring(L, 2));
1311 value = MAY_LJMP(luaL_checkstring(L, 3));
1312
1313 ref = pat_ref_lookup(name);
1314 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001315 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001316
1317 if (pat_ref_find_elt(ref, key) != NULL)
1318 pat_ref_set(ref, key, value, NULL);
1319 else
1320 pat_ref_add(ref, key, value, NULL);
1321 return 0;
1322}
1323
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001324/* A class is a lot of memory that contain data. This data can be a table,
1325 * an integer or user data. This data is associated with a metatable. This
1326 * metatable have an original version registred in the global context with
1327 * the name of the object (_G[<name>] = <metable> ).
1328 *
1329 * A metable is a table that modify the standard behavior of a standard
1330 * access to the associated data. The entries of this new metatable are
1331 * defined as is:
1332 *
1333 * http://lua-users.org/wiki/MetatableEvents
1334 *
1335 * __index
1336 *
1337 * we access an absent field in a table, the result is nil. This is
1338 * true, but it is not the whole truth. Actually, such access triggers
1339 * the interpreter to look for an __index metamethod: If there is no
1340 * such method, as usually happens, then the access results in nil;
1341 * otherwise, the metamethod will provide the result.
1342 *
1343 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1344 * the key does not appear in the table, but the metatable has an __index
1345 * property:
1346 *
1347 * - if the value is a function, the function is called, passing in the
1348 * table and the key; the return value of that function is returned as
1349 * the result.
1350 *
1351 * - if the value is another table, the value of the key in that table is
1352 * asked for and returned (and if it doesn't exist in that table, but that
1353 * table's metatable has an __index property, then it continues on up)
1354 *
1355 * - Use "rawget(myTable,key)" to skip this metamethod.
1356 *
1357 * http://www.lua.org/pil/13.4.1.html
1358 *
1359 * __newindex
1360 *
1361 * Like __index, but control property assignment.
1362 *
1363 * __mode - Control weak references. A string value with one or both
1364 * of the characters 'k' and 'v' which specifies that the the
1365 * keys and/or values in the table are weak references.
1366 *
1367 * __call - Treat a table like a function. When a table is followed by
1368 * parenthesis such as "myTable( 'foo' )" and the metatable has
1369 * a __call key pointing to a function, that function is invoked
1370 * (passing any specified arguments) and the return value is
1371 * returned.
1372 *
1373 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1374 * called, if the metatable for myTable has a __metatable
1375 * key, the value of that key is returned instead of the
1376 * actual metatable.
1377 *
1378 * __tostring - Control string representation. When the builtin
1379 * "tostring( myTable )" function is called, if the metatable
1380 * for myTable has a __tostring property set to a function,
1381 * that function is invoked (passing myTable to it) and the
1382 * return value is used as the string representation.
1383 *
1384 * __len - Control table length. When the table length is requested using
1385 * the length operator ( '#' ), if the metatable for myTable has
1386 * a __len key pointing to a function, that function is invoked
1387 * (passing myTable to it) and the return value used as the value
1388 * of "#myTable".
1389 *
1390 * __gc - Userdata finalizer code. When userdata is set to be garbage
1391 * collected, if the metatable has a __gc field pointing to a
1392 * function, that function is first invoked, passing the userdata
1393 * to it. The __gc metamethod is not called for tables.
1394 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1395 *
1396 * Special metamethods for redefining standard operators:
1397 * http://www.lua.org/pil/13.1.html
1398 *
1399 * __add "+"
1400 * __sub "-"
1401 * __mul "*"
1402 * __div "/"
1403 * __unm "!"
1404 * __pow "^"
1405 * __concat ".."
1406 *
1407 * Special methods for redfining standar relations
1408 * http://www.lua.org/pil/13.2.html
1409 *
1410 * __eq "=="
1411 * __lt "<"
1412 * __le "<="
1413 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001414
1415/*
1416 *
1417 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001418 * Class Map
1419 *
1420 *
1421 */
1422
1423/* Returns a struct hlua_map if the stack entry "ud" is
1424 * a class session, otherwise it throws an error.
1425 */
1426__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1427{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001428 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001429}
1430
1431/* This function is the map constructor. It don't need
1432 * the class Map object. It creates and return a new Map
1433 * object. It must be called only during "body" or "init"
1434 * context because it process some filesystem accesses.
1435 */
1436__LJMP static int hlua_map_new(struct lua_State *L)
1437{
1438 const char *fn;
1439 int match = PAT_MATCH_STR;
1440 struct sample_conv conv;
1441 const char *file = "";
1442 int line = 0;
1443 lua_Debug ar;
1444 char *err = NULL;
1445 struct arg args[2];
1446
1447 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1448 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1449
1450 fn = MAY_LJMP(luaL_checkstring(L, 1));
1451
1452 if (lua_gettop(L) >= 2) {
1453 match = MAY_LJMP(luaL_checkinteger(L, 2));
1454 if (match < 0 || match >= PAT_MATCH_NUM)
1455 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1456 }
1457
1458 /* Get Lua filename and line number. */
1459 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1460 lua_getinfo(L, "Sl", &ar); /* get info about it */
1461 if (ar.currentline > 0) { /* is there info? */
1462 file = ar.short_src;
1463 line = ar.currentline;
1464 }
1465 }
1466
1467 /* fill fake sample_conv struct. */
1468 conv.kw = ""; /* unused. */
1469 conv.process = NULL; /* unused. */
1470 conv.arg_mask = 0; /* unused. */
1471 conv.val_args = NULL; /* unused. */
1472 conv.out_type = SMP_T_STR;
1473 conv.private = (void *)(long)match;
1474 switch (match) {
1475 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1476 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1477 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1478 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1479 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1480 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1481 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001482 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001483 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1484 default:
1485 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1486 }
1487
1488 /* fill fake args. */
1489 args[0].type = ARGT_STR;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001490 args[0].data.str.area = (char *)fn;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001491 args[1].type = ARGT_STOP;
1492
1493 /* load the map. */
1494 if (!sample_load_map(args, &conv, file, line, &err)) {
1495 /* error case: we cant use luaL_error because we must
1496 * free the err variable.
1497 */
1498 luaL_where(L, 1);
1499 lua_pushfstring(L, "'new': %s.", err);
1500 lua_concat(L, 2);
1501 free(err);
1502 WILL_LJMP(lua_error(L));
1503 }
1504
1505 /* create the lua object. */
1506 lua_newtable(L);
1507 lua_pushlightuserdata(L, args[0].data.map);
1508 lua_rawseti(L, -2, 0);
1509
1510 /* Pop a class Map metatable and affect it to the userdata. */
1511 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1512 lua_setmetatable(L, -2);
1513
1514
1515 return 1;
1516}
1517
1518__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1519{
1520 struct map_descriptor *desc;
1521 struct pattern *pat;
1522 struct sample smp;
1523
1524 MAY_LJMP(check_args(L, 2, "lookup"));
1525 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001526 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001527 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001528 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001529 }
1530 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001531 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001532 smp.flags = SMP_F_CONST;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001533 smp.data.u.str.area = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.data));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001534 }
1535
1536 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001537 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001538 if (str)
1539 lua_pushstring(L, "");
1540 else
1541 lua_pushnil(L);
1542 return 1;
1543 }
1544
1545 /* The Lua pattern must return a string, so we can't check the returned type */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001546 lua_pushlstring(L, pat->data->u.str.area, pat->data->u.str.data);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001547 return 1;
1548}
1549
1550__LJMP static int hlua_map_lookup(struct lua_State *L)
1551{
1552 return _hlua_map_lookup(L, 0);
1553}
1554
1555__LJMP static int hlua_map_slookup(struct lua_State *L)
1556{
1557 return _hlua_map_lookup(L, 1);
1558}
1559
1560/*
1561 *
1562 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001563 * Class Socket
1564 *
1565 *
1566 */
1567
1568__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1569{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001570 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001571}
1572
1573/* This function is the handler called for each I/O on the established
1574 * connection. It is used for notify space avalaible to send or data
1575 * received.
1576 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001577static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001578{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001579 struct stream_interface *si = appctx->owner;
Olivier Houchard9aaf7782017-09-13 18:30:23 +02001580 struct connection *c = cs_conn(objt_cs(si_opposite(si)->end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001581
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001582 if (appctx->ctx.hlua_cosocket.die) {
1583 si_shutw(si);
1584 si_shutr(si);
1585 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001586 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1587 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001588 stream_shutdown(si_strm(si), SF_ERR_KILLED);
1589 }
1590
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001591 /* If the connection object is not avalaible, close all the
1592 * streams and wakeup everithing waiting for.
1593 */
1594 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001595 si_shutw(si);
1596 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001597 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001598 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1599 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001600 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001601 }
1602
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001603 /* If we cant write, wakeup the pending write signals. */
1604 if (channel_output_closed(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001605 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001606
1607 /* If we cant read, wakeup the pending read signals. */
1608 if (channel_input_closed(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001609 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001610
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001611 /* if the connection is not estabkished, inform the stream that we want
1612 * to be notified whenever the connection completes.
1613 */
1614 if (!(c->flags & CO_FL_CONNECTED)) {
1615 si_applet_cant_get(si);
1616 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001617 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001618 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001619
1620 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001621 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001622
1623 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001624 if (channel_may_recv(si_ic(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001625 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001626
1627 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001628 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001629 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER101b9762018-05-27 01:27:40 +02001630
1631 /* Some data were injected in the buffer, notify the stream
1632 * interface.
1633 */
1634 if (!channel_is_empty(si_ic(si)))
1635 stream_int_update(si);
1636
1637 /* If write notifications are registered, we considers we want
1638 * to write, so we set the flag cant put
1639 */
1640 if (notification_registered(&appctx->ctx.hlua_cosocket.wake_on_write))
1641 si_applet_cant_put(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001642}
1643
Willy Tarreau87b09662015-04-03 00:22:06 +02001644/* This function is called when the "struct stream" is destroyed.
1645 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001646 * Wake all the pending signals.
1647 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001648static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001649{
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001650 struct xref *peer;
1651
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001652 /* Remove my link in the original object. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001653 peer = xref_get_peer_and_lock(&appctx->ctx.hlua_cosocket.xref);
1654 if (peer)
1655 xref_disconnect(&appctx->ctx.hlua_cosocket.xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001656
1657 /* Wake all the task waiting for me. */
Thierry FOURNIERd6975962017-07-12 14:31:10 +02001658 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1659 notification_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001660}
1661
1662/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001663 * uses this object. If the stream does not exists, just quit.
1664 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001665 * pending signal can rest in the read and write lists. destroy
1666 * it.
1667 */
1668__LJMP static int hlua_socket_gc(lua_State *L)
1669{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001670 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001671 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001672 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001673
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001674 MAY_LJMP(check_args(L, 1, "__gc"));
1675
1676 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001677 peer = xref_get_peer_and_lock(&socket->xref);
1678 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001679 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001680 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001681
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001682 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001683 appctx->ctx.hlua_cosocket.die = 1;
1684 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001685
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001686 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001687 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001688 return 0;
1689}
1690
1691/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001692 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001693 */
sada05ed3302018-05-11 11:48:18 -07001694__LJMP static int hlua_socket_close_helper(lua_State *L)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001695{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001696 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001697 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001698 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001699
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001700 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001701
1702 /* Check if we run on the same thread than the xreator thread.
1703 * We cannot access to the socket if the thread is different.
1704 */
1705 if (socket->tid != tid)
1706 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1707
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001708 peer = xref_get_peer_and_lock(&socket->xref);
1709 if (!peer)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001710 return 0;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001711 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001712
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001713 /* Set the flag which destroy the session. */
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02001714 appctx->ctx.hlua_cosocket.die = 1;
1715 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001716
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001717 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001718 xref_disconnect(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001719 return 0;
1720}
1721
sada05ed3302018-05-11 11:48:18 -07001722/* The close function calls close_helper.
1723 */
1724__LJMP static int hlua_socket_close(lua_State *L)
1725{
1726 MAY_LJMP(check_args(L, 1, "close"));
1727 return hlua_socket_close_helper(L);
1728}
1729
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001730/* This Lua function assumes that the stack contain three parameters.
1731 * 1 - USERDATA containing a struct socket
1732 * 2 - INTEGER with values of the macro defined below
1733 * If the integer is -1, we must read at most one line.
1734 * If the integer is -2, we ust read all the data until the
1735 * end of the stream.
1736 * If the integer is positive value, we must read a number of
1737 * bytes corresponding to this value.
1738 */
1739#define HLSR_READ_LINE (-1)
1740#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001741__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001742{
1743 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1744 int wanted = lua_tointeger(L, 2);
1745 struct hlua *hlua = hlua_gethlua(L);
1746 struct appctx *appctx;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001747 size_t len;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001748 int nblk;
Willy Tarreau206ba832018-06-14 15:27:31 +02001749 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001750 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02001751 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02001752 size_t len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001753 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001754 struct channel *oc;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001755 struct stream_interface *si;
1756 struct stream *s;
1757 struct xref *peer;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001758 int missing_bytes;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001759
1760 /* Check if this lua stack is schedulable. */
1761 if (!hlua || !hlua->task)
1762 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1763 "'frontend', 'backend' or 'task'"));
1764
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001765 /* Check if we run on the same thread than the xreator thread.
1766 * We cannot access to the socket if the thread is different.
1767 */
1768 if (socket->tid != tid)
1769 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1770
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001771 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001772 peer = xref_get_peer_and_lock(&socket->xref);
1773 if (!peer)
1774 goto no_peer;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001775 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
1776 si = appctx->owner;
1777 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001778
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001779 oc = &s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001780 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001781 /* Read line. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001782 nblk = co_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001783 if (nblk < 0) /* Connection close. */
1784 goto connection_closed;
1785 if (nblk == 0) /* No data avalaible. */
1786 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001787
1788 /* remove final \r\n. */
1789 if (nblk == 1) {
1790 if (blk1[len1-1] == '\n') {
1791 len1--;
1792 skip_at_end++;
1793 if (blk1[len1-1] == '\r') {
1794 len1--;
1795 skip_at_end++;
1796 }
1797 }
1798 }
1799 else {
1800 if (blk2[len2-1] == '\n') {
1801 len2--;
1802 skip_at_end++;
1803 if (blk2[len2-1] == '\r') {
1804 len2--;
1805 skip_at_end++;
1806 }
1807 }
1808 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001809 }
1810
1811 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001812 /* Read all the available data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001813 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001814 if (nblk < 0) /* Connection close. */
1815 goto connection_closed;
1816 if (nblk == 0) /* No data avalaible. */
1817 goto connection_empty;
1818 }
1819
1820 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001821 /* Read a block of data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001822 nblk = co_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001823 if (nblk < 0) /* Connection close. */
1824 goto connection_closed;
1825 if (nblk == 0) /* No data avalaible. */
1826 goto connection_empty;
1827
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001828 missing_bytes = wanted - socket->b.n;
1829 if (len1 > missing_bytes) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001830 nblk = 1;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001831 len1 = missing_bytes;
1832 } if (nblk == 2 && len1 + len2 > missing_bytes)
1833 len2 = missing_bytes - len1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001834 }
1835
1836 len = len1;
1837
1838 luaL_addlstring(&socket->b, blk1, len1);
1839 if (nblk == 2) {
1840 len += len2;
1841 luaL_addlstring(&socket->b, blk2, len2);
1842 }
1843
1844 /* Consume data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02001845 co_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001846
1847 /* Don't wait anything. */
Thierry FOURNIER7e4ee472018-05-25 15:03:50 +02001848 appctx_wakeup(appctx);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001849
1850 /* If the pattern reclaim to read all the data
1851 * in the connection, got out.
1852 */
1853 if (wanted == HLSR_READ_ALL)
1854 goto connection_empty;
Thierry FOURNIER8c126c72018-05-25 16:27:44 +02001855 else if (wanted >= 0 && socket->b.n < wanted)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001856 goto connection_empty;
1857
1858 /* Return result. */
1859 luaL_pushresult(&socket->b);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001860 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001861 return 1;
1862
1863connection_closed:
1864
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001865 xref_unlock(&socket->xref, peer);
1866
1867no_peer:
1868
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001869 /* If the buffer containds data. */
1870 if (socket->b.n > 0) {
1871 luaL_pushresult(&socket->b);
1872 return 1;
1873 }
1874 lua_pushnil(L);
1875 lua_pushstring(L, "connection closed.");
1876 return 2;
1877
1878connection_empty:
1879
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001880 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task)) {
1881 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001882 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02001883 }
1884 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001885 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001886 return 0;
1887}
1888
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001889/* This Lua function gets two parameters. The first one can be string
1890 * or a number. If the string is "*l", the user requires one line. If
1891 * the string is "*a", the user requires all the contents of the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001892 * If the value is a number, the user require a number of bytes equal
1893 * to the value. The default value is "*l" (a line).
1894 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001895 * This parameter with a variable type is converted in integer. This
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001896 * integer takes this values:
1897 * -1 : read a line
1898 * -2 : read all the stream
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001899 * >0 : amount of bytes.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001900 *
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001901 * The second parameter is optional. It contains a string that must be
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001902 * concatenated with the read data.
1903 */
1904__LJMP static int hlua_socket_receive(struct lua_State *L)
1905{
1906 int wanted = HLSR_READ_LINE;
1907 const char *pattern;
1908 int type;
1909 char *error;
1910 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001911 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001912
1913 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1914 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1915
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001916 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001917
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001918 /* Check if we run on the same thread than the xreator thread.
1919 * We cannot access to the socket if the thread is different.
1920 */
1921 if (socket->tid != tid)
1922 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1923
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001924 /* check for pattern. */
1925 if (lua_gettop(L) >= 2) {
1926 type = lua_type(L, 2);
1927 if (type == LUA_TSTRING) {
1928 pattern = lua_tostring(L, 2);
1929 if (strcmp(pattern, "*a") == 0)
1930 wanted = HLSR_READ_ALL;
1931 else if (strcmp(pattern, "*l") == 0)
1932 wanted = HLSR_READ_LINE;
1933 else {
1934 wanted = strtoll(pattern, &error, 10);
1935 if (*error != '\0')
1936 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1937 }
1938 }
1939 else if (type == LUA_TNUMBER) {
1940 wanted = lua_tointeger(L, 2);
1941 if (wanted < 0)
1942 WILL_LJMP(luaL_error(L, "Unsupported size."));
1943 }
1944 }
1945
1946 /* Set pattern. */
1947 lua_pushinteger(L, wanted);
Tim Duesterhusc6e377e2018-01-04 19:32:13 +01001948
1949 /* Check if we would replace the top by itself. */
1950 if (lua_gettop(L) != 2)
1951 lua_replace(L, 2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001952
Tim Duesterhusb33754c2018-01-04 19:32:14 +01001953 /* init buffer, and fill it with prefix. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001954 luaL_buffinit(L, &socket->b);
1955
1956 /* Check prefix. */
1957 if (lua_gettop(L) >= 3) {
1958 if (lua_type(L, 3) != LUA_TSTRING)
1959 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1960 pattern = lua_tolstring(L, 3, &len);
1961 luaL_addlstring(&socket->b, pattern, len);
1962 }
1963
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001964 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001965}
1966
1967/* Write the Lua input string in the output buffer.
Mark Lakes22154b42018-01-29 14:38:40 -08001968 * This function returns a yield if no space is available.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001969 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001970static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001971{
1972 struct hlua_socket *socket;
1973 struct hlua *hlua = hlua_gethlua(L);
1974 struct appctx *appctx;
1975 size_t buf_len;
1976 const char *buf;
1977 int len;
1978 int send_len;
1979 int sent;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02001980 struct xref *peer;
1981 struct stream_interface *si;
1982 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001983
1984 /* Check if this lua stack is schedulable. */
1985 if (!hlua || !hlua->task)
1986 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1987 "'frontend', 'backend' or 'task'"));
1988
1989 /* Get object */
1990 socket = MAY_LJMP(hlua_checksocket(L, 1));
1991 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001992 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001993
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02001994 /* Check if we run on the same thread than the xreator thread.
1995 * We cannot access to the socket if the thread is different.
1996 */
1997 if (socket->tid != tid)
1998 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
1999
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002000 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002001 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002002 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002003 lua_pushinteger(L, -1);
2004 return 1;
2005 }
2006 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2007 si = appctx->owner;
2008 s = si_strm(si);
2009
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002010 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002011 if (channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002012 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002013 lua_pushinteger(L, -1);
2014 return 1;
2015 }
2016
2017 /* Update the input buffer data. */
2018 buf += sent;
2019 send_len = buf_len - sent;
2020
2021 /* All the data are sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002022 if (sent >= buf_len) {
2023 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002024 return 1; /* Implicitly return the length sent. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002025 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002026
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002027 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2028 * the request buffer if its not required.
2029 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002030 if (s->req.buf.size == 0) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002031 if (!channel_alloc_buffer(&s->req, &appctx->buffer_wait))
Christopher Faulet33834b12016-12-19 09:29:06 +01002032 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01002033 }
2034
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002035 /* Check for avalaible space. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002036 len = b_room(&s->req.buf);
Christopher Faulet33834b12016-12-19 09:29:06 +01002037 if (len <= 0) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002038 goto hlua_socket_write_yield_return;
Christopher Faulet33834b12016-12-19 09:29:06 +01002039 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002040
2041 /* send data */
2042 if (len < send_len)
2043 send_len = len;
Thierry FOURNIER66b89192018-05-27 01:14:47 +02002044 len = ci_putblk(&s->req, buf, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002045
2046 /* "Not enough space" (-1), "Buffer too little to contain
2047 * the data" (-2) are not expected because the available length
2048 * is tested.
2049 * Other unknown error are also not expected.
2050 */
2051 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01002052 if (len == -1)
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002053 s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01002054
sada05ed3302018-05-11 11:48:18 -07002055 MAY_LJMP(hlua_socket_close_helper(L));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002056 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002057 lua_pushinteger(L, -1);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002058 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002059 return 1;
2060 }
2061
2062 /* update buffers. */
Thierry FOURNIER101b9762018-05-27 01:27:40 +02002063 appctx_wakeup(appctx);
Willy Tarreaude70fa12015-09-26 11:25:05 +02002064
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002065 s->req.rex = TICK_ETERNITY;
2066 s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002067
2068 /* Update length sent. */
2069 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002070 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002071
2072 /* All the data buffer is sent ? */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002073 if (sent + len >= buf_len) {
2074 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002075 return 1;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002076 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002077
2078hlua_socket_write_yield_return:
Thierry FOURNIERba42fcd2018-05-27 00:59:48 +02002079 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2080 xref_unlock(&socket->xref, peer);
2081 WILL_LJMP(luaL_error(L, "out of memory"));
2082 }
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002083 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002084 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002085 return 0;
2086}
2087
2088/* This function initiate the send of data. It just check the input
2089 * parameters and push an integer in the Lua stack that contain the
2090 * amount of data writed in the buffer. This is used by the function
2091 * "hlua_socket_write_yield" that can yield.
2092 *
2093 * The Lua function gets between 3 and 4 parameters. The first one is
2094 * the associated object. The second is a string buffer. The third is
2095 * a facultative integer that represents where is the buffer position
2096 * of the start of the data that can send. The first byte is the
2097 * position "1". The default value is "1". The fourth argument is a
2098 * facultative integer that represents where is the buffer position
2099 * of the end of the data that can send. The default is the last byte.
2100 */
2101static int hlua_socket_send(struct lua_State *L)
2102{
2103 int i;
2104 int j;
2105 const char *buf;
2106 size_t buf_len;
2107
2108 /* Check number of arguments. */
2109 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
2110 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
2111
2112 /* Get the string. */
2113 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
2114
2115 /* Get and check j. */
2116 if (lua_gettop(L) == 4) {
2117 j = MAY_LJMP(luaL_checkinteger(L, 4));
2118 if (j < 0)
2119 j = buf_len + j + 1;
2120 if (j > buf_len)
2121 j = buf_len + 1;
2122 lua_pop(L, 1);
2123 }
2124 else
2125 j = buf_len;
2126
2127 /* Get and check i. */
2128 if (lua_gettop(L) == 3) {
2129 i = MAY_LJMP(luaL_checkinteger(L, 3));
2130 if (i < 0)
2131 i = buf_len + i + 1;
2132 if (i > buf_len)
2133 i = buf_len + 1;
2134 lua_pop(L, 1);
2135 } else
2136 i = 1;
2137
2138 /* Check bth i and j. */
2139 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002140 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002141 return 1;
2142 }
2143 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002144 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002145 return 1;
2146 }
2147 if (i == 0)
2148 i = 1;
2149 if (j == 0)
2150 j = 1;
2151
2152 /* Pop the string. */
2153 lua_pop(L, 1);
2154
2155 /* Update the buffer length. */
2156 buf += i - 1;
2157 buf_len = j - i + 1;
2158 lua_pushlstring(L, buf, buf_len);
2159
2160 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002161 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002162
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002163 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002164}
2165
Willy Tarreau22b0a682015-06-17 19:43:49 +02002166#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002167__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2168{
2169 static char buffer[SOCKET_INFO_MAX_LEN];
2170 int ret;
2171 int len;
2172 char *p;
2173
2174 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2175 if (ret <= 0) {
2176 lua_pushnil(L);
2177 return 1;
2178 }
2179
2180 if (ret == AF_UNIX) {
2181 lua_pushstring(L, buffer+1);
2182 return 1;
2183 }
2184 else if (ret == AF_INET6) {
2185 buffer[0] = '[';
2186 len = strlen(buffer);
2187 buffer[len] = ']';
2188 len++;
2189 buffer[len] = ':';
2190 len++;
2191 p = buffer;
2192 }
2193 else if (ret == AF_INET) {
2194 p = buffer + 1;
2195 len = strlen(p);
2196 p[len] = ':';
2197 len++;
2198 }
2199 else {
2200 lua_pushnil(L);
2201 return 1;
2202 }
2203
2204 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2205 lua_pushnil(L);
2206 return 1;
2207 }
2208
2209 lua_pushstring(L, p);
2210 return 1;
2211}
2212
2213/* Returns information about the peer of the connection. */
2214__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2215{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002216 struct hlua_socket *socket;
2217 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002218 struct xref *peer;
2219 struct appctx *appctx;
2220 struct stream_interface *si;
2221 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002222 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002223
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224 MAY_LJMP(check_args(L, 1, "getpeername"));
2225
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002226 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002227
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002228 /* Check if we run on the same thread than the xreator thread.
2229 * We cannot access to the socket if the thread is different.
2230 */
2231 if (socket->tid != tid)
2232 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2233
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002234 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002235 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002236 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002237 lua_pushnil(L);
2238 return 1;
2239 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002240 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2241 si = appctx->owner;
2242 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002243
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002244 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002246 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002247 lua_pushnil(L);
2248 return 1;
2249 }
2250
Willy Tarreaua71f6422016-11-16 17:00:14 +01002251 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002252 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002253 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002254 lua_pushnil(L);
2255 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002256 }
2257
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002258 ret = MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2259 xref_unlock(&socket->xref, peer);
2260 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002261}
2262
2263/* Returns information about my connection side. */
2264static int hlua_socket_getsockname(struct lua_State *L)
2265{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002266 struct hlua_socket *socket;
2267 struct connection *conn;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002268 struct appctx *appctx;
2269 struct xref *peer;
2270 struct stream_interface *si;
2271 struct stream *s;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002272 int ret;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002273
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002274 MAY_LJMP(check_args(L, 1, "getsockname"));
2275
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002276 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002277
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002278 /* Check if we run on the same thread than the xreator thread.
2279 * We cannot access to the socket if the thread is different.
2280 */
2281 if (socket->tid != tid)
2282 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2283
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002284 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002285 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002286 if (!peer) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002287 lua_pushnil(L);
2288 return 1;
2289 }
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002290 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2291 si = appctx->owner;
2292 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002293
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002294 conn = cs_conn(objt_cs(s->si[1].end));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002295 if (!conn) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002296 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002297 lua_pushnil(L);
2298 return 1;
2299 }
2300
Willy Tarreaua71f6422016-11-16 17:00:14 +01002301 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002302 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002303 xref_unlock(&socket->xref, peer);
Willy Tarreaua71f6422016-11-16 17:00:14 +01002304 lua_pushnil(L);
2305 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002306 }
2307
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002308 ret = hlua_socket_info(L, &conn->addr.from);
2309 xref_unlock(&socket->xref, peer);
2310 return ret;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311}
2312
2313/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002314static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315 .obj_type = OBJ_TYPE_APPLET,
2316 .name = "<LUA_TCP>",
2317 .fct = hlua_socket_handler,
2318 .release = hlua_socket_release,
2319};
2320
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002321__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002322{
2323 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2324 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002325 struct xref *peer;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002326 struct appctx *appctx;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002327 struct stream_interface *si;
2328 struct stream *s;
2329
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002330 /* Check if we run on the same thread than the xreator thread.
2331 * We cannot access to the socket if the thread is different.
2332 */
2333 if (socket->tid != tid)
2334 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2335
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002336 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002337 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002338 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002339 lua_pushnil(L);
2340 lua_pushstring(L, "Can't connect");
2341 return 2;
2342 }
2343 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2344 si = appctx->owner;
2345 s = si_strm(si);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002346
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002347 /* Check if we run on the same thread than the xreator thread.
2348 * We cannot access to the socket if the thread is different.
2349 */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002350 if (socket->tid != tid) {
2351 xref_unlock(&socket->xref, peer);
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002352 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002353 }
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002354
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002355 /* Check for connection close. */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002356 if (!hlua || channel_output_closed(&s->req)) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002357 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002358 lua_pushnil(L);
2359 lua_pushstring(L, "Can't connect");
2360 return 2;
2361 }
2362
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002363 appctx = objt_appctx(s->si[0].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002364
2365 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002366 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002367 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002368 lua_pushinteger(L, 1);
2369 return 1;
2370 }
2371
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002372 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2373 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002374 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002375 }
2376 xref_unlock(&socket->xref, peer);
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002377 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002378 return 0;
2379}
2380
2381/* This function fail or initite the connection. */
2382__LJMP static int hlua_socket_connect(struct lua_State *L)
2383{
2384 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002385 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002386 const char *ip;
2387 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002388 struct hlua *hlua;
2389 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002390 int low, high;
2391 struct sockaddr_storage *addr;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002392 struct xref *peer;
2393 struct stream_interface *si;
2394 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002395
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002396 if (lua_gettop(L) < 2)
2397 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002398
2399 /* Get args. */
2400 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002401
2402 /* Check if we run on the same thread than the xreator thread.
2403 * We cannot access to the socket if the thread is different.
2404 */
2405 if (socket->tid != tid)
2406 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2407
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002408 ip = MAY_LJMP(luaL_checkstring(L, 2));
Tim Duesterhus6edab862018-01-06 19:04:45 +01002409 if (lua_gettop(L) >= 3) {
2410 luaL_Buffer b;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002411 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002412
Tim Duesterhus6edab862018-01-06 19:04:45 +01002413 /* Force the ip to end with a colon, to support IPv6 addresses
2414 * that are not enclosed within square brackets.
2415 */
2416 if (port > 0) {
2417 luaL_buffinit(L, &b);
2418 luaL_addstring(&b, ip);
2419 luaL_addchar(&b, ':');
2420 luaL_pushresult(&b);
2421 ip = lua_tolstring(L, lua_gettop(L), NULL);
2422 }
2423 }
2424
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002425 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002426 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002427 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002428 lua_pushnil(L);
2429 return 1;
2430 }
2431 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2432 si = appctx->owner;
2433 s = si_strm(si);
2434
2435 /* Initialise connection. */
Olivier Houchard9aaf7782017-09-13 18:30:23 +02002436 conn = cs_conn(si_alloc_cs(&s->si[1], NULL));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002437 if (!conn) {
2438 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002439 WILL_LJMP(luaL_error(L, "connect: internal error"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002440 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002441
Willy Tarreau3adac082015-09-26 17:51:09 +02002442 /* needed for the connection not to be closed */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002443 conn->target = s->target;
Willy Tarreau3adac082015-09-26 17:51:09 +02002444
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002445 /* Parse ip address. */
Willy Tarreau48ef4c92017-01-06 18:32:38 +01002446 addr = str2sa_range(ip, NULL, &low, &high, NULL, NULL, NULL, 0);
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002447 if (!addr) {
2448 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002449 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002450 }
2451 if (low != high) {
2452 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002453 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002454 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002455 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002456
2457 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002458 if (low == 0) {
2459 if (conn->addr.to.ss_family == AF_INET) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002460 if (port == -1) {
2461 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002462 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002463 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002464 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2465 } else if (conn->addr.to.ss_family == AF_INET6) {
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002466 if (port == -1) {
2467 xref_unlock(&socket->xref, peer);
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002468 WILL_LJMP(luaL_error(L, "connect: port missing"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002469 }
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002470 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2471 }
2472 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002473
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002474 hlua = hlua_gethlua(L);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002475 appctx = objt_appctx(s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002476
2477 /* inform the stream that we want to be notified whenever the
2478 * connection completes.
2479 */
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002480 si_applet_cant_get(&s->si[0]);
2481 si_applet_cant_put(&s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002482 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002483
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002484 hlua->flags |= HLUA_MUST_GC;
2485
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002486 if (!notification_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task)) {
2487 xref_unlock(&socket->xref, peer);
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002488 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002489 }
2490 xref_unlock(&socket->xref, peer);
PiBa-NL706d5ee2018-05-05 23:51:42 +02002491
2492 task_wakeup(s->task, TASK_WOKEN_INIT);
2493 /* Return yield waiting for connection. */
2494
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002495 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002496
2497 return 0;
2498}
2499
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002500#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002501__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2502{
2503 struct hlua_socket *socket;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002504 struct xref *peer;
2505 struct appctx *appctx;
2506 struct stream_interface *si;
2507 struct stream *s;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002508
2509 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2510 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002511
2512 /* check for connection break. If some data where read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002513 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002514 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002515 lua_pushnil(L);
2516 return 1;
2517 }
2518 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2519 si = appctx->owner;
2520 s = si_strm(si);
2521
2522 s->target = &socket_ssl.obj_type;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002523 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002524 return MAY_LJMP(hlua_socket_connect(L));
2525}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002526#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002527
2528__LJMP static int hlua_socket_setoption(struct lua_State *L)
2529{
2530 return 0;
2531}
2532
2533__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2534{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002535 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002536 int tmout;
Mark Lakes56cc1252018-03-27 09:48:06 +02002537 double dtmout;
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002538 struct xref *peer;
2539 struct appctx *appctx;
2540 struct stream_interface *si;
2541 struct stream *s;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002542
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002543 MAY_LJMP(check_args(L, 2, "settimeout"));
2544
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002545 socket = MAY_LJMP(hlua_checksocket(L, 1));
Mark Lakes56cc1252018-03-27 09:48:06 +02002546
2547 /* round up for inputs that are fractions and convert to millis */
2548 dtmout = (0.5 + MAY_LJMP(luaL_checknumber(L, 2))) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002549
Thierry Fournier17a921b2018-03-08 09:59:02 +01002550 /* Check for negative values */
Mark Lakes56cc1252018-03-27 09:48:06 +02002551 if (dtmout < 0)
Thierry Fournier17a921b2018-03-08 09:59:02 +01002552 WILL_LJMP(luaL_error(L, "settimeout: cannot set negatives values"));
2553
Mark Lakes56cc1252018-03-27 09:48:06 +02002554 if (dtmout > INT_MAX) /* overflow check */
2555 WILL_LJMP(luaL_error(L, "settimeout: cannot set values larger than %d", INT_MAX));
2556
2557 tmout = MS_TO_TICKS((int)dtmout);
2558
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002559 /* Check if we run on the same thread than the xreator thread.
2560 * We cannot access to the socket if the thread is different.
2561 */
2562 if (socket->tid != tid)
2563 WILL_LJMP(luaL_error(L, "connect: cannot use socket on other thread"));
2564
Mark Lakes56cc1252018-03-27 09:48:06 +02002565 /* check for connection break. If some data were read, return it. */
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002566 peer = xref_get_peer_and_lock(&socket->xref);
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002567 if (!peer) {
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002568 hlua_pusherror(L, "socket: not yet initialised, you can't set timeouts.");
2569 WILL_LJMP(lua_error(L));
2570 return 0;
2571 }
2572 appctx = container_of(peer, struct appctx, ctx.hlua_cosocket.xref);
2573 si = appctx->owner;
2574 s = si_strm(si);
2575
2576 s->req.rto = tmout;
2577 s->req.wto = tmout;
2578 s->res.rto = tmout;
2579 s->res.wto = tmout;
Thierry FOURNIER952939d2017-09-01 14:17:32 +02002580 xref_unlock(&socket->xref, peer);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002581
Thierry Fourniere9636f12018-03-08 09:54:32 +01002582 lua_pushinteger(L, 1);
Tim Duesterhus119a5f12018-01-06 19:16:25 +01002583 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002584}
2585
2586__LJMP static int hlua_socket_new(lua_State *L)
2587{
2588 struct hlua_socket *socket;
2589 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002590 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002591 struct stream *strm;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002592
2593 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002594 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002595 hlua_pusherror(L, "socket: full stack");
2596 goto out_fail_conf;
2597 }
2598
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002599 /* Create the object: obj[0] = userdata. */
2600 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002601 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002602 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002603 memset(socket, 0, sizeof(*socket));
Thierry FOURNIER94a6bfc2017-07-12 12:10:44 +02002604 socket->tid = tid;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002605
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002606 /* Check if the various memory pools are intialized. */
Willy Tarreaubafbe012017-11-24 17:34:44 +01002607 if (!pool_head_stream || !pool_head_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002608 hlua_pusherror(L, "socket: uninitialized pools.");
2609 goto out_fail_conf;
2610 }
2611
Willy Tarreau87b09662015-04-03 00:22:06 +02002612 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002613 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2614 lua_setmetatable(L, -2);
2615
Willy Tarreaud420a972015-04-06 00:39:18 +02002616 /* Create the applet context */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01002617 appctx = appctx_new(&update_applet, tid_bit);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002618 if (!appctx) {
2619 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002620 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002621 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002622
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002623 appctx->ctx.hlua_cosocket.connected = 0;
Thierry FOURNIERb13b20a2017-07-16 20:48:54 +02002624 appctx->ctx.hlua_cosocket.die = 0;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002625 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2626 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002627
Willy Tarreaud420a972015-04-06 00:39:18 +02002628 /* Now create a session, task and stream for this applet */
2629 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2630 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002631 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002632 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002633 }
2634
Willy Tarreau87787ac2017-08-28 16:22:54 +02002635 strm = stream_new(sess, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002636 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002637 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002638 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002639 }
2640
Thierry FOURNIER2da788e2017-09-11 18:37:23 +02002641 /* Initialise cross reference between stream and Lua socket object. */
2642 xref_create(&socket->xref, &appctx->ctx.hlua_cosocket.xref);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002643
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002644 /* Configure "right" stream interface. this "si" is used to connect
2645 * and retrieve data from the server. The connection is initialized
2646 * with the "struct server".
2647 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002648 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002649
2650 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002651 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2652 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002653
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002654 return 1;
2655
Willy Tarreaud420a972015-04-06 00:39:18 +02002656 out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002657 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002658 out_fail_sess:
2659 appctx_free(appctx);
2660 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002661 WILL_LJMP(lua_error(L));
2662 return 0;
2663}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002664
2665/*
2666 *
2667 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002668 * Class Channel
2669 *
2670 *
2671 */
2672
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002673/* The state between the channel data and the HTTP parser state can be
2674 * unconsistent, so reset the parser and call it again. Warning, this
2675 * action not revalidate the request and not send a 400 if the modified
2676 * resuest is not valid.
2677 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002678 * This function never fails. The direction is set using dir, which equals
2679 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002680 */
2681static void hlua_resynchonize_proto(struct stream *stream, int dir)
2682{
2683 /* Protocol HTTP. */
2684 if (stream->be->mode == PR_MODE_HTTP) {
2685
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002686 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002687 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002688 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002689 http_txn_reset_res(stream->txn);
2690
2691 if (stream->txn->hdr_idx.v)
2692 hdr_idx_init(&stream->txn->hdr_idx);
2693
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002694 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002695 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002696 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002697 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2698 }
2699}
2700
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002701/* This function is called before the Lua execution. It stores
2702 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002703 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002704static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002705{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002706 c->mode = stream->be->mode;
2707 switch (c->mode) {
2708 case PR_MODE_HTTP:
2709 c->data.http.dir = opt & SMP_OPT_DIR;
2710 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2711 c->data.http.state = stream->txn->req.msg_state;
2712 else
2713 c->data.http.state = stream->txn->rsp.msg_state;
2714 break;
2715 default:
2716 break;
2717 }
2718}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002719
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002720/* This function is called after the Lua execution. it
2721 * returns true if the parser state is consistent, otherwise,
2722 * it return false.
2723 *
2724 * In HTTP mode, the parser state must be in the same state
2725 * or greater when we exit the function. Even if we do a
2726 * control yield. This prevent to break the HTTP message
2727 * from the Lua code.
2728 */
2729static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2730{
2731 if (c->mode != stream->be->mode)
2732 return 0;
2733
2734 switch (c->mode) {
2735 case PR_MODE_HTTP:
2736 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002737 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002738 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2739 return stream->txn->req.msg_state >= c->data.http.state;
2740 else
2741 return stream->txn->rsp.msg_state >= c->data.http.state;
2742 default:
2743 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002744 }
2745 return 1;
2746}
2747
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002748/* Returns the struct hlua_channel join to the class channel in the
2749 * stack entry "ud" or throws an argument error.
2750 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002751__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002752{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002753 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002754}
2755
Willy Tarreau47860ed2015-03-10 14:07:50 +01002756/* Pushes the channel onto the top of the stack. If the stask does not have a
2757 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002758 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002759static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002760{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002761 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002762 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002763 return 0;
2764
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002765 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002766 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002767 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002768
2769 /* Pop a class sesison metatable and affect it to the userdata. */
2770 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2771 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002772 return 1;
2773}
2774
2775/* Duplicate all the data present in the input channel and put it
2776 * in a string LUA variables. Returns -1 and push a nil value in
2777 * the stack if the channel is closed and all the data are consumed,
2778 * returns 0 if no data are available, otherwise it returns the length
2779 * of the builded string.
2780 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002781static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002782{
2783 char *blk1;
2784 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002785 size_t len1;
2786 size_t len2;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002787 int ret;
2788 luaL_Buffer b;
2789
Willy Tarreau06d80a92017-10-19 14:32:15 +02002790 ret = ci_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002791 if (unlikely(ret == 0))
2792 return 0;
2793
2794 if (unlikely(ret < 0)) {
2795 lua_pushnil(L);
2796 return -1;
2797 }
2798
2799 luaL_buffinit(L, &b);
2800 luaL_addlstring(&b, blk1, len1);
2801 if (unlikely(ret == 2))
2802 luaL_addlstring(&b, blk2, len2);
2803 luaL_pushresult(&b);
2804
2805 if (unlikely(ret == 2))
2806 return len1 + len2;
2807 return len1;
2808}
2809
2810/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2811 * a yield. This function keep the data in the buffer.
2812 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002813__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002814{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002815 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002816
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002817 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2818
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002819 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002820 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002821 return 1;
2822}
2823
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002824/* Check arguments for the function "hlua_channel_dup_yield". */
2825__LJMP static int hlua_channel_dup(lua_State *L)
2826{
2827 MAY_LJMP(check_args(L, 1, "dup"));
2828 MAY_LJMP(hlua_checkchannel(L, 1));
2829 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2830}
2831
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002832/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2833 * a yield. This function consumes the data in the buffer. It returns
2834 * a string containing the data or a nil pointer if no data are available
2835 * and the channel is closed.
2836 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002837__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002838{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002839 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002840 int ret;
2841
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002842 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002843
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002844 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002845 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002846 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002847
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002848 if (unlikely(ret == -1))
2849 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002850
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002851 b_sub(&chn->buf, ret);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002852 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002853 return 1;
2854}
2855
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002856/* Check arguments for the fucntion "hlua_channel_get_yield". */
2857__LJMP static int hlua_channel_get(lua_State *L)
2858{
2859 MAY_LJMP(check_args(L, 1, "get"));
2860 MAY_LJMP(hlua_checkchannel(L, 1));
2861 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2862}
2863
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002864/* This functions consumes and returns one line. If the channel is closed,
2865 * and the last data does not contains a final '\n', the data are returned
2866 * without the final '\n'. When no more data are avalaible, it returns nil
2867 * value.
2868 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002869__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002870{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002871 char *blk1;
2872 char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02002873 size_t len1;
2874 size_t len2;
2875 size_t len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002876 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002877 int ret;
2878 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002879
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002880 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2881
Willy Tarreau06d80a92017-10-19 14:32:15 +02002882 ret = ci_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002883 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002884 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002885
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002886 if (ret == -1) {
2887 lua_pushnil(L);
2888 return 1;
2889 }
2890
2891 luaL_buffinit(L, &b);
2892 luaL_addlstring(&b, blk1, len1);
2893 len = len1;
2894 if (unlikely(ret == 2)) {
2895 luaL_addlstring(&b, blk2, len2);
2896 len += len2;
2897 }
2898 luaL_pushresult(&b);
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002899 b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn) + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002900 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002901 return 1;
2902}
2903
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002904/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2905__LJMP static int hlua_channel_getline(lua_State *L)
2906{
2907 MAY_LJMP(check_args(L, 1, "getline"));
2908 MAY_LJMP(hlua_checkchannel(L, 1));
2909 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2910}
2911
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002912/* This function takes a string as input, and append it at the
2913 * input side of channel. If the data is too big, but a space
2914 * is probably available after sending some data, the function
2915 * yield. If the data is bigger than the buffer, or if the
2916 * channel is closed, it returns -1. otherwise, it returns the
2917 * amount of data writed.
2918 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002919__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002920{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002921 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002922 size_t len;
2923 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2924 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2925 int ret;
2926 int max;
2927
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002928 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2929 * the request buffer if its not required.
2930 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002931 if (chn->buf.size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002932 si_applet_cant_put(chn_prod(chn));
2933 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2934 }
2935
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002936 max = channel_recv_limit(chn) - b_data(&chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002937 if (max > len - l)
2938 max = len - l;
2939
Willy Tarreau06d80a92017-10-19 14:32:15 +02002940 ret = ci_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002941 if (ret == -2 || ret == -3) {
2942 lua_pushinteger(L, -1);
2943 return 1;
2944 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002945 if (ret == -1) {
2946 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002947 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002948 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002949 l += ret;
2950 lua_pop(L, 1);
2951 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002952 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002953
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002954 max = channel_recv_limit(chn) - b_data(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02002955 if (max == 0 && co_data(chn) == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002956 /* There are no space avalaible, and the output buffer is empty.
2957 * in this case, we cannot add more data, so we cannot yield,
2958 * we return the amount of copyied data.
2959 */
2960 return 1;
2961 }
2962 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002963 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002964 return 1;
2965}
2966
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002967/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002968 * of the writed string, or -1 if the channel is closed or if the
2969 * buffer size is too little for the data.
2970 */
2971__LJMP static int hlua_channel_append(lua_State *L)
2972{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002973 size_t len;
2974
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002975 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002976 MAY_LJMP(hlua_checkchannel(L, 1));
2977 MAY_LJMP(luaL_checklstring(L, 2, &len));
2978 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002979 lua_pushinteger(L, 0);
2980
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002981 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002982}
2983
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002984/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002985 * his process by cleaning the buffer. The result is a replacement
2986 * of the current data. It returns the length of the writed string,
2987 * or -1 if the channel is closed or if the buffer size is too
2988 * little for the data.
2989 */
2990__LJMP static int hlua_channel_set(lua_State *L)
2991{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002992 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002993
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002994 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002995 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002996 lua_pushinteger(L, 0);
2997
Willy Tarreauc9fa0482018-07-10 17:43:27 +02002998 b_set_data(&chn->buf, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002999
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003000 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003001}
3002
3003/* Append data in the output side of the buffer. This data is immediatly
3004 * sent. The fcuntion returns the ammount of data writed. If the buffer
3005 * cannot contains the data, the function yield. The function returns -1
3006 * if the channel is closed.
3007 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003008__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003009{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003010 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003011 size_t len;
3012 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3013 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3014 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003015 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003016
Willy Tarreau47860ed2015-03-10 14:07:50 +01003017 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003018 lua_pushinteger(L, -1);
3019 return 1;
3020 }
3021
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003022 /* Check if the buffer is avalaible because HAProxy doesn't allocate
3023 * the request buffer if its not required.
3024 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003025 if (chn->buf.size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01003026 si_applet_cant_put(chn_prod(chn));
3027 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01003028 }
3029
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003030 /* the writed data will be immediatly sent, so we can check
3031 * the avalaible space without taking in account the reserve.
3032 * The reserve is guaranted for the processing of incoming
3033 * data, because the buffer will be flushed.
3034 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003035 max = b_room(&chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003036
3037 /* If there are no space avalaible, and the output buffer is empty.
3038 * in this case, we cannot add more data, so we cannot yield,
3039 * we return the amount of copyied data.
3040 */
Willy Tarreaua79021a2018-06-15 18:07:57 +02003041 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003042 return 1;
3043
3044 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003045 if (max > len - l)
3046 max = len - l;
3047
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003048 /* The buffer avalaible size may be not contiguous. This test
3049 * detects a non contiguous buffer and realign it.
3050 */
Willy Tarreau3f679992018-06-15 15:06:42 +02003051 if (ci_space_for_replace(chn) < max)
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003052 channel_slow_realign(chn, trash.area);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003053
3054 /* Copy input data in the buffer. */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003055 max = b_rep_blk(&chn->buf, ci_head(chn), ci_head(chn), str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003056
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003057 /* buffer replace considers that the input part is filled.
3058 * so, I must forward these new data in the output part.
3059 */
Willy Tarreaubcbd3932018-06-06 07:13:22 +02003060 c_adv(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003061
3062 l += max;
3063 lua_pop(L, 1);
3064 lua_pushinteger(L, l);
3065
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003066 /* If there are no space avalaible, and the output buffer is empty.
3067 * in this case, we cannot add more data, so we cannot yield,
3068 * we return the amount of copyied data.
3069 */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003070 max = b_room(&chn->buf);
Willy Tarreaua79021a2018-06-15 18:07:57 +02003071 if (max == 0 && co_data(chn) == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003072 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01003073
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003074 if (l < len) {
3075 /* If we are waiting for space in the response buffer, we
3076 * must set the flag WAKERESWR. This flag required the task
3077 * wake up if any activity is detected on the response buffer.
3078 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003079 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003080 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003081 else
3082 HLUA_SET_WAKEREQWR(hlua);
3083 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003084 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003085
3086 return 1;
3087}
3088
3089/* Just a wraper of "_hlua_channel_send". This wrapper permits
3090 * yield the LUA process, and resume it without checking the
3091 * input arguments.
3092 */
3093__LJMP static int hlua_channel_send(lua_State *L)
3094{
3095 MAY_LJMP(check_args(L, 2, "send"));
3096 lua_pushinteger(L, 0);
3097
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003098 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003099}
3100
3101/* This function forward and amount of butes. The data pass from
3102 * the input side of the buffer to the output side, and can be
3103 * forwarded. This function never fails.
3104 *
3105 * The Lua function takes an amount of bytes to be forwarded in
3106 * imput. It returns the number of bytes forwarded.
3107 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003108__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003109{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003110 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003111 int len;
3112 int l;
3113 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003114 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003115
3116 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3117 len = MAY_LJMP(luaL_checkinteger(L, 2));
3118 l = MAY_LJMP(luaL_checkinteger(L, -1));
3119
3120 max = len - l;
Willy Tarreaua79021a2018-06-15 18:07:57 +02003121 if (max > ci_data(chn))
3122 max = ci_data(chn);
Willy Tarreau47860ed2015-03-10 14:07:50 +01003123 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003124 l += max;
3125
3126 lua_pop(L, 1);
3127 lua_pushinteger(L, l);
3128
3129 /* Check if it miss bytes to forward. */
3130 if (l < len) {
3131 /* The the input channel or the output channel are closed, we
3132 * must return the amount of data forwarded.
3133 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003134 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003135 return 1;
3136
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003137 /* If we are waiting for space data in the response buffer, we
3138 * must set the flag WAKERESWR. This flag required the task
3139 * wake up if any activity is detected on the response buffer.
3140 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01003141 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003142 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01003143 else
3144 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01003145
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003146 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01003147 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003148 }
3149
3150 return 1;
3151}
3152
3153/* Just check the input and prepare the stack for the previous
3154 * function "hlua_channel_forward_yield"
3155 */
3156__LJMP static int hlua_channel_forward(lua_State *L)
3157{
3158 MAY_LJMP(check_args(L, 2, "forward"));
3159 MAY_LJMP(hlua_checkchannel(L, 1));
3160 MAY_LJMP(luaL_checkinteger(L, 2));
3161
3162 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003163 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003164}
3165
3166/* Just returns the number of bytes available in the input
3167 * side of the buffer. This function never fails.
3168 */
3169__LJMP static int hlua_channel_get_in_len(lua_State *L)
3170{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003171 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003172
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003173 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003174 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003175 lua_pushinteger(L, ci_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003176 return 1;
3177}
3178
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003179/* Returns true if the channel is full. */
3180__LJMP static int hlua_channel_is_full(lua_State *L)
3181{
3182 struct channel *chn;
3183 int rem;
3184
3185 MAY_LJMP(check_args(L, 1, "is_full"));
3186 chn = MAY_LJMP(hlua_checkchannel(L, 1));
3187
Willy Tarreauc9fa0482018-07-10 17:43:27 +02003188 rem = b_room(&chn->buf);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01003189 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
3190
3191 lua_pushboolean(L, rem <= 0);
3192 return 1;
3193}
3194
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003195/* Just returns the number of bytes available in the output
3196 * side of the buffer. This function never fails.
3197 */
3198__LJMP static int hlua_channel_get_out_len(lua_State *L)
3199{
Willy Tarreau47860ed2015-03-10 14:07:50 +01003200 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003201
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003202 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003203 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreaua79021a2018-06-15 18:07:57 +02003204 lua_pushinteger(L, co_data(chn));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003205 return 1;
3206}
3207
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003208/*
3209 *
3210 *
3211 * Class Fetches
3212 *
3213 *
3214 */
3215
3216/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003217 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003218 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003219__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003220{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003221 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003222}
3223
3224/* This function creates and push in the stack a fetch object according
3225 * with a current TXN.
3226 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003227static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003228{
Willy Tarreau7073c472015-04-06 11:15:40 +02003229 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003230
3231 /* Check stack size. */
3232 if (!lua_checkstack(L, 3))
3233 return 0;
3234
3235 /* Create the object: obj[0] = userdata.
3236 * Note that the base of the Fetches object is the
3237 * transaction object.
3238 */
3239 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003240 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003241 lua_rawseti(L, -2, 0);
3242
Willy Tarreau7073c472015-04-06 11:15:40 +02003243 hsmp->s = txn->s;
3244 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003245 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003246 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003247
3248 /* Pop a class sesison metatable and affect it to the userdata. */
3249 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
3250 lua_setmetatable(L, -2);
3251
3252 return 1;
3253}
3254
3255/* This function is an LUA binding. It is called with each sample-fetch.
3256 * It uses closure argument to store the associated sample-fetch. It
3257 * returns only one argument or throws an error. An error is thrown
3258 * only if an error is encountered during the argument parsing. If
3259 * the "sample-fetch" function fails, nil is returned.
3260 */
3261__LJMP static int hlua_run_sample_fetch(lua_State *L)
3262{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003263 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01003264 struct sample_fetch *f;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003265 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003266 int i;
3267 struct sample smp;
3268
3269 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003270 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003271
3272 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003273 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003274
Thierry FOURNIERca988662015-12-20 18:43:03 +01003275 /* Check execution authorization. */
3276 if (f->use & SMP_USE_HTTP_ANY &&
3277 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
3278 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
3279 "is not available in Lua services", f->kw);
3280 WILL_LJMP(lua_error(L));
3281 }
3282
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003283 /* Get extra arguments. */
3284 for (i = 0; i < lua_gettop(L) - 1; i++) {
3285 if (i >= ARGM_NBARGS)
3286 break;
3287 hlua_lua2arg(L, i + 2, &args[i]);
3288 }
3289 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003290 args[i].data.str.area = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003291
3292 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003293 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003294
3295 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003296 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003297 lua_pushfstring(L, "error in arguments");
3298 WILL_LJMP(lua_error(L));
3299 }
3300
3301 /* Initialise the sample. */
3302 memset(&smp, 0, sizeof(smp));
3303
3304 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003305 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003306 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003307 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003308 lua_pushstring(L, "");
3309 else
3310 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003311 return 1;
3312 }
3313
3314 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003315 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003316 hlua_smp2lua_str(L, &smp);
3317 else
3318 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003319 return 1;
3320}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003321
3322/*
3323 *
3324 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003325 * Class Converters
3326 *
3327 *
3328 */
3329
3330/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003331 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003332 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003333__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003334{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003335 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003336}
3337
3338/* This function creates and push in the stack a Converters object
3339 * according with a current TXN.
3340 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003341static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003342{
Willy Tarreau7073c472015-04-06 11:15:40 +02003343 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003344
3345 /* Check stack size. */
3346 if (!lua_checkstack(L, 3))
3347 return 0;
3348
3349 /* Create the object: obj[0] = userdata.
3350 * Note that the base of the Converters object is the
3351 * same than the TXN object.
3352 */
3353 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003354 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003355 lua_rawseti(L, -2, 0);
3356
Willy Tarreau7073c472015-04-06 11:15:40 +02003357 hsmp->s = txn->s;
3358 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003359 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003360 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003361
Willy Tarreau87b09662015-04-03 00:22:06 +02003362 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003363 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3364 lua_setmetatable(L, -2);
3365
3366 return 1;
3367}
3368
3369/* This function is an LUA binding. It is called with each converter.
3370 * It uses closure argument to store the associated converter. It
3371 * returns only one argument or throws an error. An error is thrown
3372 * only if an error is encountered during the argument parsing. If
3373 * the converter function function fails, nil is returned.
3374 */
3375__LJMP static int hlua_run_sample_conv(lua_State *L)
3376{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003377 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003378 struct sample_conv *conv;
Frédéric Lécaillef874a832018-06-15 13:56:04 +02003379 struct arg args[ARGM_NBARGS + 1] = {{0}};
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003380 int i;
3381 struct sample smp;
3382
3383 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003384 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003385
3386 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003387 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003388
3389 /* Get extra arguments. */
3390 for (i = 0; i < lua_gettop(L) - 2; i++) {
3391 if (i >= ARGM_NBARGS)
3392 break;
3393 hlua_lua2arg(L, i + 3, &args[i]);
3394 }
3395 args[i].type = ARGT_STOP;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003396 args[i].data.str.area = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003397
3398 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003399 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003400
3401 /* Run the special args checker. */
3402 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3403 hlua_pusherror(L, "error in arguments");
3404 WILL_LJMP(lua_error(L));
3405 }
3406
3407 /* Initialise the sample. */
3408 if (!hlua_lua2smp(L, 2, &smp)) {
3409 hlua_pusherror(L, "error in the input argument");
3410 WILL_LJMP(lua_error(L));
3411 }
3412
Willy Tarreau1777ea62016-03-10 16:15:46 +01003413 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3414
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003415 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003416 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003417 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003418 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003419 WILL_LJMP(lua_error(L));
3420 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003421 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3422 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003423 hlua_pusherror(L, "error during the input argument casting");
3424 WILL_LJMP(lua_error(L));
3425 }
3426
3427 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003428 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003429 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003430 lua_pushstring(L, "");
3431 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003432 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003433 return 1;
3434 }
3435
3436 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003437 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003438 hlua_smp2lua_str(L, &smp);
3439 else
3440 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003441 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003442}
3443
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003444/*
3445 *
3446 *
3447 * Class AppletTCP
3448 *
3449 *
3450 */
3451
3452/* Returns a struct hlua_txn if the stack entry "ud" is
3453 * a class stream, otherwise it throws an error.
3454 */
3455__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3456{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003457 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003458}
3459
3460/* This function creates and push in the stack an Applet object
3461 * according with a current TXN.
3462 */
3463static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3464{
3465 struct hlua_appctx *appctx;
3466 struct stream_interface *si = ctx->owner;
3467 struct stream *s = si_strm(si);
3468 struct proxy *p = s->be;
3469
3470 /* Check stack size. */
3471 if (!lua_checkstack(L, 3))
3472 return 0;
3473
3474 /* Create the object: obj[0] = userdata.
3475 * Note that the base of the Converters object is the
3476 * same than the TXN object.
3477 */
3478 lua_newtable(L);
3479 appctx = lua_newuserdata(L, sizeof(*appctx));
3480 lua_rawseti(L, -2, 0);
3481 appctx->appctx = ctx;
3482 appctx->htxn.s = s;
3483 appctx->htxn.p = p;
3484
3485 /* Create the "f" field that contains a list of fetches. */
3486 lua_pushstring(L, "f");
3487 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3488 return 0;
3489 lua_settable(L, -3);
3490
3491 /* Create the "sf" field that contains a list of stringsafe fetches. */
3492 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003493 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003494 return 0;
3495 lua_settable(L, -3);
3496
3497 /* Create the "c" field that contains a list of converters. */
3498 lua_pushstring(L, "c");
3499 if (!hlua_converters_new(L, &appctx->htxn, 0))
3500 return 0;
3501 lua_settable(L, -3);
3502
3503 /* Create the "sc" field that contains a list of stringsafe converters. */
3504 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003505 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003506 return 0;
3507 lua_settable(L, -3);
3508
3509 /* Pop a class stream metatable and affect it to the table. */
3510 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3511 lua_setmetatable(L, -2);
3512
3513 return 1;
3514}
3515
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003516__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3517{
3518 struct hlua_appctx *appctx;
3519 struct stream *s;
3520 const char *name;
3521 size_t len;
3522 struct sample smp;
3523
3524 MAY_LJMP(check_args(L, 3, "set_var"));
3525
3526 /* It is useles to retrieve the stream, but this function
3527 * runs only in a stream context.
3528 */
3529 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3530 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3531 s = appctx->htxn.s;
3532
3533 /* Converts the third argument in a sample. */
3534 hlua_lua2smp(L, 3, &smp);
3535
3536 /* Store the sample in a variable. */
3537 smp_set_owner(&smp, s->be, s->sess, s, 0);
3538 vars_set_by_name(name, len, &smp);
3539 return 0;
3540}
3541
3542__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3543{
3544 struct hlua_appctx *appctx;
3545 struct stream *s;
3546 const char *name;
3547 size_t len;
3548 struct sample smp;
3549
3550 MAY_LJMP(check_args(L, 2, "unset_var"));
3551
3552 /* It is useles to retrieve the stream, but this function
3553 * runs only in a stream context.
3554 */
3555 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3556 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3557 s = appctx->htxn.s;
3558
3559 /* Unset the variable. */
3560 smp_set_owner(&smp, s->be, s->sess, s, 0);
3561 vars_unset_by_name(name, len, &smp);
3562 return 0;
3563}
3564
3565__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3566{
3567 struct hlua_appctx *appctx;
3568 struct stream *s;
3569 const char *name;
3570 size_t len;
3571 struct sample smp;
3572
3573 MAY_LJMP(check_args(L, 2, "get_var"));
3574
3575 /* It is useles to retrieve the stream, but this function
3576 * runs only in a stream context.
3577 */
3578 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3579 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3580 s = appctx->htxn.s;
3581
3582 smp_set_owner(&smp, s->be, s->sess, s, 0);
3583 if (!vars_get_by_name(name, len, &smp)) {
3584 lua_pushnil(L);
3585 return 1;
3586 }
3587
3588 return hlua_smp2lua(L, &smp);
3589}
3590
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003591__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3592{
3593 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3594 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003595 struct hlua *hlua;
3596
3597 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003598 if (!s->hlua)
3599 return 0;
3600 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003601
3602 MAY_LJMP(check_args(L, 2, "set_priv"));
3603
3604 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02003605 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003606
3607 /* Get and store new value. */
3608 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3609 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3610
3611 return 0;
3612}
3613
3614__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3615{
3616 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3617 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01003618 struct hlua *hlua;
3619
3620 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01003621 if (!s->hlua) {
3622 lua_pushnil(L);
3623 return 1;
3624 }
3625 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003626
3627 /* Push configuration index in the stack. */
3628 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3629
3630 return 1;
3631}
3632
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003633/* If expected data not yet available, it returns a yield. This function
3634 * consumes the data in the buffer. It returns a string containing the
3635 * data. This string can be empty.
3636 */
3637__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3638{
3639 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3640 struct stream_interface *si = appctx->appctx->owner;
3641 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003642 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003643 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003644 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003645 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003646
3647 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003648 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003649
3650 /* Data not yet avalaible. return yield. */
3651 if (ret == 0) {
3652 si_applet_cant_get(si);
3653 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3654 }
3655
3656 /* End of data: commit the total strings and return. */
3657 if (ret < 0) {
3658 luaL_pushresult(&appctx->b);
3659 return 1;
3660 }
3661
3662 /* Ensure that the block 2 length is usable. */
3663 if (ret == 1)
3664 len2 = 0;
3665
3666 /* dont check the max length read and dont check. */
3667 luaL_addlstring(&appctx->b, blk1, len1);
3668 luaL_addlstring(&appctx->b, blk2, len2);
3669
3670 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003671 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003672 luaL_pushresult(&appctx->b);
3673 return 1;
3674}
3675
3676/* Check arguments for the fucntion "hlua_channel_get_yield". */
3677__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3678{
3679 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3680
3681 /* Initialise the string catenation. */
3682 luaL_buffinit(L, &appctx->b);
3683
3684 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3685}
3686
3687/* If expected data not yet available, it returns a yield. This function
3688 * consumes the data in the buffer. It returns a string containing the
3689 * data. This string can be empty.
3690 */
3691__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3692{
3693 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3694 struct stream_interface *si = appctx->appctx->owner;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003695 size_t len = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003696 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02003697 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003698 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02003699 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02003700 size_t len2;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003701
3702 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003703 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003704
3705 /* Data not yet avalaible. return yield. */
3706 if (ret == 0) {
3707 si_applet_cant_get(si);
3708 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3709 }
3710
3711 /* End of data: commit the total strings and return. */
3712 if (ret < 0) {
3713 luaL_pushresult(&appctx->b);
3714 return 1;
3715 }
3716
3717 /* Ensure that the block 2 length is usable. */
3718 if (ret == 1)
3719 len2 = 0;
3720
3721 if (len == -1) {
3722
3723 /* If len == -1, catenate all the data avalaile and
3724 * yield because we want to get all the data until
3725 * the end of data stream.
3726 */
3727 luaL_addlstring(&appctx->b, blk1, len1);
3728 luaL_addlstring(&appctx->b, blk2, len2);
Willy Tarreau06d80a92017-10-19 14:32:15 +02003729 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003730 si_applet_cant_get(si);
3731 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3732
3733 } else {
3734
3735 /* Copy the fisrt block caping to the length required. */
3736 if (len1 > len)
3737 len1 = len;
3738 luaL_addlstring(&appctx->b, blk1, len1);
3739 len -= len1;
3740
3741 /* Copy the second block. */
3742 if (len2 > len)
3743 len2 = len;
3744 luaL_addlstring(&appctx->b, blk2, len2);
3745 len -= len2;
3746
3747 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003748 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003749
3750 /* If we are no other data avalaible, yield waiting for new data. */
3751 if (len > 0) {
3752 lua_pushinteger(L, len);
3753 lua_replace(L, 2);
3754 si_applet_cant_get(si);
3755 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3756 }
3757
3758 /* return the result. */
3759 luaL_pushresult(&appctx->b);
3760 return 1;
3761 }
3762
3763 /* we never executes this */
3764 hlua_pusherror(L, "Lua: internal error");
3765 WILL_LJMP(lua_error(L));
3766 return 0;
3767}
3768
3769/* Check arguments for the fucntion "hlua_channel_get_yield". */
3770__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3771{
3772 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3773 int len = -1;
3774
3775 if (lua_gettop(L) > 2)
3776 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3777 if (lua_gettop(L) >= 2) {
3778 len = MAY_LJMP(luaL_checkinteger(L, 2));
3779 lua_pop(L, 1);
3780 }
3781
3782 /* Confirm or set the required length */
3783 lua_pushinteger(L, len);
3784
3785 /* Initialise the string catenation. */
3786 luaL_buffinit(L, &appctx->b);
3787
3788 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3789}
3790
3791/* Append data in the output side of the buffer. This data is immediatly
3792 * sent. The fcuntion returns the ammount of data writed. If the buffer
3793 * cannot contains the data, the function yield. The function returns -1
3794 * if the channel is closed.
3795 */
3796__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3797{
3798 size_t len;
3799 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3800 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3801 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3802 struct stream_interface *si = appctx->appctx->owner;
3803 struct channel *chn = si_ic(si);
3804 int max;
3805
3806 /* Get the max amount of data which can write as input in the channel. */
3807 max = channel_recv_max(chn);
3808 if (max > (len - l))
3809 max = len - l;
3810
3811 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02003812 ci_putblk(chn, str + l, max);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003813
3814 /* update counters. */
3815 l += max;
3816 lua_pop(L, 1);
3817 lua_pushinteger(L, l);
3818
3819 /* If some data is not send, declares the situation to the
3820 * applet, and returns a yield.
3821 */
3822 if (l < len) {
3823 si_applet_cant_put(si);
3824 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3825 }
3826
3827 return 1;
3828}
3829
3830/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3831 * yield the LUA process, and resume it without checking the
3832 * input arguments.
3833 */
3834__LJMP static int hlua_applet_tcp_send(lua_State *L)
3835{
3836 MAY_LJMP(check_args(L, 2, "send"));
3837 lua_pushinteger(L, 0);
3838
3839 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3840}
3841
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003842/*
3843 *
3844 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003845 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003846 *
3847 *
3848 */
3849
3850/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003851 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003852 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003853__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003854{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003855 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003856}
3857
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003858/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003859 * according with a current TXN.
3860 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003861static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003862{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003863 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003864 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003865 struct stream_interface *si = ctx->owner;
3866 struct stream *s = si_strm(si);
3867 struct proxy *px = s->be;
3868 struct http_txn *txn = s->txn;
3869 const char *path;
3870 const char *end;
3871 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003872
3873 /* Check stack size. */
3874 if (!lua_checkstack(L, 3))
3875 return 0;
3876
3877 /* Create the object: obj[0] = userdata.
3878 * Note that the base of the Converters object is the
3879 * same than the TXN object.
3880 */
3881 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003882 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003883 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003884 appctx->appctx = ctx;
3885 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
Robin H. Johnson52f5db22017-01-01 13:10:52 -08003886 appctx->appctx->ctx.hlua_apphttp.reason = NULL; /* Use default reason based on status */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003887 appctx->htxn.s = s;
3888 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003889
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003890 /* Create the "f" field that contains a list of fetches. */
3891 lua_pushstring(L, "f");
3892 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3893 return 0;
3894 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003895
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003896 /* Create the "sf" field that contains a list of stringsafe fetches. */
3897 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003898 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003899 return 0;
3900 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003901
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003902 /* Create the "c" field that contains a list of converters. */
3903 lua_pushstring(L, "c");
3904 if (!hlua_converters_new(L, &appctx->htxn, 0))
3905 return 0;
3906 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003907
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003908 /* Create the "sc" field that contains a list of stringsafe converters. */
3909 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003910 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003911 return 0;
3912 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003913
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003914 /* Stores the request method. */
3915 lua_pushstring(L, "method");
Willy Tarreaua79021a2018-06-15 18:07:57 +02003916 lua_pushlstring(L, ci_head(txn->req.chn), txn->req.sl.rq.m_l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003917 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003918
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003919 /* Stores the http version. */
3920 lua_pushstring(L, "version");
Willy Tarreaua79021a2018-06-15 18:07:57 +02003921 lua_pushlstring(L, ci_head(txn->req.chn) + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003922 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003923
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003924 /* creates an array of headers. hlua_http_get_headers() crates and push
3925 * the array on the top of the stack.
3926 */
3927 lua_pushstring(L, "headers");
3928 htxn.s = s;
3929 htxn.p = px;
3930 htxn.dir = SMP_OPT_DIR_REQ;
3931 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3932 return 0;
3933 lua_settable(L, -3);
3934
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003935 /* Get path and qs */
3936 path = http_get_path(txn);
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003937 if (path) {
Willy Tarreaua79021a2018-06-15 18:07:57 +02003938 end = ci_head(txn->req.chn) + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003939 p = path;
3940 while (p < end && *p != '?')
3941 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003942
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003943 /* Stores the request path. */
3944 lua_pushstring(L, "path");
3945 lua_pushlstring(L, path, p - path);
3946 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003947
Thierry FOURNIER7d388632017-02-22 02:06:16 +01003948 /* Stores the query string. */
3949 lua_pushstring(L, "qs");
3950 if (*p == '?')
3951 p++;
3952 lua_pushlstring(L, p, end - p);
3953 lua_settable(L, -3);
3954 }
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003955
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003956 /* Stores the request path. */
3957 lua_pushstring(L, "length");
3958 lua_pushinteger(L, txn->req.body_len);
3959 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003960
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003961 /* Create an array of HTTP request headers. */
3962 lua_pushstring(L, "headers");
3963 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3964 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003965
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003966 /* Create an empty array of HTTP request headers. */
3967 lua_pushstring(L, "response");
3968 lua_newtable(L);
3969 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003970
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003971 /* Pop a class stream metatable and affect it to the table. */
3972 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3973 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003974
3975 return 1;
3976}
3977
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003978__LJMP static int hlua_applet_http_set_var(lua_State *L)
3979{
3980 struct hlua_appctx *appctx;
3981 struct stream *s;
3982 const char *name;
3983 size_t len;
3984 struct sample smp;
3985
3986 MAY_LJMP(check_args(L, 3, "set_var"));
3987
3988 /* It is useles to retrieve the stream, but this function
3989 * runs only in a stream context.
3990 */
3991 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3992 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3993 s = appctx->htxn.s;
3994
3995 /* Converts the third argument in a sample. */
3996 hlua_lua2smp(L, 3, &smp);
3997
3998 /* Store the sample in a variable. */
3999 smp_set_owner(&smp, s->be, s->sess, s, 0);
4000 vars_set_by_name(name, len, &smp);
4001 return 0;
4002}
4003
4004__LJMP static int hlua_applet_http_unset_var(lua_State *L)
4005{
4006 struct hlua_appctx *appctx;
4007 struct stream *s;
4008 const char *name;
4009 size_t len;
4010 struct sample smp;
4011
4012 MAY_LJMP(check_args(L, 2, "unset_var"));
4013
4014 /* It is useles to retrieve the stream, but this function
4015 * runs only in a stream context.
4016 */
4017 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4018 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4019 s = appctx->htxn.s;
4020
4021 /* Unset the variable. */
4022 smp_set_owner(&smp, s->be, s->sess, s, 0);
4023 vars_unset_by_name(name, len, &smp);
4024 return 0;
4025}
4026
4027__LJMP static int hlua_applet_http_get_var(lua_State *L)
4028{
4029 struct hlua_appctx *appctx;
4030 struct stream *s;
4031 const char *name;
4032 size_t len;
4033 struct sample smp;
4034
4035 MAY_LJMP(check_args(L, 2, "get_var"));
4036
4037 /* It is useles to retrieve the stream, but this function
4038 * runs only in a stream context.
4039 */
4040 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4041 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4042 s = appctx->htxn.s;
4043
4044 smp_set_owner(&smp, s->be, s->sess, s, 0);
4045 if (!vars_get_by_name(name, len, &smp)) {
4046 lua_pushnil(L);
4047 return 1;
4048 }
4049
4050 return hlua_smp2lua(L, &smp);
4051}
4052
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004053__LJMP static int hlua_applet_http_set_priv(lua_State *L)
4054{
4055 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4056 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004057 struct hlua *hlua;
4058
4059 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004060 if (!s->hlua)
4061 return 0;
4062 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004063
4064 MAY_LJMP(check_args(L, 2, "set_priv"));
4065
4066 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02004067 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004068
4069 /* Get and store new value. */
4070 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4071 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4072
4073 return 0;
4074}
4075
4076__LJMP static int hlua_applet_http_get_priv(lua_State *L)
4077{
4078 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4079 struct stream *s = appctx->htxn.s;
Thierry FOURNIER3b0a6d42016-12-16 08:48:32 +01004080 struct hlua *hlua;
4081
4082 /* Note that this hlua struct is from the session and not from the applet. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01004083 if (!s->hlua) {
4084 lua_pushnil(L);
4085 return 1;
4086 }
4087 hlua = s->hlua;
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01004088
4089 /* Push configuration index in the stack. */
4090 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4091
4092 return 1;
4093}
4094
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004095/* If expected data not yet available, it returns a yield. This function
4096 * consumes the data in the buffer. It returns a string containing the
4097 * data. This string can be empty.
4098 */
4099__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004100{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004101 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4102 struct stream_interface *si = appctx->appctx->owner;
4103 struct channel *chn = si_ic(si);
4104 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004105 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004106 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004107 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004108 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004109
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004110 /* Maybe we cant send a 100-continue ? */
4111 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004112 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004113 /* if ret == -2 or -3 the channel closed or the message si too
4114 * big for the buffers. We cant send anything. So, we ignoring
4115 * the error, considers that the 100-continue is sent, and try
4116 * to receive.
4117 * If ret is -1, we dont have room in the buffer, so we yield.
4118 */
4119 if (ret == -1) {
4120 si_applet_cant_put(si);
4121 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4122 }
4123 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4124 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004125
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004126 /* Check for the end of the data. */
4127 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
4128 luaL_pushresult(&appctx->b);
4129 return 1;
4130 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004131
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004132 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004133 ret = co_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004134
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004135 /* Data not yet avalaible. return yield. */
4136 if (ret == 0) {
4137 si_applet_cant_get(si);
4138 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
4139 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004140
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004141 /* End of data: commit the total strings and return. */
4142 if (ret < 0) {
4143 luaL_pushresult(&appctx->b);
4144 return 1;
4145 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004146
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004147 /* Ensure that the block 2 length is usable. */
4148 if (ret == 1)
4149 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004150
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004151 /* Copy the fisrt block caping to the length required. */
4152 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4153 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4154 luaL_addlstring(&appctx->b, blk1, len1);
4155 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004156
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004157 /* Copy the second block. */
4158 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4159 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4160 luaL_addlstring(&appctx->b, blk2, len2);
4161 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004162
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004163 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004164 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004165 luaL_pushresult(&appctx->b);
4166 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004167}
4168
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004169/* Check arguments for the fucntion "hlua_channel_get_yield". */
4170__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004171{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004172 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004173
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004174 /* Initialise the string catenation. */
4175 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004176
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004177 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004178}
4179
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004180/* If expected data not yet available, it returns a yield. This function
4181 * consumes the data in the buffer. It returns a string containing the
4182 * data. This string can be empty.
4183 */
4184__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004185{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004186 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4187 struct stream_interface *si = appctx->appctx->owner;
4188 int len = MAY_LJMP(luaL_checkinteger(L, 2));
4189 struct channel *chn = si_ic(si);
4190 int ret;
Willy Tarreau206ba832018-06-14 15:27:31 +02004191 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004192 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02004193 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02004194 size_t len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004195
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004196 /* Maybe we cant send a 100-continue ? */
4197 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
Willy Tarreau06d80a92017-10-19 14:32:15 +02004198 ret = ci_putblk(chn, HTTP_100C, strlen(HTTP_100C));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004199 /* if ret == -2 or -3 the channel closed or the message si too
4200 * big for the buffers. We cant send anything. So, we ignoring
4201 * the error, considers that the 100-continue is sent, and try
4202 * to receive.
4203 * If ret is -1, we dont have room in the buffer, so we yield.
4204 */
4205 if (ret == -1) {
4206 si_applet_cant_put(si);
4207 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4208 }
4209 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
4210 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004211
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004212 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004213 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004214
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004215 /* Data not yet avalaible. return yield. */
4216 if (ret == 0) {
4217 si_applet_cant_get(si);
4218 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4219 }
4220
4221 /* End of data: commit the total strings and return. */
4222 if (ret < 0) {
4223 luaL_pushresult(&appctx->b);
4224 return 1;
4225 }
4226
4227 /* Ensure that the block 2 length is usable. */
4228 if (ret == 1)
4229 len2 = 0;
4230
4231 /* Copy the fisrt block caping to the length required. */
4232 if (len1 > len)
4233 len1 = len;
4234 luaL_addlstring(&appctx->b, blk1, len1);
4235 len -= len1;
4236
4237 /* Copy the second block. */
4238 if (len2 > len)
4239 len2 = len;
4240 luaL_addlstring(&appctx->b, blk2, len2);
4241 len -= len2;
4242
4243 /* Consume input channel output buffer data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004244 co_skip(si_oc(si), len1 + len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004245 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
4246 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
4247
4248 /* If we are no other data avalaible, yield waiting for new data. */
4249 if (len > 0) {
4250 lua_pushinteger(L, len);
4251 lua_replace(L, 2);
4252 si_applet_cant_get(si);
4253 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
4254 }
4255
4256 /* return the result. */
4257 luaL_pushresult(&appctx->b);
4258 return 1;
4259}
4260
4261/* Check arguments for the fucntion "hlua_channel_get_yield". */
4262__LJMP static int hlua_applet_http_recv(lua_State *L)
4263{
4264 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4265 int len = -1;
4266
4267 /* Check arguments. */
4268 if (lua_gettop(L) > 2)
4269 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
4270 if (lua_gettop(L) >= 2) {
4271 len = MAY_LJMP(luaL_checkinteger(L, 2));
4272 lua_pop(L, 1);
4273 }
4274
4275 /* Check the required length */
4276 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
4277 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
4278 lua_pushinteger(L, len);
4279
4280 /* Initialise the string catenation. */
4281 luaL_buffinit(L, &appctx->b);
4282
4283 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
4284}
4285
4286/* Append data in the output side of the buffer. This data is immediatly
4287 * sent. The fcuntion returns the ammount of data writed. If the buffer
4288 * cannot contains the data, the function yield. The function returns -1
4289 * if the channel is closed.
4290 */
4291__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
4292{
4293 size_t len;
4294 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4295 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
4296 int l = MAY_LJMP(luaL_checkinteger(L, 3));
4297 struct stream_interface *si = appctx->appctx->owner;
4298 struct channel *chn = si_ic(si);
4299 int max;
4300
4301 /* Get the max amount of data which can write as input in the channel. */
4302 max = channel_recv_max(chn);
4303 if (max > (len - l))
4304 max = len - l;
4305
4306 /* Copy data. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004307 ci_putblk(chn, str + l, max);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004308
4309 /* update counters. */
4310 l += max;
4311 lua_pop(L, 1);
4312 lua_pushinteger(L, l);
4313
4314 /* If some data is not send, declares the situation to the
4315 * applet, and returns a yield.
4316 */
4317 if (l < len) {
4318 si_applet_cant_put(si);
4319 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4320 }
4321
4322 return 1;
4323}
4324
4325/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4326 * yield the LUA process, and resume it without checking the
4327 * input arguments.
4328 */
4329__LJMP static int hlua_applet_http_send(lua_State *L)
4330{
4331 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4332 size_t len;
4333 char hex[10];
4334
4335 MAY_LJMP(luaL_checklstring(L, 2, &len));
4336
4337 /* If transfer encoding chunked is selected, we surround the data
4338 * by chunk data.
4339 */
4340 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4341 snprintf(hex, 9, "%x", (unsigned int)len);
4342 lua_pushfstring(L, "%s\r\n", hex);
4343 lua_insert(L, 2); /* swap the last 2 entries. */
4344 lua_pushstring(L, "\r\n");
4345 lua_concat(L, 3);
4346 }
4347
4348 /* This interger is used for followinf the amount of data sent. */
4349 lua_pushinteger(L, 0);
4350
4351 /* We want to send some data. Headers must be sent. */
4352 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4353 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4354 WILL_LJMP(lua_error(L));
4355 }
4356
4357 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4358}
4359
4360__LJMP static int hlua_applet_http_addheader(lua_State *L)
4361{
4362 const char *name;
4363 int ret;
4364
4365 MAY_LJMP(hlua_checkapplet_http(L, 1));
4366 name = MAY_LJMP(luaL_checkstring(L, 2));
4367 MAY_LJMP(luaL_checkstring(L, 3));
4368
4369 /* Push in the stack the "response" entry. */
4370 ret = lua_getfield(L, 1, "response");
4371 if (ret != LUA_TTABLE) {
4372 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4373 "is expected as an array. %s found", lua_typename(L, ret));
4374 WILL_LJMP(lua_error(L));
4375 }
4376
4377 /* check if the header is already registered if it is not
4378 * the case, register it.
4379 */
4380 ret = lua_getfield(L, -1, name);
4381 if (ret == LUA_TNIL) {
4382
4383 /* Entry not found. */
4384 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4385
4386 /* Insert the new header name in the array in the top of the stack.
4387 * It left the new array in the top of the stack.
4388 */
4389 lua_newtable(L);
4390 lua_pushvalue(L, 2);
4391 lua_pushvalue(L, -2);
4392 lua_settable(L, -4);
4393
4394 } else if (ret != LUA_TTABLE) {
4395
4396 /* corruption error. */
4397 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4398 "is expected as an array. %s found", name, lua_typename(L, ret));
4399 WILL_LJMP(lua_error(L));
4400 }
4401
4402 /* Now the top od thestack is an array of values. We push
4403 * the header value as new entry.
4404 */
4405 lua_pushvalue(L, 3);
4406 ret = lua_rawlen(L, -2);
4407 lua_rawseti(L, -2, ret + 1);
4408 lua_pushboolean(L, 1);
4409 return 1;
4410}
4411
4412__LJMP static int hlua_applet_http_status(lua_State *L)
4413{
4414 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4415 int status = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004416 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004417
4418 if (status < 100 || status > 599) {
4419 lua_pushboolean(L, 0);
4420 return 1;
4421 }
4422
4423 appctx->appctx->ctx.hlua_apphttp.status = status;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004424 appctx->appctx->ctx.hlua_apphttp.reason = reason;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004425 lua_pushboolean(L, 1);
4426 return 1;
4427}
4428
4429/* We will build the status line and the headers of the HTTP response.
4430 * We will try send at once if its not possible, we give back the hand
4431 * waiting for more room.
4432 */
4433__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4434{
4435 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4436 struct stream_interface *si = appctx->appctx->owner;
4437 struct channel *chn = si_ic(si);
4438 int ret;
4439 size_t len;
4440 const char *msg;
4441
4442 /* Get the message as the first argument on the stack. */
4443 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4444
4445 /* Send the message at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02004446 ret = ci_putblk(chn, msg, len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004447
4448 /* if ret == -2 or -3 the channel closed or the message si too
4449 * big for the buffers.
4450 */
4451 if (ret == -2 || ret == -3) {
4452 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4453 WILL_LJMP(lua_error(L));
4454 }
4455
4456 /* If ret is -1, we dont have room in the buffer, so we yield. */
4457 if (ret == -1) {
4458 si_applet_cant_put(si);
4459 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4460 }
4461
4462 /* Headers sent, set the flag. */
4463 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4464 return 0;
4465}
4466
4467__LJMP static int hlua_applet_http_start_response(lua_State *L)
4468{
Willy Tarreau83061a82018-07-13 11:56:34 +02004469 struct buffer *tmp = get_trash_chunk();
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004470 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004471 const char *name;
Willy Tarreaua3294632017-08-23 11:24:47 +02004472 size_t name_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004473 const char *value;
Willy Tarreaua3294632017-08-23 11:24:47 +02004474 size_t value_len;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004475 int id;
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004476 long long hdr_contentlength = -1;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004477 int hdr_chunked = 0;
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004478 const char *reason = appctx->appctx->ctx.hlua_apphttp.reason;
4479
4480 if (reason == NULL)
4481 reason = get_reason(appctx->appctx->ctx.hlua_apphttp.status);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004482
4483 /* Use the same http version than the request. */
4484 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004485 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004486 appctx->appctx->ctx.hlua_apphttp.status,
Robin H. Johnson52f5db22017-01-01 13:10:52 -08004487 reason);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004488
4489 /* Get the array associated to the field "response" in the object AppletHTTP. */
4490 lua_pushvalue(L, 0);
4491 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4492 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4493 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4494 WILL_LJMP(lua_error(L));
4495 }
4496
4497 /* Browse the list of headers. */
4498 lua_pushnil(L);
4499 while(lua_next(L, -2) != 0) {
4500
4501 /* We expect a string as -2. */
4502 if (lua_type(L, -2) != LUA_TSTRING) {
4503 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4504 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4505 lua_typename(L, lua_type(L, -2)));
4506 WILL_LJMP(lua_error(L));
4507 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004508 name = lua_tolstring(L, -2, &name_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004509
4510 /* We expect an array as -1. */
4511 if (lua_type(L, -1) != LUA_TTABLE) {
4512 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4513 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4514 name,
4515 lua_typename(L, lua_type(L, -1)));
4516 WILL_LJMP(lua_error(L));
4517 }
4518
4519 /* Browse the table who is on the top of the stack. */
4520 lua_pushnil(L);
4521 while(lua_next(L, -2) != 0) {
4522
4523 /* We expect a number as -2. */
4524 if (lua_type(L, -2) != LUA_TNUMBER) {
4525 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4526 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4527 name,
4528 lua_typename(L, lua_type(L, -2)));
4529 WILL_LJMP(lua_error(L));
4530 }
4531 id = lua_tointeger(L, -2);
4532
4533 /* We expect a string as -2. */
4534 if (lua_type(L, -1) != LUA_TSTRING) {
4535 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4536 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4537 name, id,
4538 lua_typename(L, lua_type(L, -1)));
4539 WILL_LJMP(lua_error(L));
4540 }
Willy Tarreaua3294632017-08-23 11:24:47 +02004541 value = lua_tolstring(L, -1, &value_len);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004542
4543 /* Catenate a new header. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004544 if (tmp->data + name_len + 2 + value_len + 2 < tmp->size) {
4545 memcpy(tmp->area + tmp->data, name, name_len);
4546 tmp->data += name_len;
4547 tmp->area[tmp->data++] = ':';
4548 tmp->area[tmp->data++] = ' ';
Willy Tarreaua3294632017-08-23 11:24:47 +02004549
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004550 memcpy(tmp->area + tmp->data, value,
4551 value_len);
4552 tmp->data += value_len;
4553 tmp->area[tmp->data++] = '\r';
4554 tmp->area[tmp->data++] = '\n';
Willy Tarreaua3294632017-08-23 11:24:47 +02004555 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004556
4557 /* Protocol checks. */
4558
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004559 /* Copy the header content length. The length conversion
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004560 * is done without control. If it contains a bad value,
4561 * the content-length remains negative so that we can
4562 * switch to either chunked encoding or close.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004563 */
Willy Tarreaua3294632017-08-23 11:24:47 +02004564 if (name_len == 14 && strcasecmp("content-length", name) == 0)
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004565 strl2llrc(value, strlen(value), &hdr_contentlength);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004566
4567 /* Check if the client annouces a transfer-encoding chunked it self. */
Willy Tarreaua3294632017-08-23 11:24:47 +02004568 if (name_len == 17 && value_len == 7 &&
4569 strcasecmp("transfer-encoding", name) == 0 &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004570 strcasecmp("chunked", value) == 0)
4571 hdr_chunked = 1;
4572
4573 /* Remove the array from the stack, and get next element with a remaining string. */
4574 lua_pop(L, 1);
4575 }
4576
4577 /* Remove the array from the stack, and get next element with a remaining string. */
4578 lua_pop(L, 1);
4579 }
4580
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004581 /* If we dont have a content-length set, and the HTTP version is 1.1
4582 * and the status code implies the presence of a message body, we must
4583 * announce a transfer encoding chunked. This is required by haproxy
4584 * for the keepalive compliance. If the applet annouces a transfer-encoding
4585 * chunked itslef, don't do anything.
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004586 */
Willy Tarreauc9f4ea02017-08-23 09:32:06 +02004587 if (hdr_contentlength < 0 && hdr_chunked == 0 &&
Willy Tarreau06c75fe2017-08-23 09:10:38 +02004588 (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11) &&
4589 appctx->appctx->ctx.hlua_apphttp.status >= 200 &&
4590 appctx->appctx->ctx.hlua_apphttp.status != 204 &&
4591 appctx->appctx->ctx.hlua_apphttp.status != 304) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004592 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4593 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4594 }
4595
4596 /* Finalize headers. */
4597 chunk_appendf(tmp, "\r\n");
4598
4599 /* Remove the last entry and the array of headers */
4600 lua_pop(L, 2);
4601
4602 /* Push the headers block. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004603 lua_pushlstring(L, tmp->area, tmp->data);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004604
4605 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4606}
4607
4608/*
4609 *
4610 *
4611 * Class HTTP
4612 *
4613 *
4614 */
4615
4616/* Returns a struct hlua_txn if the stack entry "ud" is
4617 * a class stream, otherwise it throws an error.
4618 */
4619__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4620{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004621 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004622}
4623
4624/* This function creates and push in the stack a HTTP object
4625 * according with a current TXN.
4626 */
4627static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4628{
4629 struct hlua_txn *htxn;
4630
4631 /* Check stack size. */
4632 if (!lua_checkstack(L, 3))
4633 return 0;
4634
4635 /* Create the object: obj[0] = userdata.
4636 * Note that the base of the Converters object is the
4637 * same than the TXN object.
4638 */
4639 lua_newtable(L);
4640 htxn = lua_newuserdata(L, sizeof(*htxn));
4641 lua_rawseti(L, -2, 0);
4642
4643 htxn->s = txn->s;
4644 htxn->p = txn->p;
4645
4646 /* Pop a class stream metatable and affect it to the table. */
4647 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4648 lua_setmetatable(L, -2);
4649
4650 return 1;
4651}
4652
4653/* This function creates ans returns an array of HTTP headers.
4654 * This function does not fails. It is used as wrapper with the
4655 * 2 following functions.
4656 */
4657__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4658{
4659 const char *cur_ptr, *cur_next, *p;
4660 int old_idx, cur_idx;
4661 struct hdr_idx_elem *cur_hdr;
4662 const char *hn, *hv;
4663 int hnl, hvl;
4664 int type;
4665 const char *in;
4666 char *out;
4667 int len;
4668
4669 /* Create the table. */
4670 lua_newtable(L);
4671
4672 if (!htxn->s->txn)
4673 return 1;
4674
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004675 /* Check if a valid response is parsed */
4676 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4677 return 1;
4678
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004679 /* Build array of headers. */
4680 old_idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02004681 cur_next = ci_head(msg->chn) + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004682
4683 while (1) {
4684 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4685 if (!cur_idx)
4686 break;
4687 old_idx = cur_idx;
4688
4689 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4690 cur_ptr = cur_next;
4691 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4692
4693 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4694 * and the next header starts at cur_next. We'll check
4695 * this header in the list as well as against the default
4696 * rule.
4697 */
4698
4699 /* look for ': *'. */
4700 hn = cur_ptr;
4701 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4702 if (p >= cur_ptr+cur_hdr->len)
4703 continue;
4704 hnl = p - hn;
4705 p++;
4706 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4707 p++;
4708 if (p >= cur_ptr+cur_hdr->len)
4709 continue;
4710 hv = p;
4711 hvl = cur_ptr+cur_hdr->len-p;
4712
4713 /* Lowercase the key. Don't check the size of trash, it have
4714 * the size of one buffer and the input data contains in one
4715 * buffer.
4716 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004717 out = trash.area;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004718 for (in=hn; in<hn+hnl; in++, out++)
4719 *out = tolower(*in);
4720 *out = '\0';
4721
4722 /* Check for existing entry:
4723 * assume that the table is on the top of the stack, and
4724 * push the key in the stack, the function lua_gettable()
4725 * perform the lookup.
4726 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004727 lua_pushlstring(L, trash.area, hnl);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004728 lua_gettable(L, -2);
4729 type = lua_type(L, -1);
4730
4731 switch (type) {
4732 case LUA_TNIL:
4733 /* Table not found, create it. */
4734 lua_pop(L, 1); /* remove the nil value. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004735 lua_pushlstring(L, trash.area, hnl); /* push the header name as key. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004736 lua_newtable(L); /* create and push empty table. */
4737 lua_pushlstring(L, hv, hvl); /* push header value. */
4738 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4739 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4740 break;
4741
4742 case LUA_TTABLE:
4743 /* Entry found: push the value in the table. */
4744 len = lua_rawlen(L, -1);
4745 lua_pushlstring(L, hv, hvl); /* push header value. */
4746 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4747 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4748 break;
4749
4750 default:
4751 /* Other cases are errors. */
4752 hlua_pusherror(L, "internal error during the parsing of headers.");
4753 WILL_LJMP(lua_error(L));
4754 }
4755 }
4756
4757 return 1;
4758}
4759
4760__LJMP static int hlua_http_req_get_headers(lua_State *L)
4761{
4762 struct hlua_txn *htxn;
4763
4764 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4765 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4766
4767 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4768}
4769
4770__LJMP static int hlua_http_res_get_headers(lua_State *L)
4771{
4772 struct hlua_txn *htxn;
4773
4774 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4775 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4776
4777 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4778}
4779
4780/* This function replace full header, or just a value in
4781 * the request or in the response. It is a wrapper fir the
4782 * 4 following functions.
4783 */
4784__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4785 struct http_msg *msg, int action)
4786{
4787 size_t name_len;
4788 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4789 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4790 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4791 struct my_regex re;
4792
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004793 /* Check if a valid response is parsed */
4794 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4795 return 0;
4796
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004797 if (!regex_comp(reg, &re, 1, 1, NULL))
4798 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4799
4800 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4801 regex_free(&re);
4802 return 0;
4803}
4804
4805__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4806{
4807 struct hlua_txn *htxn;
4808
4809 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4810 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4811
4812 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4813}
4814
4815__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4816{
4817 struct hlua_txn *htxn;
4818
4819 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4820 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4821
4822 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4823}
4824
4825__LJMP static int hlua_http_req_rep_val(lua_State *L)
4826{
4827 struct hlua_txn *htxn;
4828
4829 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4830 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4831
4832 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4833}
4834
4835__LJMP static int hlua_http_res_rep_val(lua_State *L)
4836{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004837 struct hlua_txn *htxn;
4838
4839 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4840 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4841
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004842 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004843}
4844
4845/* This function deletes all the occurences of an header.
4846 * It is a wrapper for the 2 following functions.
4847 */
4848__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4849{
4850 size_t len;
4851 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4852 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004853 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004854
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004855 /* Check if a valid response is parsed */
4856 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4857 return 0;
4858
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004859 ctx.idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02004860 while (http_find_header2(name, len, ci_head(msg->chn), &txn->hdr_idx, &ctx))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004861 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4862 return 0;
4863}
4864
4865__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4866{
4867 struct hlua_txn *htxn;
4868
4869 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4870 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4871
Willy Tarreaueee5b512015-04-03 23:46:31 +02004872 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004873}
4874
4875__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4876{
4877 struct hlua_txn *htxn;
4878
4879 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4880 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4881
Willy Tarreaueee5b512015-04-03 23:46:31 +02004882 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004883}
4884
4885/* This function adds an header. It is a wrapper used by
4886 * the 2 following functions.
4887 */
4888__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4889{
4890 size_t name_len;
4891 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4892 size_t value_len;
4893 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4894 char *p;
4895
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004896 /* Check if a valid message is parsed */
4897 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4898 return 0;
4899
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004900 /* Check length. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004901 trash.data = value_len + name_len + 2;
4902 if (trash.data > trash.size)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004903 return 0;
4904
4905 /* Creates the header string. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004906 p = trash.area;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004907 memcpy(p, name, name_len);
4908 p += name_len;
4909 *p = ':';
4910 p++;
4911 *p = ' ';
4912 p++;
4913 memcpy(p, value, value_len);
4914
Willy Tarreaueee5b512015-04-03 23:46:31 +02004915 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004916 trash.area, trash.data) != 0);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004917
4918 return 0;
4919}
4920
4921__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4922{
4923 struct hlua_txn *htxn;
4924
4925 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4926 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4927
Willy Tarreaueee5b512015-04-03 23:46:31 +02004928 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004929}
4930
4931__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4932{
4933 struct hlua_txn *htxn;
4934
4935 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4936 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4937
Willy Tarreaueee5b512015-04-03 23:46:31 +02004938 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004939}
4940
4941static int hlua_http_req_set_hdr(lua_State *L)
4942{
4943 struct hlua_txn *htxn;
4944
4945 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4946 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4947
Willy Tarreaueee5b512015-04-03 23:46:31 +02004948 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4949 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004950}
4951
4952static int hlua_http_res_set_hdr(lua_State *L)
4953{
4954 struct hlua_txn *htxn;
4955
4956 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4957 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4958
Willy Tarreaueee5b512015-04-03 23:46:31 +02004959 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4960 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004961}
4962
4963/* This function set the method. */
4964static int hlua_http_req_set_meth(lua_State *L)
4965{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004966 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004967 size_t name_len;
4968 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004969
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004970 /* Check if a valid request is parsed */
4971 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4972 lua_pushboolean(L, 0);
4973 return 1;
4974 }
4975
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004976 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004977 return 1;
4978}
4979
4980/* This function set the method. */
4981static int hlua_http_req_set_path(lua_State *L)
4982{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004983 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004984 size_t name_len;
4985 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004986
4987 /* Check if a valid request is parsed */
4988 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4989 lua_pushboolean(L, 0);
4990 return 1;
4991 }
4992
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004993 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004994 return 1;
4995}
4996
4997/* This function set the query-string. */
4998static int hlua_http_req_set_query(lua_State *L)
4999{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005000 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005001 size_t name_len;
5002 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005003
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005004 /* Check if a valid request is parsed */
5005 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
5006 lua_pushboolean(L, 0);
5007 return 1;
5008 }
5009
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005010 /* Check length. */
5011 if (name_len > trash.size - 1) {
5012 lua_pushboolean(L, 0);
5013 return 1;
5014 }
5015
5016 /* Add the mark question as prefix. */
5017 chunk_reset(&trash);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005018 trash.area[trash.data++] = '?';
5019 memcpy(trash.area + trash.data, name, name_len);
5020 trash.data += name_len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005021
Willy Tarreau843b7cb2018-07-13 10:54:26 +02005022 lua_pushboolean(L,
5023 http_replace_req_line(2, trash.area, trash.data, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005024 return 1;
5025}
5026
5027/* This function set the uri. */
5028static int hlua_http_req_set_uri(lua_State *L)
5029{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02005030 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005031 size_t name_len;
5032 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005033
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005034 /* Check if a valid request is parsed */
5035 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
5036 lua_pushboolean(L, 0);
5037 return 1;
5038 }
5039
Willy Tarreau987e3fb2015-04-04 01:09:08 +02005040 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005041 return 1;
5042}
5043
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005044/* This function set the response code & optionally reason. */
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005045static int hlua_http_res_set_status(lua_State *L)
5046{
5047 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
5048 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005049 const char *reason = MAY_LJMP(luaL_optlstring(L, 3, NULL, NULL));
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005050
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02005051 /* Check if a valid response is parsed */
5052 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
5053 return 0;
5054
Robin H. Johnson52f5db22017-01-01 13:10:52 -08005055 http_set_status(code, reason, htxn->s);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005056 return 0;
5057}
5058
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005059/*
5060 *
5061 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005062 * Class TXN
5063 *
5064 *
5065 */
5066
5067/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02005068 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005069 */
5070__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
5071{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005072 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005073}
5074
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005075__LJMP static int hlua_set_var(lua_State *L)
5076{
5077 struct hlua_txn *htxn;
5078 const char *name;
5079 size_t len;
5080 struct sample smp;
5081
5082 MAY_LJMP(check_args(L, 3, "set_var"));
5083
5084 /* It is useles to retrieve the stream, but this function
5085 * runs only in a stream context.
5086 */
5087 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5088 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5089
5090 /* Converts the third argument in a sample. */
5091 hlua_lua2smp(L, 3, &smp);
5092
5093 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01005094 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005095 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005096 return 0;
5097}
5098
Christopher Faulet85d79c92016-11-09 16:54:56 +01005099__LJMP static int hlua_unset_var(lua_State *L)
5100{
5101 struct hlua_txn *htxn;
5102 const char *name;
5103 size_t len;
5104 struct sample smp;
5105
5106 MAY_LJMP(check_args(L, 2, "unset_var"));
5107
5108 /* It is useles to retrieve the stream, but this function
5109 * runs only in a stream context.
5110 */
5111 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5112 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5113
5114 /* Unset the variable. */
5115 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
5116 vars_unset_by_name(name, len, &smp);
5117 return 0;
5118}
5119
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005120__LJMP static int hlua_get_var(lua_State *L)
5121{
5122 struct hlua_txn *htxn;
5123 const char *name;
5124 size_t len;
5125 struct sample smp;
5126
5127 MAY_LJMP(check_args(L, 2, "get_var"));
5128
5129 /* It is useles to retrieve the stream, but this function
5130 * runs only in a stream context.
5131 */
5132 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5133 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
5134
Willy Tarreau7560dd42016-03-10 16:28:58 +01005135 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01005136 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005137 lua_pushnil(L);
5138 return 1;
5139 }
5140
5141 return hlua_smp2lua(L, &smp);
5142}
5143
Willy Tarreau59551662015-03-10 14:23:13 +01005144__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005145{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005146 struct hlua *hlua;
5147
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005148 MAY_LJMP(check_args(L, 2, "set_priv"));
5149
Willy Tarreau87b09662015-04-03 00:22:06 +02005150 /* It is useles to retrieve the stream, but this function
5151 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005152 */
5153 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005154 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005155
5156 /* Remove previous value. */
Thierry FOURNIERe068b602017-04-26 13:27:05 +02005157 luaL_unref(L, LUA_REGISTRYINDEX, hlua->Mref);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005158
5159 /* Get and store new value. */
5160 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
5161 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
5162
5163 return 0;
5164}
5165
Willy Tarreau59551662015-03-10 14:23:13 +01005166__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005167{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005168 struct hlua *hlua;
5169
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005170 MAY_LJMP(check_args(L, 1, "get_priv"));
5171
Willy Tarreau87b09662015-04-03 00:22:06 +02005172 /* It is useles to retrieve the stream, but this function
5173 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005174 */
5175 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005176 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005177
5178 /* Push configuration index in the stack. */
5179 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
5180
5181 return 1;
5182}
5183
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005184/* Create stack entry containing a class TXN. This function
5185 * return 0 if the stack does not contains free slots,
5186 * otherwise it returns 1.
5187 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005188static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005189{
Willy Tarreaude491382015-04-06 11:04:28 +02005190 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005191
5192 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005193 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005194 return 0;
5195
5196 /* NOTE: The allocation never fails. The failure
5197 * throw an error, and the function never returns.
5198 * if the throw is not avalaible, the process is aborted.
5199 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005200 /* Create the object: obj[0] = userdata. */
5201 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02005202 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01005203 lua_rawseti(L, -2, 0);
5204
Willy Tarreaude491382015-04-06 11:04:28 +02005205 htxn->s = s;
5206 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01005207 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005208 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005209
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005210 /* Create the "f" field that contains a list of fetches. */
5211 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005212 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005213 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005214 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005215
5216 /* Create the "sf" field that contains a list of stringsafe fetches. */
5217 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01005218 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005219 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005220 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005221
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005222 /* Create the "c" field that contains a list of converters. */
5223 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02005224 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005225 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005226 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01005227
5228 /* Create the "sc" field that contains a list of stringsafe converters. */
5229 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01005230 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005231 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005232 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005233
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005234 /* Create the "req" field that contains the request channel object. */
5235 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005236 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005237 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005238 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005239
5240 /* Create the "res" field that contains the response channel object. */
5241 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01005242 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005243 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005244 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01005245
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005246 /* Creates the HTTP object is the current proxy allows http. */
5247 lua_pushstring(L, "http");
5248 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02005249 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005250 return 0;
5251 }
5252 else
5253 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02005254 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005255
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005256 /* Pop a class sesison metatable and affect it to the userdata. */
5257 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
5258 lua_setmetatable(L, -2);
5259
5260 return 1;
5261}
5262
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005263__LJMP static int hlua_txn_deflog(lua_State *L)
5264{
5265 const char *msg;
5266 struct hlua_txn *htxn;
5267
5268 MAY_LJMP(check_args(L, 2, "deflog"));
5269 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5270 msg = MAY_LJMP(luaL_checkstring(L, 2));
5271
5272 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
5273 return 0;
5274}
5275
5276__LJMP static int hlua_txn_log(lua_State *L)
5277{
5278 int level;
5279 const char *msg;
5280 struct hlua_txn *htxn;
5281
5282 MAY_LJMP(check_args(L, 3, "log"));
5283 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5284 level = MAY_LJMP(luaL_checkinteger(L, 2));
5285 msg = MAY_LJMP(luaL_checkstring(L, 3));
5286
5287 if (level < 0 || level >= NB_LOG_LEVELS)
5288 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5289
5290 hlua_sendlog(htxn->s->be, level, msg);
5291 return 0;
5292}
5293
5294__LJMP static int hlua_txn_log_debug(lua_State *L)
5295{
5296 const char *msg;
5297 struct hlua_txn *htxn;
5298
5299 MAY_LJMP(check_args(L, 2, "Debug"));
5300 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5301 msg = MAY_LJMP(luaL_checkstring(L, 2));
5302 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
5303 return 0;
5304}
5305
5306__LJMP static int hlua_txn_log_info(lua_State *L)
5307{
5308 const char *msg;
5309 struct hlua_txn *htxn;
5310
5311 MAY_LJMP(check_args(L, 2, "Info"));
5312 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5313 msg = MAY_LJMP(luaL_checkstring(L, 2));
5314 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
5315 return 0;
5316}
5317
5318__LJMP static int hlua_txn_log_warning(lua_State *L)
5319{
5320 const char *msg;
5321 struct hlua_txn *htxn;
5322
5323 MAY_LJMP(check_args(L, 2, "Warning"));
5324 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5325 msg = MAY_LJMP(luaL_checkstring(L, 2));
5326 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
5327 return 0;
5328}
5329
5330__LJMP static int hlua_txn_log_alert(lua_State *L)
5331{
5332 const char *msg;
5333 struct hlua_txn *htxn;
5334
5335 MAY_LJMP(check_args(L, 2, "Alert"));
5336 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5337 msg = MAY_LJMP(luaL_checkstring(L, 2));
5338 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5339 return 0;
5340}
5341
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005342__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5343{
5344 struct hlua_txn *htxn;
5345 int ll;
5346
5347 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5348 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5349 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5350
5351 if (ll < 0 || ll > 7)
5352 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5353
5354 htxn->s->logs.level = ll;
5355 return 0;
5356}
5357
5358__LJMP static int hlua_txn_set_tos(lua_State *L)
5359{
5360 struct hlua_txn *htxn;
5361 struct connection *cli_conn;
5362 int tos;
5363
5364 MAY_LJMP(check_args(L, 2, "set_tos"));
5365 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5366 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5367
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005368 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005369 inet_set_tos(cli_conn->handle.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005370
5371 return 0;
5372}
5373
5374__LJMP static int hlua_txn_set_mark(lua_State *L)
5375{
5376#ifdef SO_MARK
5377 struct hlua_txn *htxn;
5378 struct connection *cli_conn;
5379 int mark;
5380
5381 MAY_LJMP(check_args(L, 2, "set_mark"));
5382 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5383 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5384
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005385 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau585744b2017-08-24 14:31:19 +02005386 setsockopt(cli_conn->handle.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005387#endif
5388 return 0;
5389}
5390
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005391/* This function is an Lua binding that send pending data
5392 * to the client, and close the stream interface.
5393 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005394__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005395{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005396 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005397 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005398 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005399
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005400 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005401 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005402 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005403
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005404 /* If the flags NOTERM is set, we cannot terminate the http
5405 * session, so we just end the execution of the current
5406 * lua code.
5407 */
5408 if (htxn->flags & HLUA_TXN_NOTERM) {
5409 WILL_LJMP(hlua_done(L));
5410 return 0;
5411 }
5412
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005413 ic = &htxn->s->req;
5414 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005415
Willy Tarreau630ef452015-08-28 10:06:15 +02005416 if (htxn->s->txn) {
5417 /* HTTP mode, let's stay in sync with the stream */
Willy Tarreauc9fa0482018-07-10 17:43:27 +02005418 b_del(&ic->buf, htxn->s->txn->req.sov);
Willy Tarreau630ef452015-08-28 10:06:15 +02005419 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5420 htxn->s->txn->req.sov = 0;
5421 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5422 oc->analysers = AN_RES_HTTP_XFER_BODY;
5423 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5424 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5425
Willy Tarreau630ef452015-08-28 10:06:15 +02005426 /* Note that if we want to support keep-alive, we need
5427 * to bypass the close/shutr_now calls below, but that
5428 * may only be done if the HTTP request was already
5429 * processed and the connection header is known (ie
5430 * not during TCP rules).
5431 */
5432 }
5433
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005434 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005435 channel_abort(ic);
5436 channel_auto_close(ic);
5437 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005438
5439 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005440 channel_auto_read(oc);
5441 channel_auto_close(oc);
5442 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005443
Willy Tarreau0458b082015-08-28 09:40:04 +02005444 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005445
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005446 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005447 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005448 return 0;
5449}
5450
5451__LJMP static int hlua_log(lua_State *L)
5452{
5453 int level;
5454 const char *msg;
5455
5456 MAY_LJMP(check_args(L, 2, "log"));
5457 level = MAY_LJMP(luaL_checkinteger(L, 1));
5458 msg = MAY_LJMP(luaL_checkstring(L, 2));
5459
5460 if (level < 0 || level >= NB_LOG_LEVELS)
5461 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5462
5463 hlua_sendlog(NULL, level, msg);
5464 return 0;
5465}
5466
5467__LJMP static int hlua_log_debug(lua_State *L)
5468{
5469 const char *msg;
5470
5471 MAY_LJMP(check_args(L, 1, "debug"));
5472 msg = MAY_LJMP(luaL_checkstring(L, 1));
5473 hlua_sendlog(NULL, LOG_DEBUG, msg);
5474 return 0;
5475}
5476
5477__LJMP static int hlua_log_info(lua_State *L)
5478{
5479 const char *msg;
5480
5481 MAY_LJMP(check_args(L, 1, "info"));
5482 msg = MAY_LJMP(luaL_checkstring(L, 1));
5483 hlua_sendlog(NULL, LOG_INFO, msg);
5484 return 0;
5485}
5486
5487__LJMP static int hlua_log_warning(lua_State *L)
5488{
5489 const char *msg;
5490
5491 MAY_LJMP(check_args(L, 1, "warning"));
5492 msg = MAY_LJMP(luaL_checkstring(L, 1));
5493 hlua_sendlog(NULL, LOG_WARNING, msg);
5494 return 0;
5495}
5496
5497__LJMP static int hlua_log_alert(lua_State *L)
5498{
5499 const char *msg;
5500
5501 MAY_LJMP(check_args(L, 1, "alert"));
5502 msg = MAY_LJMP(luaL_checkstring(L, 1));
5503 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005504 return 0;
5505}
5506
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005507__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005508{
5509 int wakeup_ms = lua_tointeger(L, -1);
5510 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005511 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005512 return 0;
5513}
5514
5515__LJMP static int hlua_sleep(lua_State *L)
5516{
5517 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005518 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005519
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005520 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005521
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005522 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005523 wakeup_ms = tick_add(now_ms, delay);
5524 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005525
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005526 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5527 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005528}
5529
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005530__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005531{
5532 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005533 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005534
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005535 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005536
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005537 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005538 wakeup_ms = tick_add(now_ms, delay);
5539 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005540
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005541 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5542 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005543}
5544
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005545/* This functionis an LUA binding. it permits to give back
5546 * the hand at the HAProxy scheduler. It is used when the
5547 * LUA processing consumes a lot of time.
5548 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005549__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005550{
5551 return 0;
5552}
5553
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005554__LJMP static int hlua_yield(lua_State *L)
5555{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005556 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5557 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005558}
5559
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005560/* This function change the nice of the currently executed
5561 * task. It is used set low or high priority at the current
5562 * task.
5563 */
Willy Tarreau59551662015-03-10 14:23:13 +01005564__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005565{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005566 struct hlua *hlua;
5567 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005568
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005569 MAY_LJMP(check_args(L, 1, "set_nice"));
5570 hlua = hlua_gethlua(L);
5571 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005572
5573 /* If he task is not set, I'm in a start mode. */
5574 if (!hlua || !hlua->task)
5575 return 0;
5576
5577 if (nice < -1024)
5578 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005579 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005580 nice = 1024;
5581
5582 hlua->task->nice = nice;
5583 return 0;
5584}
5585
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005586/* This function is used as a calback of a task. It is called by the
5587 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5588 * return an E_AGAIN signal, the emmiter of this signal must set a
5589 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005590 *
5591 * Task wrapper are longjmp safe because the only one Lua code
5592 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005593 */
Olivier Houchard9f6af332018-05-25 14:04:04 +02005594static struct task *hlua_process_task(struct task *task, void *context, unsigned short state)
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005595{
Olivier Houchard9f6af332018-05-25 14:04:04 +02005596 struct hlua *hlua = context;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005597 enum hlua_exec status;
5598
Christopher Faulet5bc99722018-04-25 10:34:45 +02005599 if (task->thread_mask == MAX_THREADS_MASK)
5600 task_set_affinity(task, tid_bit);
5601
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005602 /* If it is the first call to the task, we must initialize the
5603 * execution timeouts.
5604 */
5605 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005606 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005607
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005608 /* Execute the Lua code. */
5609 status = hlua_ctx_resume(hlua, 1);
5610
5611 switch (status) {
5612 /* finished or yield */
5613 case HLUA_E_OK:
5614 hlua_ctx_destroy(hlua);
5615 task_delete(task);
5616 task_free(task);
Tim Duesterhuscd235c62018-04-24 13:56:01 +02005617 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005618 break;
5619
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005620 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
Thierry FOURNIERcb146882017-12-10 17:10:57 +01005621 notification_gc(&hlua->com);
PiBa-NLfe971b32018-05-02 22:27:14 +02005622 task->expire = hlua->wake_time;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005623 break;
5624
5625 /* finished with error. */
5626 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005627 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005628 hlua_ctx_destroy(hlua);
5629 task_delete(task);
5630 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005631 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005632 break;
5633
5634 case HLUA_E_ERR:
5635 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005636 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005637 hlua_ctx_destroy(hlua);
5638 task_delete(task);
5639 task_free(task);
Emeric Brun253e53e2017-10-17 18:58:40 +02005640 task = NULL;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005641 break;
5642 }
Emeric Brun253e53e2017-10-17 18:58:40 +02005643 return task;
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005644}
5645
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005646/* This function is an LUA binding that register LUA function to be
5647 * executed after the HAProxy configuration parsing and before the
5648 * HAProxy scheduler starts. This function expect only one LUA
5649 * argument that is a function. This function returns nothing, but
5650 * throws if an error is encountered.
5651 */
5652__LJMP static int hlua_register_init(lua_State *L)
5653{
5654 struct hlua_init_function *init;
5655 int ref;
5656
5657 MAY_LJMP(check_args(L, 1, "register_init"));
5658
5659 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5660
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005661 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005662 if (!init)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005663 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005664
5665 init->function_ref = ref;
5666 LIST_ADDQ(&hlua_init_functions, &init->l);
5667 return 0;
5668}
5669
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005670/* This functio is an LUA binding. It permits to register a task
5671 * executed in parallel of the main HAroxy activity. The task is
5672 * created and it is set in the HAProxy scheduler. It can be called
5673 * from the "init" section, "post init" or during the runtime.
5674 *
5675 * Lua prototype:
5676 *
5677 * <none> core.register_task(<function>)
5678 */
5679static int hlua_register_task(lua_State *L)
5680{
5681 struct hlua *hlua;
5682 struct task *task;
5683 int ref;
5684
5685 MAY_LJMP(check_args(L, 1, "register_task"));
5686
5687 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5688
Willy Tarreaubafbe012017-11-24 17:34:44 +01005689 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005690 if (!hlua)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005691 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005692
Emeric Brunc60def82017-09-27 14:59:38 +02005693 task = task_new(MAX_THREADS_MASK);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005694 task->context = hlua;
5695 task->process = hlua_process_task;
5696
5697 if (!hlua_ctx_init(hlua, task))
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01005698 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005699
5700 /* Restore the function in the stack. */
5701 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5702 hlua->nargs = 0;
5703
5704 /* Schedule task. */
5705 task_schedule(task, now_ms);
5706
5707 return 0;
5708}
5709
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005710/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5711 * doesn't allow "yield" functions because the HAProxy engine cannot
5712 * resume converters.
5713 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005714static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005715{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005716 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005717 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005718 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005719
Willy Tarreaube508f12016-03-10 11:47:01 +01005720 if (!stream)
5721 return 0;
5722
Willy Tarreau87b09662015-04-03 00:22:06 +02005723 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005724 * Lua context can be not initialized. This behavior
5725 * permits to save performances because a systematic
5726 * Lua initialization cause 5% performances loss.
5727 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005728 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005729 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005730 if (!stream->hlua) {
5731 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5732 return 0;
5733 }
5734 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5735 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
5736 return 0;
5737 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005738 }
5739
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005740 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005741 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005742
5743 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005744 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5745 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5746 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005747 else
5748 error = "critical error";
5749 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005750 return 0;
5751 }
5752
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005753 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005754 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005755 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005756 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005757 return 0;
5758 }
5759
5760 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005761 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005762
5763 /* convert input sample and pust-it in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005764 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005765 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005766 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005767 return 0;
5768 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005769 hlua_smp2lua(stream->hlua->T, smp);
5770 stream->hlua->nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005771
5772 /* push keywords in the stack. */
5773 if (arg_p) {
5774 for (; arg_p->type != ARGT_STOP; arg_p++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005775 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005776 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005777 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005778 return 0;
5779 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005780 hlua_arg2lua(stream->hlua->T, arg_p);
5781 stream->hlua->nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005782 }
5783 }
5784
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005785 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005786 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005787
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005788 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005789 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005790 }
5791
5792 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005793 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005794 /* finished. */
5795 case HLUA_E_OK:
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005796 /* If the stack is empty, the function fails. */
5797 if (lua_gettop(stream->hlua->T) <= 0)
5798 return 0;
5799
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005800 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005801 hlua_lua2smp(stream->hlua->T, -1, smp);
5802 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005803 return 1;
5804
5805 /* yield. */
5806 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005807 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005808 return 0;
5809
5810 /* finished with error. */
5811 case HLUA_E_ERRMSG:
5812 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005813 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005814 fcn->name, lua_tostring(stream->hlua->T, -1));
5815 lua_pop(stream->hlua->T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005816 return 0;
5817
Thierry Fournierd5b073c2018-05-21 19:42:47 +02005818 case HLUA_E_ETMOUT:
5819 SEND_ERR(stream->be, "Lua converter '%s': execution timeout.\n", fcn->name);
5820 return 0;
5821
5822 case HLUA_E_NOMEM:
5823 SEND_ERR(stream->be, "Lua converter '%s': out of memory error.\n", fcn->name);
5824 return 0;
5825
5826 case HLUA_E_YIELD:
5827 SEND_ERR(stream->be, "Lua converter '%s': yield functions like core.tcp() or core.sleep() are not allowed.\n", fcn->name);
5828 return 0;
5829
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005830 case HLUA_E_ERR:
5831 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005832 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005833
5834 default:
5835 return 0;
5836 }
5837}
5838
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005839/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5840 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005841 * resume sample-fetches. This function will be called by the sample
5842 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005843 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005844static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5845 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005846{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005847 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005848 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005849 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02005850 const struct buffer msg = { };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005851
Willy Tarreaube508f12016-03-10 11:47:01 +01005852 if (!stream)
5853 return 0;
5854
Willy Tarreau87b09662015-04-03 00:22:06 +02005855 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005856 * Lua context can be not initialized. This behavior
5857 * permits to save performances because a systematic
5858 * Lua initialization cause 5% performances loss.
5859 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005860 if (!stream->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01005861 stream->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005862 if (!stream->hlua) {
5863 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5864 return 0;
5865 }
5866 if (!hlua_ctx_init(stream->hlua, stream->task)) {
5867 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
5868 return 0;
5869 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005870 }
5871
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005872 consistency_set(stream, smp->opt, &stream->hlua->cons);
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005873
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005874 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005875 if (!HLUA_IS_RUNNING(stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005876
5877 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005878 if (!SET_SAFE_LJMP(stream->hlua->T)) {
5879 if (lua_type(stream->hlua->T, -1) == LUA_TSTRING)
5880 error = lua_tostring(stream->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01005881 else
5882 error = "critical error";
5883 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005884 return 0;
5885 }
5886
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005887 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005888 if (!lua_checkstack(stream->hlua->T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005889 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005890 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005891 return 0;
5892 }
5893
5894 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005895 lua_rawgeti(stream->hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005896
5897 /* push arguments in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005898 if (!hlua_txn_new(stream->hlua->T, stream, smp->px, smp->opt & SMP_OPT_DIR,
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005899 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005900 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005901 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005902 return 0;
5903 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005904 stream->hlua->nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005905
5906 /* push keywords in the stack. */
5907 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5908 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005909 if (!lua_checkstack(stream->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005910 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005911 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005912 return 0;
5913 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005914 hlua_arg2lua(stream->hlua->T, arg_p);
5915 stream->hlua->nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005916 }
5917
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005918 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005919 stream->hlua->max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005920
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005921 /* At this point the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005922 RESET_SAFE_LJMP(stream->hlua->T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005923 }
5924
5925 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005926 switch (hlua_ctx_resume(stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005927 /* finished. */
5928 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005929 if (!consistency_check(stream, smp->opt, &stream->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005930 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005931 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005932 }
Thierry FOURNIERfd80df12017-05-12 16:32:20 +02005933 /* If the stack is empty, the function fails. */
5934 if (lua_gettop(stream->hlua->T) <= 0)
5935 return 0;
5936
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005937 /* Convert the returned value in sample. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005938 hlua_lua2smp(stream->hlua->T, -1, smp);
5939 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005940
5941 /* Set the end of execution flag. */
5942 smp->flags &= ~SMP_F_MAY_CHANGE;
5943 return 1;
5944
5945 /* yield. */
5946 case HLUA_E_AGAIN:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005947 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005948 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005949 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005950 return 0;
5951
5952 /* finished with error. */
5953 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005954 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005955 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005956 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005957 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005958 fcn->name, lua_tostring(stream->hlua->T, -1));
5959 lua_pop(stream->hlua->T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005960 return 0;
5961
Thierry Fournierd5b073c2018-05-21 19:42:47 +02005962 case HLUA_E_ETMOUT:
5963 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
5964 stream_int_retnclose(&stream->si[0], &msg);
5965 SEND_ERR(smp->px, "Lua sample-fetch '%s': execution timeout.\n", fcn->name);
5966 return 0;
5967
5968 case HLUA_E_NOMEM:
5969 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
5970 stream_int_retnclose(&stream->si[0], &msg);
5971 SEND_ERR(smp->px, "Lua sample-fetch '%s': out of memory error.\n", fcn->name);
5972 return 0;
5973
5974 case HLUA_E_YIELD:
5975 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
5976 stream_int_retnclose(&stream->si[0], &msg);
5977 SEND_ERR(smp->px, "Lua sample-fetch '%s': yield not allowed.\n", fcn->name);
5978 return 0;
5979
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005980 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01005981 if (!consistency_check(stream, smp->opt, &stream->hlua->cons))
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005982 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005983 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005984 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005985
5986 default:
5987 return 0;
5988 }
5989}
5990
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005991/* This function is an LUA binding used for registering
5992 * "sample-conv" functions. It expects a converter name used
5993 * in the haproxy configuration file, and an LUA function.
5994 */
5995__LJMP static int hlua_register_converters(lua_State *L)
5996{
5997 struct sample_conv_kw_list *sck;
5998 const char *name;
5999 int ref;
6000 int len;
6001 struct hlua_function *fcn;
6002
6003 MAY_LJMP(check_args(L, 2, "register_converters"));
6004
6005 /* First argument : converter name. */
6006 name = MAY_LJMP(luaL_checkstring(L, 1));
6007
6008 /* Second argument : lua function. */
6009 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6010
6011 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006012 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006013 if (!sck)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006014 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006015 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006016 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006017 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006018
6019 /* Fill fcn. */
6020 fcn->name = strdup(name);
6021 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006022 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006023 fcn->function_ref = ref;
6024
6025 /* List head */
6026 sck->list.n = sck->list.p = NULL;
6027
6028 /* converter keyword. */
6029 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006030 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006031 if (!sck->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006032 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006033
6034 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
6035 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006036 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 +01006037 sck->kw[0].val_args = NULL;
6038 sck->kw[0].in_type = SMP_T_STR;
6039 sck->kw[0].out_type = SMP_T_STR;
6040 sck->kw[0].private = fcn;
6041
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01006042 /* Register this new converter */
6043 sample_register_convs(sck);
6044
6045 return 0;
6046}
6047
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006048/* This fucntion is an LUA binding used for registering
6049 * "sample-fetch" functions. It expects a converter name used
6050 * in the haproxy configuration file, and an LUA function.
6051 */
6052__LJMP static int hlua_register_fetches(lua_State *L)
6053{
6054 const char *name;
6055 int ref;
6056 int len;
6057 struct sample_fetch_kw_list *sfk;
6058 struct hlua_function *fcn;
6059
6060 MAY_LJMP(check_args(L, 2, "register_fetches"));
6061
6062 /* First argument : sample-fetch name. */
6063 name = MAY_LJMP(luaL_checkstring(L, 1));
6064
6065 /* Second argument : lua function. */
6066 ref = MAY_LJMP(hlua_checkfunction(L, 2));
6067
6068 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006069 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006070 if (!sfk)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006071 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006072 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006073 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006074 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006075
6076 /* Fill fcn. */
6077 fcn->name = strdup(name);
6078 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006079 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006080 fcn->function_ref = ref;
6081
6082 /* List head */
6083 sfk->list.n = sfk->list.p = NULL;
6084
6085 /* sample-fetch keyword. */
6086 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006087 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006088 if (!sfk->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006089 return luaL_error(L, "Lua out of memory error.");
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006090
6091 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
6092 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01006093 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 +01006094 sfk->kw[0].val_args = NULL;
6095 sfk->kw[0].out_type = SMP_T_STR;
6096 sfk->kw[0].use = SMP_USE_HTTP_ANY;
6097 sfk->kw[0].val = 0;
6098 sfk->kw[0].private = fcn;
6099
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01006100 /* Register this new fetch. */
6101 sample_register_fetches(sfk);
6102
6103 return 0;
6104}
6105
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006106/* This function is a wrapper to execute each LUA function declared
6107 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006108 * return ACT_RET_CONT if the processing is finished (with or without
6109 * error) and return ACT_RET_YIELD if the function must be called again
6110 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006111 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006112static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02006113 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006114{
6115 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006116 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006117 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006118 const char *error;
Willy Tarreau83061a82018-07-13 11:56:34 +02006119 const struct buffer msg = { };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006120
6121 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01006122 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
6123 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
6124 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
6125 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006126 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006127 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006128 return ACT_RET_CONT;
6129 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006130
Willy Tarreau87b09662015-04-03 00:22:06 +02006131 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006132 * Lua context can be not initialized. This behavior
6133 * permits to save performances because a systematic
6134 * Lua initialization cause 5% performances loss.
6135 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006136 if (!s->hlua) {
Willy Tarreaubafbe012017-11-24 17:34:44 +01006137 s->hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006138 if (!s->hlua) {
6139 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6140 rule->arg.hlua_rule->fcn.name);
6141 return ACT_RET_CONT;
6142 }
6143 if (!hlua_ctx_init(s->hlua, s->task)) {
6144 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
6145 rule->arg.hlua_rule->fcn.name);
6146 return ACT_RET_CONT;
6147 }
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01006148 }
6149
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006150 consistency_set(s, dir, &s->hlua->cons);
6151
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006152 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006153 if (!HLUA_IS_RUNNING(s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006154
6155 /* The following Lua calls can fail. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006156 if (!SET_SAFE_LJMP(s->hlua->T)) {
6157 if (lua_type(s->hlua->T, -1) == LUA_TSTRING)
6158 error = lua_tostring(s->hlua->T, -1);
Thierry Fournierfd107a22016-02-19 19:57:23 +01006159 else
6160 error = "critical error";
6161 SEND_ERR(px, "Lua function '%s': %s.\n",
6162 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006163 return ACT_RET_CONT;
6164 }
6165
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006166 /* Check stack available size. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006167 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006168 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006169 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006170 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006171 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006172 }
6173
6174 /* Restore the function in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006175 lua_rawgeti(s->hlua->T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006176
Willy Tarreau87b09662015-04-03 00:22:06 +02006177 /* Create and and push object stream in the stack. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006178 if (!hlua_txn_new(s->hlua->T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006179 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006180 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006181 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006182 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006183 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006184 s->hlua->nargs = 1;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006185
6186 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006187 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006188 if (!lua_checkstack(s->hlua->T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006189 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006190 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006191 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006192 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006193 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006194 lua_pushstring(s->hlua->T, *arg);
6195 s->hlua->nargs++;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006196 }
6197
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006198 /* Now the execution is safe. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006199 RESET_SAFE_LJMP(s->hlua->T);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006200
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006201 /* We must initialize the execution timeouts. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006202 s->hlua->max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006203 }
6204
6205 /* Execute the function. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006206 switch (hlua_ctx_resume(s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006207 /* finished. */
6208 case HLUA_E_OK:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006209 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006210 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006211 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006212 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006213 if (s->hlua->flags & HLUA_STOP)
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02006214 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006215 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006216
6217 /* yield. */
6218 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006219 /* Set timeout in the required channel. */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006220 if (s->hlua->wake_time != TICK_ETERNITY) {
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006221 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006222 s->req.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006223 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006224 s->res.analyse_exp = s->hlua->wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01006225 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006226 /* Some actions can be wake up when a "write" event
6227 * is detected on a response channel. This is useful
6228 * only for actions targetted on the requests.
6229 */
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006230 if (HLUA_IS_WAKERESWR(s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006231 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01006232 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006233 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006234 }
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006235 if (HLUA_IS_WAKEREQWR(s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01006236 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006237 /* We can quit the fcuntion without consistency check
6238 * because HAProxy is not able to manipulate data, it
6239 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006240 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006241
6242 /* finished with error. */
6243 case HLUA_E_ERRMSG:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006244 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006245 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006246 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006247 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006248 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006249 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006250 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua->T, -1));
6251 lua_pop(s->hlua->T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006252 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006253
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006254 case HLUA_E_ETMOUT:
6255 if (!consistency_check(s, dir, &s->hlua->cons)) {
6256 stream_int_retnclose(&s->si[0], &msg);
6257 return ACT_RET_ERR;
6258 }
6259 SEND_ERR(px, "Lua function '%s': execution timeout.\n", rule->arg.hlua_rule->fcn.name);
6260 return 0;
6261
6262 case HLUA_E_NOMEM:
6263 if (!consistency_check(s, dir, &s->hlua->cons)) {
6264 stream_int_retnclose(&s->si[0], &msg);
6265 return ACT_RET_ERR;
6266 }
6267 SEND_ERR(px, "Lua function '%s': out of memory error.\n", rule->arg.hlua_rule->fcn.name);
6268 return 0;
6269
6270 case HLUA_E_YIELD:
6271 if (!consistency_check(s, dir, &s->hlua->cons)) {
6272 stream_int_retnclose(&s->si[0], &msg);
6273 return ACT_RET_ERR;
6274 }
6275 SEND_ERR(px, "Lua function '%s': aborting Lua processing on expired timeout.\n",
6276 rule->arg.hlua_rule->fcn.name);
6277 return 0;
6278
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006279 case HLUA_E_ERR:
Thierry FOURNIER2c8b54e2016-12-17 12:45:32 +01006280 if (!consistency_check(s, dir, &s->hlua->cons)) {
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006281 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02006282 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01006283 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006284 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02006285 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006286 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006287
6288 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02006289 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006290 }
6291}
6292
Olivier Houchard9f6af332018-05-25 14:04:04 +02006293struct task *hlua_applet_wakeup(struct task *t, void *context, unsigned short state)
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006294{
Olivier Houchard9f6af332018-05-25 14:04:04 +02006295 struct appctx *ctx = context;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006296 struct stream_interface *si = ctx->owner;
6297
6298 /* If the applet is wake up without any expected work, the sheduler
6299 * remove it from the run queue. This flag indicate that the applet
6300 * is waiting for write. If the buffer is full, the main processing
6301 * will send some data and after call the applet, otherwise it call
6302 * the applet ASAP.
6303 */
6304 si_applet_cant_put(si);
6305 appctx_wakeup(ctx);
Willy Tarreaud9587412017-08-23 16:07:33 +02006306 t->expire = TICK_ETERNITY;
Willy Tarreaud1aa41f2017-07-21 16:41:56 +02006307 return t;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006308}
6309
6310static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6311{
6312 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006313 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006314 struct task *task;
6315 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01006316 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006317
Willy Tarreaubafbe012017-11-24 17:34:44 +01006318 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006319 if (!hlua) {
6320 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6321 ctx->rule->arg.hlua_rule->fcn.name);
6322 return 0;
6323 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006324 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006325 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006326 ctx->ctx.hlua_apptcp.flags = 0;
6327
6328 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006329 task = task_new(tid_bit);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006330 if (!task) {
6331 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
6332 ctx->rule->arg.hlua_rule->fcn.name);
6333 return 0;
6334 }
6335 task->nice = 0;
6336 task->context = ctx;
6337 task->process = hlua_applet_wakeup;
6338 ctx->ctx.hlua_apptcp.task = task;
6339
6340 /* In the execution wrappers linked with a stream, the
6341 * Lua context can be not initialized. This behavior
6342 * permits to save performances because a systematic
6343 * Lua initialization cause 5% performances loss.
6344 */
6345 if (!hlua_ctx_init(hlua, task)) {
6346 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
6347 ctx->rule->arg.hlua_rule->fcn.name);
6348 return 0;
6349 }
6350
6351 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006352 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006353
6354 /* The following Lua calls can fail. */
6355 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006356 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6357 error = lua_tostring(hlua->T, -1);
6358 else
6359 error = "critical error";
6360 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6361 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006362 RESET_SAFE_LJMP(hlua->T);
6363 return 0;
6364 }
6365
6366 /* Check stack available size. */
6367 if (!lua_checkstack(hlua->T, 1)) {
6368 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6369 ctx->rule->arg.hlua_rule->fcn.name);
6370 RESET_SAFE_LJMP(hlua->T);
6371 return 0;
6372 }
6373
6374 /* Restore the function in the stack. */
6375 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6376
6377 /* Create and and push object stream in the stack. */
6378 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
6379 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6380 ctx->rule->arg.hlua_rule->fcn.name);
6381 RESET_SAFE_LJMP(hlua->T);
6382 return 0;
6383 }
6384 hlua->nargs = 1;
6385
6386 /* push keywords in the stack. */
6387 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6388 if (!lua_checkstack(hlua->T, 1)) {
6389 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
6390 ctx->rule->arg.hlua_rule->fcn.name);
6391 RESET_SAFE_LJMP(hlua->T);
6392 return 0;
6393 }
6394 lua_pushstring(hlua->T, *arg);
6395 hlua->nargs++;
6396 }
6397
6398 RESET_SAFE_LJMP(hlua->T);
6399
6400 /* Wakeup the applet ASAP. */
6401 si_applet_cant_get(si);
6402 si_applet_cant_put(si);
6403
6404 return 1;
6405}
6406
6407static void hlua_applet_tcp_fct(struct appctx *ctx)
6408{
6409 struct stream_interface *si = ctx->owner;
6410 struct stream *strm = si_strm(si);
6411 struct channel *res = si_ic(si);
6412 struct act_rule *rule = ctx->rule;
6413 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006414 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006415
6416 /* The applet execution is already done. */
6417 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6418 return;
6419
6420 /* If the stream is disconnect or closed, ldo nothing. */
6421 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6422 return;
6423
6424 /* Execute the function. */
6425 switch (hlua_ctx_resume(hlua, 1)) {
6426 /* finished. */
6427 case HLUA_E_OK:
6428 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6429
6430 /* log time */
6431 strm->logs.tv_request = now;
6432
6433 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006434 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006435 res->flags |= CF_READ_NULL;
6436 si_shutr(si);
6437 return;
6438
6439 /* yield. */
6440 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006441 if (hlua->wake_time != TICK_ETERNITY)
6442 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006443 return;
6444
6445 /* finished with error. */
6446 case HLUA_E_ERRMSG:
6447 /* Display log. */
6448 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6449 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6450 lua_pop(hlua->T, 1);
6451 goto error;
6452
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006453 case HLUA_E_ETMOUT:
6454 SEND_ERR(px, "Lua applet tcp '%s': execution timeout.\n",
6455 rule->arg.hlua_rule->fcn.name);
6456 goto error;
6457
6458 case HLUA_E_NOMEM:
6459 SEND_ERR(px, "Lua applet tcp '%s': out of memory error.\n",
6460 rule->arg.hlua_rule->fcn.name);
6461 goto error;
6462
6463 case HLUA_E_YIELD: /* unexpected */
6464 SEND_ERR(px, "Lua applet tcp '%s': yield not allowed.\n",
6465 rule->arg.hlua_rule->fcn.name);
6466 goto error;
6467
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006468 case HLUA_E_ERR:
6469 /* Display log. */
6470 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6471 rule->arg.hlua_rule->fcn.name);
6472 goto error;
6473
6474 default:
6475 goto error;
6476 }
6477
6478error:
6479
6480 /* For all other cases, just close the stream. */
6481 si_shutw(si);
6482 si_shutr(si);
6483 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6484}
6485
6486static void hlua_applet_tcp_release(struct appctx *ctx)
6487{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006488 task_delete(ctx->ctx.hlua_apptcp.task);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006489 task_free(ctx->ctx.hlua_apptcp.task);
6490 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006491 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006492 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006493}
6494
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006495/* The function returns 1 if the initialisation is complete, 0 if
6496 * an errors occurs and -1 if more data are required for initializing
6497 * the applet.
6498 */
6499static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6500{
6501 struct stream_interface *si = ctx->owner;
6502 struct channel *req = si_oc(si);
6503 struct http_msg *msg;
6504 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006505 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006506 char **arg;
6507 struct hdr_ctx hdr;
6508 struct task *task;
6509 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006510 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006511
6512 /* Wait for a full HTTP request. */
6513 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6514 if (smp.flags & SMP_F_MAY_CHANGE)
6515 return -1;
6516 return 0;
6517 }
6518 txn = strm->txn;
6519 msg = &txn->req;
6520
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006521 /* We want two things in HTTP mode :
6522 * - enforce server-close mode if we were in keep-alive, so that the
6523 * applet is released after each response ;
6524 * - enable request body transfer to the applet in order to resync
6525 * with the response body.
6526 */
6527 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6528 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006529
Willy Tarreaubafbe012017-11-24 17:34:44 +01006530 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006531 if (!hlua) {
6532 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6533 ctx->rule->arg.hlua_rule->fcn.name);
6534 return 0;
6535 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006536 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006537 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006538 ctx->ctx.hlua_apphttp.left_bytes = -1;
6539 ctx->ctx.hlua_apphttp.flags = 0;
6540
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006541 if (txn->req.flags & HTTP_MSGF_VER_11)
6542 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6543
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006544 /* Create task used by signal to wakeup applets. */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01006545 task = task_new(tid_bit);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006546 if (!task) {
6547 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6548 ctx->rule->arg.hlua_rule->fcn.name);
6549 return 0;
6550 }
6551 task->nice = 0;
6552 task->context = ctx;
6553 task->process = hlua_applet_wakeup;
6554 ctx->ctx.hlua_apphttp.task = task;
6555
6556 /* In the execution wrappers linked with a stream, the
6557 * Lua context can be not initialized. This behavior
6558 * permits to save performances because a systematic
6559 * Lua initialization cause 5% performances loss.
6560 */
6561 if (!hlua_ctx_init(hlua, task)) {
6562 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6563 ctx->rule->arg.hlua_rule->fcn.name);
6564 return 0;
6565 }
6566
6567 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006568 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006569
6570 /* The following Lua calls can fail. */
6571 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006572 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6573 error = lua_tostring(hlua->T, -1);
6574 else
6575 error = "critical error";
6576 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6577 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006578 return 0;
6579 }
6580
6581 /* Check stack available size. */
6582 if (!lua_checkstack(hlua->T, 1)) {
6583 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6584 ctx->rule->arg.hlua_rule->fcn.name);
6585 RESET_SAFE_LJMP(hlua->T);
6586 return 0;
6587 }
6588
6589 /* Restore the function in the stack. */
6590 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6591
6592 /* Create and and push object stream in the stack. */
6593 if (!hlua_applet_http_new(hlua->T, ctx)) {
6594 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6595 ctx->rule->arg.hlua_rule->fcn.name);
6596 RESET_SAFE_LJMP(hlua->T);
6597 return 0;
6598 }
6599 hlua->nargs = 1;
6600
6601 /* Look for a 100-continue expected. */
6602 if (msg->flags & HTTP_MSGF_VER_11) {
6603 hdr.idx = 0;
Willy Tarreaua79021a2018-06-15 18:07:57 +02006604 if (http_find_header2("Expect", 6, ci_head(req), &txn->hdr_idx, &hdr) &&
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006605 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6606 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6607 }
6608
6609 /* push keywords in the stack. */
6610 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6611 if (!lua_checkstack(hlua->T, 1)) {
6612 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6613 ctx->rule->arg.hlua_rule->fcn.name);
6614 RESET_SAFE_LJMP(hlua->T);
6615 return 0;
6616 }
6617 lua_pushstring(hlua->T, *arg);
6618 hlua->nargs++;
6619 }
6620
6621 RESET_SAFE_LJMP(hlua->T);
6622
6623 /* Wakeup the applet when data is ready for read. */
6624 si_applet_cant_get(si);
6625
6626 return 1;
6627}
6628
6629static void hlua_applet_http_fct(struct appctx *ctx)
6630{
6631 struct stream_interface *si = ctx->owner;
6632 struct stream *strm = si_strm(si);
6633 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006634 struct act_rule *rule = ctx->rule;
6635 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006636 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Willy Tarreau206ba832018-06-14 15:27:31 +02006637 const char *blk1;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02006638 size_t len1;
Willy Tarreau206ba832018-06-14 15:27:31 +02006639 const char *blk2;
Willy Tarreau55f3ce12018-07-18 11:49:27 +02006640 size_t len2;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006641 int ret;
6642
6643 /* If the stream is disconnect or closed, ldo nothing. */
6644 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6645 return;
6646
6647 /* Set the currently running flag. */
6648 if (!HLUA_IS_RUNNING(hlua) &&
6649 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6650
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006651 /* Wait for full HTTP analysys. */
6652 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6653 si_applet_cant_get(si);
6654 return;
6655 }
6656
6657 /* Store the max amount of bytes that we can read. */
6658 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6659
6660 /* We need to flush the request header. This left the body
6661 * for the Lua.
6662 */
6663
6664 /* Read the maximum amount of data avalaible. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006665 ret = co_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006666 if (ret == -1)
6667 return;
6668
6669 /* No data available, ask for more data. */
6670 if (ret == 1)
6671 len2 = 0;
6672 if (ret == 0)
6673 len1 = 0;
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02006674 if (len1 + len2 < strm->txn->req.eoh + strm->txn->req.eol) {
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006675 si_applet_cant_get(si);
6676 return;
6677 }
6678
6679 /* skip the requests bytes. */
Thierry FOURNIER70d318c2018-06-30 10:37:33 +02006680 co_skip(si_oc(si), strm->txn->req.eoh + strm->txn->req.eol);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006681 }
6682
6683 /* Executes The applet if it is not done. */
6684 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6685
6686 /* Execute the function. */
6687 switch (hlua_ctx_resume(hlua, 1)) {
6688 /* finished. */
6689 case HLUA_E_OK:
6690 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6691 break;
6692
6693 /* yield. */
6694 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006695 if (hlua->wake_time != TICK_ETERNITY)
6696 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006697 return;
6698
6699 /* finished with error. */
6700 case HLUA_E_ERRMSG:
6701 /* Display log. */
6702 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6703 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6704 lua_pop(hlua->T, 1);
6705 goto error;
6706
Thierry Fournierd5b073c2018-05-21 19:42:47 +02006707 case HLUA_E_ETMOUT:
6708 SEND_ERR(px, "Lua applet http '%s': execution timeout.\n",
6709 rule->arg.hlua_rule->fcn.name);
6710 goto error;
6711
6712 case HLUA_E_NOMEM:
6713 SEND_ERR(px, "Lua applet http '%s': out of memory error.\n",
6714 rule->arg.hlua_rule->fcn.name);
6715 goto error;
6716
6717 case HLUA_E_YIELD: /* unexpected */
6718 SEND_ERR(px, "Lua applet http '%s': yield not allowed.\n",
6719 rule->arg.hlua_rule->fcn.name);
6720 goto error;
6721
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006722 case HLUA_E_ERR:
6723 /* Display log. */
6724 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6725 rule->arg.hlua_rule->fcn.name);
6726 goto error;
6727
6728 default:
6729 goto error;
6730 }
6731 }
6732
6733 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6734
6735 /* We must send the final chunk. */
6736 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6737 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6738
6739 /* sent last chunk at once. */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006740 ret = ci_putblk(res, "0\r\n\r\n", 5);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006741
6742 /* critical error. */
6743 if (ret == -2 || ret == -3) {
6744 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6745 rule->arg.hlua_rule->fcn.name);
6746 goto error;
6747 }
6748
6749 /* no enough space error. */
6750 if (ret == -1) {
6751 si_applet_cant_put(si);
6752 return;
6753 }
6754
6755 /* set the last chunk sent. */
6756 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6757 }
6758
6759 /* close the connection. */
6760
6761 /* status / log */
6762 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6763 strm->logs.tv_request = now;
6764
6765 /* eat the whole request */
Willy Tarreaua79021a2018-06-15 18:07:57 +02006766 co_skip(si_oc(si), co_data(si_oc(si)));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006767 res->flags |= CF_READ_NULL;
6768 si_shutr(si);
6769
6770 return;
6771 }
6772
6773error:
6774
6775 /* If we are in HTTP mode, and we are not send any
6776 * data, return a 500 server error in best effort:
6777 * if there are no room avalaible in the buffer,
6778 * just close the connection.
6779 */
Willy Tarreau06d80a92017-10-19 14:32:15 +02006780 ci_putblk(res, error_500, strlen(error_500));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006781 if (!(strm->flags & SF_ERR_MASK))
6782 strm->flags |= SF_ERR_RESOURCE;
6783 si_shutw(si);
6784 si_shutr(si);
6785 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6786}
6787
6788static void hlua_applet_http_release(struct appctx *ctx)
6789{
Willy Tarreaubd7fc952017-07-24 17:35:27 +02006790 task_delete(ctx->ctx.hlua_apphttp.task);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006791 task_free(ctx->ctx.hlua_apphttp.task);
6792 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006793 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006794 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006795}
6796
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006797/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6798 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006799 *
6800 * This function can fail with an abort() due to an Lua critical error.
6801 * We are in the configuration parsing process of HAProxy, this abort() is
6802 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006803 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006804static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6805 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006806{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006807 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006808 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006809
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006810 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006811 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006812 if (!rule->arg.hlua_rule) {
6813 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006814 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006815 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006816
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006817 /* Memory for arguments. */
6818 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6819 if (!rule->arg.hlua_rule->args) {
6820 memprintf(err, "out of memory error");
6821 return ACT_RET_PRS_ERR;
6822 }
6823
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006824 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006825 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006826
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006827 /* Expect some arguments */
6828 for (i = 0; i < fcn->nargs; i++) {
6829 if (*args[i+1] == '\0') {
6830 memprintf(err, "expect %d arguments", fcn->nargs);
6831 return ACT_RET_PRS_ERR;
6832 }
6833 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6834 if (!rule->arg.hlua_rule->args[i]) {
6835 memprintf(err, "out of memory error");
6836 return ACT_RET_PRS_ERR;
6837 }
6838 (*cur_arg)++;
6839 }
6840 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006841
Thierry FOURNIER42148732015-09-02 17:17:33 +02006842 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006843 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006844 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006845}
6846
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006847static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6848 struct act_rule *rule, char **err)
6849{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006850 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006851
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006852 /* HTTP applets are forbidden in tcp-request rules.
6853 * HTTP applet request requires everything initilized by
6854 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6855 * The applet will be immediately initilized, but its before
6856 * the call of this analyzer.
6857 */
6858 if (rule->from != ACT_F_HTTP_REQ) {
6859 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6860 return ACT_RET_PRS_ERR;
6861 }
6862
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006863 /* Memory for the rule. */
6864 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6865 if (!rule->arg.hlua_rule) {
6866 memprintf(err, "out of memory error");
6867 return ACT_RET_PRS_ERR;
6868 }
6869
6870 /* Reference the Lua function and store the reference. */
6871 rule->arg.hlua_rule->fcn = *fcn;
6872
6873 /* TODO: later accept arguments. */
6874 rule->arg.hlua_rule->args = NULL;
6875
6876 /* Add applet pointer in the rule. */
6877 rule->applet.obj_type = OBJ_TYPE_APPLET;
6878 rule->applet.name = fcn->name;
6879 rule->applet.init = hlua_applet_http_init;
6880 rule->applet.fct = hlua_applet_http_fct;
6881 rule->applet.release = hlua_applet_http_release;
6882 rule->applet.timeout = hlua_timeout_applet;
6883
6884 return ACT_RET_PRS_OK;
6885}
6886
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006887/* This function is an LUA binding used for registering
6888 * "sample-conv" functions. It expects a converter name used
6889 * in the haproxy configuration file, and an LUA function.
6890 */
6891__LJMP static int hlua_register_action(lua_State *L)
6892{
6893 struct action_kw_list *akl;
6894 const char *name;
6895 int ref;
6896 int len;
6897 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006898 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006899
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006900 /* Initialise the number of expected arguments at 0. */
6901 nargs = 0;
6902
6903 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6904 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006905
6906 /* First argument : converter name. */
6907 name = MAY_LJMP(luaL_checkstring(L, 1));
6908
6909 /* Second argument : environment. */
6910 if (lua_type(L, 2) != LUA_TTABLE)
6911 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6912
6913 /* Third argument : lua function. */
6914 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6915
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006916 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6917 if (lua_gettop(L) >= 4)
6918 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6919
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006920 /* browse the second argulent as an array. */
6921 lua_pushnil(L);
6922 while (lua_next(L, 2) != 0) {
6923 if (lua_type(L, -1) != LUA_TSTRING)
6924 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6925
6926 /* Check required environment. Only accepted "http" or "tcp". */
6927 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006928 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006929 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006930 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006931 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006932 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006933 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006934
6935 /* Fill fcn. */
6936 fcn->name = strdup(name);
6937 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006938 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006939 fcn->function_ref = ref;
6940
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006941 /* Set the expected number od arguments. */
6942 fcn->nargs = nargs;
6943
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006944 /* List head */
6945 akl->list.n = akl->list.p = NULL;
6946
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006947 /* action keyword. */
6948 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006949 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006950 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006951 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006952
6953 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6954
6955 akl->kw[0].match_pfx = 0;
6956 akl->kw[0].private = fcn;
6957 akl->kw[0].parse = action_register_lua;
6958
6959 /* select the action registering point. */
6960 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6961 tcp_req_cont_keywords_register(akl);
6962 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6963 tcp_res_cont_keywords_register(akl);
6964 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6965 http_req_keywords_register(akl);
6966 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6967 http_res_keywords_register(akl);
6968 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01006969 WILL_LJMP(luaL_error(L, "Lua action environment '%s' is unknown. "
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006970 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6971 "are expected.", lua_tostring(L, -1)));
6972
6973 /* pop the environment string. */
6974 lua_pop(L, 1);
6975 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006976 return ACT_RET_PRS_OK;
6977}
6978
6979static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6980 struct act_rule *rule, char **err)
6981{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006982 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006983
6984 /* Memory for the rule. */
6985 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6986 if (!rule->arg.hlua_rule) {
6987 memprintf(err, "out of memory error");
6988 return ACT_RET_PRS_ERR;
6989 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006990
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006991 /* Reference the Lua function and store the reference. */
6992 rule->arg.hlua_rule->fcn = *fcn;
6993
6994 /* TODO: later accept arguments. */
6995 rule->arg.hlua_rule->args = NULL;
6996
6997 /* Add applet pointer in the rule. */
6998 rule->applet.obj_type = OBJ_TYPE_APPLET;
6999 rule->applet.name = fcn->name;
7000 rule->applet.init = hlua_applet_tcp_init;
7001 rule->applet.fct = hlua_applet_tcp_fct;
7002 rule->applet.release = hlua_applet_tcp_release;
7003 rule->applet.timeout = hlua_timeout_applet;
7004
7005 return 0;
7006}
7007
7008/* This function is an LUA binding used for registering
7009 * "sample-conv" functions. It expects a converter name used
7010 * in the haproxy configuration file, and an LUA function.
7011 */
7012__LJMP static int hlua_register_service(lua_State *L)
7013{
7014 struct action_kw_list *akl;
7015 const char *name;
7016 const char *env;
7017 int ref;
7018 int len;
7019 struct hlua_function *fcn;
7020
7021 MAY_LJMP(check_args(L, 3, "register_service"));
7022
7023 /* First argument : converter name. */
7024 name = MAY_LJMP(luaL_checkstring(L, 1));
7025
7026 /* Second argument : environment. */
7027 env = MAY_LJMP(luaL_checkstring(L, 2));
7028
7029 /* Third argument : lua function. */
7030 ref = MAY_LJMP(hlua_checkfunction(L, 3));
7031
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007032 /* Allocate and fill the sample fetch keyword struct. */
7033 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
7034 if (!akl)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007035 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007036 fcn = calloc(1, sizeof(*fcn));
7037 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007038 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007039
7040 /* Fill fcn. */
7041 len = strlen("<lua.>") + strlen(name) + 1;
7042 fcn->name = calloc(1, len);
7043 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007044 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007045 snprintf((char *)fcn->name, len, "<lua.%s>", name);
7046 fcn->function_ref = ref;
7047
7048 /* List head */
7049 akl->list.n = akl->list.p = NULL;
7050
7051 /* converter keyword. */
7052 len = strlen("lua.") + strlen(name) + 1;
7053 akl->kw[0].kw = calloc(1, len);
7054 if (!akl->kw[0].kw)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007055 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007056
7057 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
7058
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01007059 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007060 if (strcmp(env, "tcp") == 0)
7061 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007062 else if (strcmp(env, "http") == 0)
7063 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007064 else
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007065 WILL_LJMP(luaL_error(L, "Lua service environment '%s' is unknown. "
Eric Salamafe7456f2017-12-21 14:30:07 +01007066 "'tcp' or 'http' are expected.", env));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007067
7068 akl->kw[0].match_pfx = 0;
7069 akl->kw[0].private = fcn;
7070
7071 /* End of array. */
7072 memset(&akl->kw[1], 0, sizeof(*akl->kw));
7073
7074 /* Register this new converter */
7075 service_keywords_register(akl);
7076
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007077 return 0;
7078}
7079
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007080/* This function initialises Lua cli handler. It copies the
7081 * arguments in the Lua stack and create channel IO objects.
7082 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02007083static int hlua_cli_parse_fct(char **args, char *payload, struct appctx *appctx, void *private)
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007084{
7085 struct hlua *hlua;
7086 struct hlua_function *fcn;
7087 int i;
7088 const char *error;
7089
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007090 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007091 appctx->ctx.hlua_cli.fcn = private;
7092
Willy Tarreaubafbe012017-11-24 17:34:44 +01007093 hlua = pool_alloc(pool_head_hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007094 if (!hlua) {
7095 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007096 return 1;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007097 }
7098 HLUA_INIT(hlua);
7099 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007100
7101 /* Create task used by signal to wakeup applets.
7102 * We use the same wakeup fonction than the Lua applet_tcp and
7103 * applet_http. It is absolutely compatible.
7104 */
Willy Tarreau5f4a47b2017-10-31 15:59:32 +01007105 appctx->ctx.hlua_cli.task = task_new(tid_bit);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007106 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01007107 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007108 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007109 }
7110 appctx->ctx.hlua_cli.task->nice = 0;
7111 appctx->ctx.hlua_cli.task->context = appctx;
7112 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
7113
7114 /* Initialises the Lua context */
7115 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
7116 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007117 goto error;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007118 }
7119
7120 /* The following Lua calls can fail. */
7121 if (!SET_SAFE_LJMP(hlua->T)) {
7122 if (lua_type(hlua->T, -1) == LUA_TSTRING)
7123 error = lua_tostring(hlua->T, -1);
7124 else
7125 error = "critical error";
7126 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
7127 goto error;
7128 }
7129
7130 /* Check stack available size. */
7131 if (!lua_checkstack(hlua->T, 2)) {
7132 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7133 goto error;
7134 }
7135
7136 /* Restore the function in the stack. */
7137 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
7138
7139 /* Once the arguments parsed, the CLI is like an AppletTCP,
7140 * so push AppletTCP in the stack.
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007141 */
7142 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
7143 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7144 goto error;
7145 }
7146 hlua->nargs = 1;
7147
7148 /* push keywords in the stack. */
7149 for (i = 0; *args[i]; i++) {
7150 /* Check stack available size. */
7151 if (!lua_checkstack(hlua->T, 1)) {
7152 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
7153 goto error;
7154 }
7155 lua_pushstring(hlua->T, args[i]);
7156 hlua->nargs++;
7157 }
7158
7159 /* We must initialize the execution timeouts. */
7160 hlua->max_time = hlua_timeout_session;
7161
7162 /* At this point the execution is safe. */
7163 RESET_SAFE_LJMP(hlua->T);
7164
7165 /* It's ok */
7166 return 0;
7167
7168 /* It's not ok. */
7169error:
7170 RESET_SAFE_LJMP(hlua->T);
7171 hlua_ctx_destroy(hlua);
Thierry FOURNIER1be34152016-12-17 12:09:51 +01007172 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007173 return 1;
7174}
7175
7176static int hlua_cli_io_handler_fct(struct appctx *appctx)
7177{
7178 struct hlua *hlua;
7179 struct stream_interface *si;
7180 struct hlua_function *fcn;
7181
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007182 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007183 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01007184 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007185
7186 /* If the stream is disconnect or closed, ldo nothing. */
7187 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
7188 return 1;
7189
7190 /* Execute the function. */
7191 switch (hlua_ctx_resume(hlua, 1)) {
7192
7193 /* finished. */
7194 case HLUA_E_OK:
7195 return 1;
7196
7197 /* yield. */
7198 case HLUA_E_AGAIN:
7199 /* We want write. */
7200 if (HLUA_IS_WAKERESWR(hlua))
7201 si_applet_cant_put(si);
7202 /* Set the timeout. */
7203 if (hlua->wake_time != TICK_ETERNITY)
7204 task_schedule(hlua->task, hlua->wake_time);
7205 return 0;
7206
7207 /* finished with error. */
7208 case HLUA_E_ERRMSG:
7209 /* Display log. */
7210 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
7211 fcn->name, lua_tostring(hlua->T, -1));
7212 lua_pop(hlua->T, 1);
7213 return 1;
7214
Thierry Fournierd5b073c2018-05-21 19:42:47 +02007215 case HLUA_E_ETMOUT:
7216 SEND_ERR(NULL, "Lua converter '%s': execution timeout.\n",
7217 fcn->name);
7218 return 1;
7219
7220 case HLUA_E_NOMEM:
7221 SEND_ERR(NULL, "Lua converter '%s': out of memory error.\n",
7222 fcn->name);
7223 return 1;
7224
7225 case HLUA_E_YIELD: /* unexpected */
7226 SEND_ERR(NULL, "Lua converter '%s': yield not allowed.\n",
7227 fcn->name);
7228 return 1;
7229
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007230 case HLUA_E_ERR:
7231 /* Display log. */
7232 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
7233 fcn->name);
7234 return 1;
7235
7236 default:
7237 return 1;
7238 }
7239
7240 return 1;
7241}
7242
7243static void hlua_cli_io_release_fct(struct appctx *appctx)
7244{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007245 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007246 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007247}
7248
7249/* This function is an LUA binding used for registering
7250 * new keywords in the cli. It expects a list of keywords
7251 * which are the "path". It is limited to 5 keywords. A
7252 * description of the command, a function to be executed
7253 * for the parsing and a function for io handlers.
7254 */
7255__LJMP static int hlua_register_cli(lua_State *L)
7256{
7257 struct cli_kw_list *cli_kws;
7258 const char *message;
7259 int ref_io;
7260 int len;
7261 struct hlua_function *fcn;
7262 int index;
7263 int i;
7264
7265 MAY_LJMP(check_args(L, 3, "register_cli"));
7266
7267 /* First argument : an array of maximum 5 keywords. */
7268 if (!lua_istable(L, 1))
7269 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
7270
7271 /* Second argument : string with contextual message. */
7272 message = MAY_LJMP(luaL_checkstring(L, 2));
7273
7274 /* Third and fourth argument : lua function. */
7275 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
7276
7277 /* Allocate and fill the sample fetch keyword struct. */
7278 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
7279 if (!cli_kws)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007280 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007281 fcn = calloc(1, sizeof(*fcn));
7282 if (!fcn)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007283 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007284
7285 /* Fill path. */
7286 index = 0;
7287 lua_pushnil(L);
7288 while(lua_next(L, 1) != 0) {
7289 if (index >= 5)
7290 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
7291 if (lua_type(L, -1) != LUA_TSTRING)
7292 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
7293 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
7294 if (!cli_kws->kw[0].str_kw[index])
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007295 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007296 index++;
7297 lua_pop(L, 1);
7298 }
7299
7300 /* Copy help message. */
7301 cli_kws->kw[0].usage = strdup(message);
7302 if (!cli_kws->kw[0].usage)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007303 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007304
7305 /* Fill fcn io handler. */
7306 len = strlen("<lua.cli>") + 1;
7307 for (i = 0; i < index; i++)
7308 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
7309 fcn->name = calloc(1, len);
7310 if (!fcn->name)
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007311 WILL_LJMP(luaL_error(L, "Lua out of memory error."));
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007312 strncat((char *)fcn->name, "<lua.cli", len);
7313 for (i = 0; i < index; i++) {
7314 strncat((char *)fcn->name, ".", len);
7315 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
7316 }
7317 strncat((char *)fcn->name, ">", len);
7318 fcn->function_ref = ref_io;
7319
7320 /* Fill last entries. */
7321 cli_kws->kw[0].private = fcn;
7322 cli_kws->kw[0].parse = hlua_cli_parse_fct;
7323 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
7324 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
7325
7326 /* Register this new converter */
7327 cli_register_kw(cli_kws);
7328
7329 return 0;
7330}
7331
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007332static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
7333 struct proxy *defpx, const char *file, int line,
7334 char **err, unsigned int *timeout)
7335{
7336 const char *error;
7337
7338 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
7339 if (error && *error != '\0') {
7340 memprintf(err, "%s: invalid timeout", args[0]);
7341 return -1;
7342 }
7343 return 0;
7344}
7345
7346static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
7347 struct proxy *defpx, const char *file, int line,
7348 char **err)
7349{
7350 return hlua_read_timeout(args, section_type, curpx, defpx,
7351 file, line, err, &hlua_timeout_session);
7352}
7353
7354static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
7355 struct proxy *defpx, const char *file, int line,
7356 char **err)
7357{
7358 return hlua_read_timeout(args, section_type, curpx, defpx,
7359 file, line, err, &hlua_timeout_task);
7360}
7361
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007362static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
7363 struct proxy *defpx, const char *file, int line,
7364 char **err)
7365{
7366 return hlua_read_timeout(args, section_type, curpx, defpx,
7367 file, line, err, &hlua_timeout_applet);
7368}
7369
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007370static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
7371 struct proxy *defpx, const char *file, int line,
7372 char **err)
7373{
7374 char *error;
7375
7376 hlua_nb_instruction = strtoll(args[1], &error, 10);
7377 if (*error != '\0') {
7378 memprintf(err, "%s: invalid number", args[0]);
7379 return -1;
7380 }
7381 return 0;
7382}
7383
Willy Tarreau32f61e22015-03-18 17:54:59 +01007384static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
7385 struct proxy *defpx, const char *file, int line,
7386 char **err)
7387{
7388 char *error;
7389
7390 if (*(args[1]) == 0) {
7391 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
7392 return -1;
7393 }
7394 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
7395 if (*error != '\0') {
7396 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
7397 return -1;
7398 }
7399 return 0;
7400}
7401
7402
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007403/* This function is called by the main configuration key "lua-load". It loads and
7404 * execute an lua file during the parsing of the HAProxy configuration file. It is
7405 * the main lua entry point.
7406 *
7407 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
7408 * occured, otherwise it returns 0.
7409 *
7410 * In some error case, LUA set an error message in top of the stack. This function
7411 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007412 *
7413 * This function can fail with an abort() due to an Lua critical error.
7414 * We are in the configuration parsing process of HAProxy, this abort() is
7415 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007416 */
7417static int hlua_load(char **args, int section_type, struct proxy *curpx,
7418 struct proxy *defpx, const char *file, int line,
7419 char **err)
7420{
7421 int error;
7422
7423 /* Just load and compile the file. */
7424 error = luaL_loadfile(gL.T, args[1]);
7425 if (error) {
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007426 memprintf(err, "error in Lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007427 lua_pop(gL.T, 1);
7428 return -1;
7429 }
7430
7431 /* If no syntax error where detected, execute the code. */
7432 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
7433 switch (error) {
7434 case LUA_OK:
7435 break;
7436 case LUA_ERRRUN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007437 memprintf(err, "Lua runtime error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007438 lua_pop(gL.T, 1);
7439 return -1;
7440 case LUA_ERRMEM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007441 memprintf(err, "Lua out of memory error.n");
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007442 return -1;
7443 case LUA_ERRERR:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007444 memprintf(err, "Lua message handler error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007445 lua_pop(gL.T, 1);
7446 return -1;
7447 case LUA_ERRGCMM:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007448 memprintf(err, "Lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007449 lua_pop(gL.T, 1);
7450 return -1;
7451 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007452 memprintf(err, "Lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007453 lua_pop(gL.T, 1);
7454 return -1;
7455 }
7456
7457 return 0;
7458}
7459
7460/* configuration keywords declaration */
7461static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007462 { CFG_GLOBAL, "lua-load", hlua_load },
7463 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7464 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007465 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007466 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007467 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007468 { 0, NULL, NULL },
7469}};
7470
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007471/* This function can fail with an abort() due to an Lua critical error.
7472 * We are in the initialisation process of HAProxy, this abort() is
7473 * tolerated.
7474 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007475int hlua_post_init()
7476{
7477 struct hlua_init_function *init;
7478 const char *msg;
7479 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007480 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007481
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007482 /* Call post initialisation function in safe environement. */
7483 if (!SET_SAFE_LJMP(gL.T)) {
7484 if (lua_type(gL.T, -1) == LUA_TSTRING)
7485 error = lua_tostring(gL.T, -1);
7486 else
7487 error = "critical error";
7488 fprintf(stderr, "Lua post-init: %s.\n", error);
7489 exit(1);
7490 }
7491 hlua_fcn_post_init(gL.T);
7492 RESET_SAFE_LJMP(gL.T);
7493
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007494 list_for_each_entry(init, &hlua_init_functions, l) {
7495 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7496 ret = hlua_ctx_resume(&gL, 0);
7497 switch (ret) {
7498 case HLUA_E_OK:
7499 lua_pop(gL.T, -1);
7500 return 1;
7501 case HLUA_E_AGAIN:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007502 ha_alert("Lua init: yield not allowed.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007503 return 0;
7504 case HLUA_E_ERRMSG:
7505 msg = lua_tostring(gL.T, -1);
Christopher Faulet767a84b2017-11-24 16:50:31 +01007506 ha_alert("lua init: %s.\n", msg);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007507 return 0;
7508 case HLUA_E_ERR:
7509 default:
Thierry FOURNIER2986c0d2018-02-25 14:32:36 +01007510 ha_alert("Lua init: unknown runtime error.\n");
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007511 return 0;
7512 }
7513 }
7514 return 1;
7515}
7516
Willy Tarreau32f61e22015-03-18 17:54:59 +01007517/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7518 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7519 * is the previously allocated size or the kind of object in case of a new
7520 * allocation. <nsize> is the requested new size.
7521 */
7522static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7523{
7524 struct hlua_mem_allocator *zone = ud;
7525
7526 if (nsize == 0) {
7527 /* it's a free */
7528 if (ptr)
7529 zone->allocated -= osize;
7530 free(ptr);
7531 return NULL;
7532 }
7533
7534 if (!ptr) {
7535 /* it's a new allocation */
7536 if (zone->limit && zone->allocated + nsize > zone->limit)
7537 return NULL;
7538
7539 ptr = malloc(nsize);
7540 if (ptr)
7541 zone->allocated += nsize;
7542 return ptr;
7543 }
7544
7545 /* it's a realloc */
7546 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7547 return NULL;
7548
7549 ptr = realloc(ptr, nsize);
7550 if (ptr)
7551 zone->allocated += nsize - osize;
7552 return ptr;
7553}
7554
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007555/* Ithis function can fail with an abort() due to an Lua critical error.
7556 * We are in the initialisation process of HAProxy, this abort() is
7557 * tolerated.
7558 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007559void hlua_init(void)
7560{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007561 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007562 int idx;
7563 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007564 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007565 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007566 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007567#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007568 struct srv_kw *kw;
7569 int tmp_error;
7570 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007571 char *args[] = { /* SSL client configuration. */
7572 "ssl",
7573 "verify",
7574 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007575 NULL
7576 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007577#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007578
Christopher Faulet2a944ee2017-11-07 10:42:54 +01007579 HA_SPIN_INIT(&hlua_global_lock);
Thierry FOURNIER61ba0e22017-07-12 11:41:21 +02007580
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007581 /* Initialise struct hlua and com signals pool */
Willy Tarreaubafbe012017-11-24 17:34:44 +01007582 pool_head_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007583
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007584 /* Register configuration keywords. */
7585 cfg_register_keywords(&cfg_kws);
7586
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007587 /* Init main lua stack. */
7588 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007589 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007590 LIST_INIT(&gL.com);
Willy Tarreau42ef75f2017-04-12 21:40:29 +02007591 gL.T = lua_newstate(hlua_alloc, &hlua_global_allocator);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007592 hlua_sethlua(&gL);
7593 gL.Tref = LUA_REFNIL;
7594 gL.task = NULL;
7595
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007596 /* From this point, until the end of the initialisation fucntion,
7597 * the Lua function can fail with an abort. We are in the initialisation
7598 * process of HAProxy, this abort() is tolerated.
7599 */
7600
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007601 /* Initialise lua. */
7602 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007603
Thierry Fournier75933d42016-01-21 09:30:18 +01007604 /* Set safe environment for the initialisation. */
7605 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007606 if (lua_type(gL.T, -1) == LUA_TSTRING)
7607 error_msg = lua_tostring(gL.T, -1);
7608 else
7609 error_msg = "critical error";
7610 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007611 exit(1);
7612 }
7613
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007614 /*
7615 *
7616 * Create "core" object.
7617 *
7618 */
7619
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007620 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007621 lua_newtable(gL.T);
7622
7623 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007624 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007625 hlua_class_const_int(gL.T, log_levels[i], i);
7626
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007627 /* Register special functions. */
7628 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007629 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007630 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007631 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007632 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007633 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007634 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007635 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007636 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007637 hlua_class_function(gL.T, "sleep", hlua_sleep);
7638 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007639 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7640 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7641 hlua_class_function(gL.T, "set_map", hlua_set_map);
7642 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007643 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007644 hlua_class_function(gL.T, "log", hlua_log);
7645 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7646 hlua_class_function(gL.T, "Info", hlua_log_info);
7647 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7648 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007649 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007650 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007651
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007652 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007653
7654 /*
7655 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007656 * Register class Map
7657 *
7658 */
7659
7660 /* This table entry is the object "Map" base. */
7661 lua_newtable(gL.T);
7662
7663 /* register pattern types. */
7664 for (i=0; i<PAT_MATCH_NUM; i++)
7665 hlua_class_const_int(gL.T, pat_match_names[i], i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007666 for (i=0; i<PAT_MATCH_NUM; i++) {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007667 snprintf(trash.area, trash.size, "_%s", pat_match_names[i]);
7668 hlua_class_const_int(gL.T, trash.area, i);
Thierry FOURNIER4dc71972017-01-28 08:33:08 +01007669 }
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007670
7671 /* register constructor. */
7672 hlua_class_function(gL.T, "new", hlua_map_new);
7673
7674 /* Create and fill the metatable. */
7675 lua_newtable(gL.T);
7676
7677 /* Create and fille the __index entry. */
7678 lua_pushstring(gL.T, "__index");
7679 lua_newtable(gL.T);
7680
7681 /* Register . */
7682 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7683 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7684
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007685 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007686
Thierry Fournier45e78d72016-02-19 18:34:46 +01007687 /* Register previous table in the registry with reference and named entry.
7688 * The function hlua_register_metatable() pops the stack, so we
7689 * previously create a copy of the table.
7690 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007691 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007692 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007693
7694 /* Assign the metatable to the mai Map object. */
7695 lua_setmetatable(gL.T, -2);
7696
7697 /* Set a name to the table. */
7698 lua_setglobal(gL.T, "Map");
7699
7700 /*
7701 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007702 * Register class Channel
7703 *
7704 */
7705
7706 /* Create and fill the metatable. */
7707 lua_newtable(gL.T);
7708
7709 /* Create and fille the __index entry. */
7710 lua_pushstring(gL.T, "__index");
7711 lua_newtable(gL.T);
7712
7713 /* Register . */
7714 hlua_class_function(gL.T, "get", hlua_channel_get);
7715 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7716 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7717 hlua_class_function(gL.T, "set", hlua_channel_set);
7718 hlua_class_function(gL.T, "append", hlua_channel_append);
7719 hlua_class_function(gL.T, "send", hlua_channel_send);
7720 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7721 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7722 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007723 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007724
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007725 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007726
7727 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007728 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007729
7730 /*
7731 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007732 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007733 *
7734 */
7735
7736 /* Create and fill the metatable. */
7737 lua_newtable(gL.T);
7738
7739 /* Create and fille the __index entry. */
7740 lua_pushstring(gL.T, "__index");
7741 lua_newtable(gL.T);
7742
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007743 /* Browse existing fetches and create the associated
7744 * object method.
7745 */
7746 sf = NULL;
7747 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7748
7749 /* Dont register the keywork if the arguments check function are
7750 * not safe during the runtime.
7751 */
7752 if ((sf->val_args != NULL) &&
7753 (sf->val_args != val_payload_lv) &&
7754 (sf->val_args != val_hdr))
7755 continue;
7756
7757 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7758 * by an underscore.
7759 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007760 strncpy(trash.area, sf->kw, trash.size);
7761 trash.area[trash.size - 1] = '\0';
7762 for (p = trash.area; *p; p++)
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007763 if (*p == '.' || *p == '-' || *p == '+')
7764 *p = '_';
7765
7766 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007767 lua_pushstring(gL.T, trash.area);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007768 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007769 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007770 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007771 }
7772
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007773 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007774
7775 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007776 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007777
7778 /*
7779 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007780 * Register class Converters
7781 *
7782 */
7783
7784 /* Create and fill the metatable. */
7785 lua_newtable(gL.T);
7786
7787 /* Create and fill the __index entry. */
7788 lua_pushstring(gL.T, "__index");
7789 lua_newtable(gL.T);
7790
7791 /* Browse existing converters and create the associated
7792 * object method.
7793 */
7794 sc = NULL;
7795 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7796 /* Dont register the keywork if the arguments check function are
7797 * not safe during the runtime.
7798 */
7799 if (sc->val_args != NULL)
7800 continue;
7801
7802 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7803 * by an underscore.
7804 */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007805 strncpy(trash.area, sc->kw, trash.size);
7806 trash.area[trash.size - 1] = '\0';
7807 for (p = trash.area; *p; p++)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007808 if (*p == '.' || *p == '-' || *p == '+')
7809 *p = '_';
7810
7811 /* Register the function. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02007812 lua_pushstring(gL.T, trash.area);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007813 lua_pushlightuserdata(gL.T, sc);
7814 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007815 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007816 }
7817
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007818 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007819
7820 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007821 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007822
7823 /*
7824 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007825 * Register class HTTP
7826 *
7827 */
7828
7829 /* Create and fill the metatable. */
7830 lua_newtable(gL.T);
7831
7832 /* Create and fille the __index entry. */
7833 lua_pushstring(gL.T, "__index");
7834 lua_newtable(gL.T);
7835
7836 /* Register Lua functions. */
7837 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7838 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7839 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7840 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7841 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7842 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7843 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7844 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7845 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7846 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7847
7848 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7849 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7850 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7851 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7852 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7853 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007854 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007855
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007856 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007857
7858 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007859 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007860
7861 /*
7862 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007863 * Register class AppletTCP
7864 *
7865 */
7866
7867 /* Create and fill the metatable. */
7868 lua_newtable(gL.T);
7869
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007870 /* Create and fille the __index entry. */
7871 lua_pushstring(gL.T, "__index");
7872 lua_newtable(gL.T);
7873
7874 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007875 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7876 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7877 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7878 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7879 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007880 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7881 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7882 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007883
7884 lua_settable(gL.T, -3);
7885
7886 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007887 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007888
7889 /*
7890 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007891 * Register class AppletHTTP
7892 *
7893 */
7894
7895 /* Create and fill the metatable. */
7896 lua_newtable(gL.T);
7897
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007898 /* Create and fille the __index entry. */
7899 lua_pushstring(gL.T, "__index");
7900 lua_newtable(gL.T);
7901
7902 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007903 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7904 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007905 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7906 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7907 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007908 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7909 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7910 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7911 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7912 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7913 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7914
7915 lua_settable(gL.T, -3);
7916
7917 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007918 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007919
7920 /*
7921 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007922 * Register class TXN
7923 *
7924 */
7925
7926 /* Create and fill the metatable. */
7927 lua_newtable(gL.T);
7928
7929 /* Create and fille the __index entry. */
7930 lua_pushstring(gL.T, "__index");
7931 lua_newtable(gL.T);
7932
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007933 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007934 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7935 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007936 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007937 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007938 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007939 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007940 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7941 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7942 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007943 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7944 hlua_class_function(gL.T, "log", hlua_txn_log);
7945 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7946 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7947 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7948 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007949
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007950 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007951
7952 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007953 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007954
7955 /*
7956 *
7957 * Register class Socket
7958 *
7959 */
7960
7961 /* Create and fill the metatable. */
7962 lua_newtable(gL.T);
7963
7964 /* Create and fille the __index entry. */
7965 lua_pushstring(gL.T, "__index");
7966 lua_newtable(gL.T);
7967
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007968#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007969 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007970#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007971 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7972 hlua_class_function(gL.T, "send", hlua_socket_send);
7973 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7974 hlua_class_function(gL.T, "close", hlua_socket_close);
7975 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7976 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7977 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7978 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7979
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007980 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007981
7982 /* Register the garbage collector entry. */
7983 lua_pushstring(gL.T, "__gc");
7984 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007985 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007986
7987 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007988 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007989
7990 /* Proxy and server configuration initialisation. */
7991 memset(&socket_proxy, 0, sizeof(socket_proxy));
7992 init_new_proxy(&socket_proxy);
7993 socket_proxy.parent = NULL;
7994 socket_proxy.last_change = now.tv_sec;
7995 socket_proxy.id = "LUA-SOCKET";
7996 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7997 socket_proxy.maxconn = 0;
7998 socket_proxy.accept = NULL;
7999 socket_proxy.options2 |= PR_O2_INDEPSTR;
8000 socket_proxy.srv = NULL;
8001 socket_proxy.conn_retries = 0;
8002 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
8003
8004 /* Init TCP server: unchanged parameters */
8005 memset(&socket_tcp, 0, sizeof(socket_tcp));
8006 socket_tcp.next = NULL;
8007 socket_tcp.proxy = &socket_proxy;
8008 socket_tcp.obj_type = OBJ_TYPE_SERVER;
8009 LIST_INIT(&socket_tcp.actconns);
8010 LIST_INIT(&socket_tcp.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02008011 socket_tcp.priv_conns = NULL;
8012 socket_tcp.idle_conns = NULL;
8013 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008014 socket_tcp.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008015 socket_tcp.last_change = 0;
8016 socket_tcp.id = "LUA-TCP-CONN";
8017 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8018 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8019 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
8020
8021 /* XXX: Copy default parameter from default server,
8022 * but the default server is not initialized.
8023 */
8024 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
8025 socket_tcp.minconn = socket_proxy.defsrv.minconn;
8026 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
8027 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
8028 socket_tcp.onerror = socket_proxy.defsrv.onerror;
8029 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8030 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
8031 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8032 socket_tcp.uweight = socket_proxy.defsrv.iweight;
8033 socket_tcp.iweight = socket_proxy.defsrv.iweight;
8034
8035 socket_tcp.check.status = HCHK_STATUS_INI;
8036 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
8037 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
8038 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
8039 socket_tcp.check.server = &socket_tcp;
8040
8041 socket_tcp.agent.status = HCHK_STATUS_INI;
8042 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
8043 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
8044 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
8045 socket_tcp.agent.server = &socket_tcp;
8046
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008047 socket_tcp.xprt = xprt_get(XPRT_RAW);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008048
8049#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008050 /* Init TCP server: unchanged parameters */
8051 memset(&socket_ssl, 0, sizeof(socket_ssl));
8052 socket_ssl.next = NULL;
8053 socket_ssl.proxy = &socket_proxy;
8054 socket_ssl.obj_type = OBJ_TYPE_SERVER;
8055 LIST_INIT(&socket_ssl.actconns);
8056 LIST_INIT(&socket_ssl.pendconns);
Christopher Faulet40a007c2017-07-03 15:41:01 +02008057 socket_tcp.priv_conns = NULL;
8058 socket_tcp.idle_conns = NULL;
8059 socket_tcp.safe_conns = NULL;
Emeric Brun52a91d32017-08-31 14:41:55 +02008060 socket_ssl.next_state = SRV_ST_RUNNING; /* early server setup */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008061 socket_ssl.last_change = 0;
8062 socket_ssl.id = "LUA-SSL-CONN";
8063 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8064 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
8065 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
8066
8067 /* XXX: Copy default parameter from default server,
8068 * but the default server is not initialized.
8069 */
8070 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
8071 socket_ssl.minconn = socket_proxy.defsrv.minconn;
8072 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
8073 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
8074 socket_ssl.onerror = socket_proxy.defsrv.onerror;
8075 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
8076 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
8077 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
8078 socket_ssl.uweight = socket_proxy.defsrv.iweight;
8079 socket_ssl.iweight = socket_proxy.defsrv.iweight;
8080
8081 socket_ssl.check.status = HCHK_STATUS_INI;
8082 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
8083 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
8084 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
8085 socket_ssl.check.server = &socket_ssl;
8086
8087 socket_ssl.agent.status = HCHK_STATUS_INI;
8088 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
8089 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
8090 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
8091 socket_ssl.agent.server = &socket_ssl;
8092
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008093 socket_ssl.use_ssl = 1;
Willy Tarreaua261e9b2016-12-22 20:44:00 +01008094 socket_ssl.xprt = xprt_get(XPRT_SSL);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008095
Thierry FOURNIER36d13742015-03-17 16:48:53 +01008096 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008097 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
8098 /*
8099 *
8100 * If the keyword is not known, we can search in the registered
8101 * server keywords. This is usefull to configure special SSL
8102 * features like client certificates and ssl_verify.
8103 *
8104 */
8105 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
8106 if (tmp_error != 0) {
8107 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
8108 abort(); /* This must be never arrives because the command line
8109 not editable by the user. */
8110 }
8111 idx += kw->skip;
8112 }
8113 }
8114
8115 /* Initialize SSL server. */
Willy Tarreaucbe6da52018-05-18 17:08:28 +02008116 if (socket_ssl.xprt->prepare_srv) {
8117 int saved_used_backed = global.ssl_used_backend;
8118 // don't affect maxconn automatic computation
Willy Tarreau17d45382016-12-22 21:16:08 +01008119 socket_ssl.xprt->prepare_srv(&socket_ssl);
Willy Tarreaucbe6da52018-05-18 17:08:28 +02008120 global.ssl_used_backend = saved_used_backed;
8121 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01008122#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01008123
8124 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01008125}
Willy Tarreaubb57d942016-12-21 19:04:56 +01008126
8127__attribute__((constructor))
8128static void __hlua_init(void)
8129{
8130 char *ptr = NULL;
8131 memprintf(&ptr, "Built with Lua version : %s", LUA_RELEASE);
8132 hap_register_build_opts(ptr, 1);
8133}