blob: 2621ba6bae638dde2a99e8922ab190ca2c3c3443 [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>
Thierry FOURNIERbabae282015-09-17 11:36:37 +020014#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +010015
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010016#include <lauxlib.h>
17#include <lua.h>
18#include <lualib.h>
19
Thierry FOURNIER463119c2015-03-10 00:35:36 +010020#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
21#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010022#endif
23
Thierry FOURNIER380d0932015-01-23 14:27:52 +010024#include <ebpttree.h>
25
26#include <common/cfgparse.h>
27
William Lallemand9ed62032016-11-21 17:49:11 +010028#include <types/cli.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010029#include <types/hlua.h>
30#include <types/proxy.h>
William Lallemand9ed62032016-11-21 17:49:11 +010031#include <types/stats.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010032
Thierry FOURNIER55da1652015-01-23 11:36:30 +010033#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020034#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010035#include <proto/channel.h>
William Lallemand9ed62032016-11-21 17:49:11 +010036#include <proto/cli.h>
Willy Tarreaua71f6422016-11-16 17:00:14 +010037#include <proto/connection.h>
William Lallemand9ed62032016-11-21 17:49:11 +010038#include <proto/stats.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010039#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010040#include <proto/hlua.h>
Thierry Fournierfb0b5462016-01-21 09:28:58 +010041#include <proto/hlua_fcn.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020042#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010043#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010044#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010045#include <proto/payload.h>
46#include <proto/proto_http.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010047#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010048#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010049#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020050#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020051#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010052#include <proto/ssl_sock.h>
53#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010054#include <proto/task.h>
Willy Tarreau39713102016-11-25 15:49:32 +010055#include <proto/tcp_rules.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020056#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010057
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010058/* Lua uses longjmp to perform yield or throwing errors. This
59 * macro is used only for identifying the function that can
60 * not return because a longjmp is executed.
61 * __LJMP marks a prototype of hlua file that can use longjmp.
62 * WILL_LJMP() marks an lua function that will use longjmp.
63 * MAY_LJMP() marks an lua function that may use longjmp.
64 */
65#define __LJMP
66#define WILL_LJMP(func) func
67#define MAY_LJMP(func) func
68
Thierry FOURNIERbabae282015-09-17 11:36:37 +020069/* This couple of function executes securely some Lua calls outside of
70 * the lua runtime environment. Each Lua call can return a longjmp
71 * if it encounter a memory error.
72 *
73 * Lua documentation extract:
74 *
75 * If an error happens outside any protected environment, Lua calls
76 * a panic function (see lua_atpanic) and then calls abort, thus
77 * exiting the host application. Your panic function can avoid this
78 * exit by never returning (e.g., doing a long jump to your own
79 * recovery point outside Lua).
80 *
81 * The panic function runs as if it were a message handler (see
82 * §2.3); in particular, the error message is at the top of the
83 * stack. However, there is no guarantee about stack space. To push
84 * anything on the stack, the panic function must first check the
85 * available space (see §4.2).
86 *
87 * We must check all the Lua entry point. This includes:
88 * - The include/proto/hlua.h exported functions
89 * - the task wrapper function
90 * - The action wrapper function
91 * - The converters wrapper function
92 * - The sample-fetch wrapper functions
93 *
94 * It is tolerated that the initilisation function returns an abort.
95 * Before each Lua abort, an error message is writed on stderr.
96 *
97 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
98 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
99 * because they must be exists in the program stack when the longjmp
100 * is called.
101 */
102jmp_buf safe_ljmp_env;
103static int hlua_panic_safe(lua_State *L) { return 0; }
104static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
105
106#define SET_SAFE_LJMP(__L) \
107 ({ \
108 int ret; \
109 if (setjmp(safe_ljmp_env) != 0) { \
110 lua_atpanic(__L, hlua_panic_safe); \
111 ret = 0; \
112 } else { \
113 lua_atpanic(__L, hlua_panic_ljmp); \
114 ret = 1; \
115 } \
116 ret; \
117 })
118
119/* If we are the last function catching Lua errors, we
120 * must reset the panic function.
121 */
122#define RESET_SAFE_LJMP(__L) \
123 do { \
124 lua_atpanic(__L, hlua_panic_safe); \
125 } while(0)
126
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200127/* Applet status flags */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200128#define APPLET_DONE 0x01 /* applet processing is done. */
129#define APPLET_100C 0x02 /* 100 continue expected. */
130#define APPLET_HDR_SENT 0x04 /* Response header sent. */
131#define APPLET_CHUNKED 0x08 /* Use transfer encoding chunked. */
132#define APPLET_LAST_CHK 0x10 /* Last chunk sent. */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +0100133#define APPLET_HTTP11 0x20 /* Last chunk sent. */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200134
135#define HTTP_100C "HTTP/1.1 100 Continue\r\n\r\n"
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200136
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100137/* The main Lua execution context. */
138struct hlua gL;
139
Thierry FOURNIERebed6e92016-12-16 11:54:07 +0100140/* This is the memory pool containing struct lua for applets
141 * (including cli).
142 */
143struct pool_head *pool2_hlua;
144
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100145/* This is the memory pool containing all the signal structs. These
146 * struct are used to store each requiered signal between two tasks.
147 */
148struct pool_head *pool2_hlua_com;
149
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100150/* Used for Socket connection. */
151static struct proxy socket_proxy;
152static struct server socket_tcp;
153#ifdef USE_OPENSSL
154static struct server socket_ssl;
155#endif
156
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100157/* List head of the function called at the initialisation time. */
158struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
159
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100160/* The following variables contains the reference of the different
161 * Lua classes. These references are useful for identify metadata
162 * associated with an object.
163 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100164static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100165static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100166static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100167static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100168static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100169static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200170static int class_map_ref;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200171static int class_applet_tcp_ref;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200172static int class_applet_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100173
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100174/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200175 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100176 * short timeout. Lua linked with tasks doesn't have a timeout
177 * because a task may remain alive during all the haproxy execution.
178 */
179static unsigned int hlua_timeout_session = 4000; /* session timeout. */
180static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +0200181static unsigned int hlua_timeout_applet = 4000; /* applet timeout. */
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100182
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100183/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
184 * it is used for preventing infinite loops.
185 *
186 * I test the scheer with an infinite loop containing one incrementation
187 * and one test. I run this loop between 10 seconds, I raise a ceil of
188 * 710M loops from one interrupt each 9000 instructions, so I fix the value
189 * to one interrupt each 10 000 instructions.
190 *
191 * configured | Number of
192 * instructions | loops executed
193 * between two | in milions
194 * forced yields |
195 * ---------------+---------------
196 * 10 | 160
197 * 500 | 670
198 * 1000 | 680
199 * 5000 | 700
200 * 7000 | 700
201 * 8000 | 700
202 * 9000 | 710 <- ceil
203 * 10000 | 710
204 * 100000 | 710
205 * 1000000 | 710
206 *
207 */
208static unsigned int hlua_nb_instruction = 10000;
209
Willy Tarreau32f61e22015-03-18 17:54:59 +0100210/* Descriptor for the memory allocation state. If limit is not null, it will
211 * be enforced on any memory allocation.
212 */
213struct hlua_mem_allocator {
214 size_t allocated;
215 size_t limit;
216};
217
218static struct hlua_mem_allocator hlua_global_allocator;
219
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200220static const char error_500[] =
221 "HTTP/1.0 500 Server Error\r\n"
222 "Cache-Control: no-cache\r\n"
223 "Connection: close\r\n"
224 "Content-Type: text/html\r\n"
225 "\r\n"
226 "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n";
227
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100228/* These functions converts types between HAProxy internal args or
229 * sample and LUA types. Another function permits to check if the
230 * LUA stack contains arguments according with an required ARG_T
231 * format.
232 */
233static int hlua_arg2lua(lua_State *L, const struct arg *arg);
234static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100235__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100236 uint64_t mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100237static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100238static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100239static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
240
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200241__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg);
242
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200243#define SEND_ERR(__be, __fmt, __args...) \
244 do { \
245 send_log(__be, LOG_ERR, __fmt, ## __args); \
246 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
247 Alert(__fmt, ## __args); \
248 } while (0)
249
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100250/* Used to check an Lua function type in the stack. It creates and
251 * returns a reference of the function. This function throws an
252 * error if the rgument is not a "function".
253 */
254__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
255{
256 if (!lua_isfunction(L, argno)) {
257 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
258 WILL_LJMP(luaL_argerror(L, argno, msg));
259 }
260 lua_pushvalue(L, argno);
261 return luaL_ref(L, LUA_REGISTRYINDEX);
262}
263
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +0200264/* Return the string that is of the top of the stack. */
265const char *hlua_get_top_error_string(lua_State *L)
266{
267 if (lua_gettop(L) < 1)
268 return "unknown error";
269 if (lua_type(L, -1) != LUA_TSTRING)
270 return "unknown error";
271 return lua_tostring(L, -1);
272}
273
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100274/* This function check the number of arguments available in the
275 * stack. If the number of arguments available is not the same
276 * then <nb> an error is throwed.
277 */
278__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
279{
280 if (lua_gettop(L) == nb)
281 return;
282 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
283}
284
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100285/* This fucntion push an error string prefixed by the file name
286 * and the line number where the error is encountered.
287 */
288static int hlua_pusherror(lua_State *L, const char *fmt, ...)
289{
290 va_list argp;
291 va_start(argp, fmt);
292 luaL_where(L, 1);
293 lua_pushvfstring(L, fmt, argp);
294 va_end(argp);
295 lua_concat(L, 2);
296 return 1;
297}
298
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100299/* This function register a new signal. "lua" is the current lua
300 * execution context. It contains a pointer to the associated task.
301 * "link" is a list head attached to an other task that must be wake
302 * the lua task if an event occurs. This is useful with external
303 * events like TCP I/O or sleep functions. This funcion allocate
304 * memory for the signal.
305 */
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100306static struct hlua_com *hlua_com_new(struct list *purge, struct list *event, struct task *wakeup)
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100307{
308 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
309 if (!com)
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100310 return NULL;
311 LIST_ADDQ(purge, &com->purge_me);
312 LIST_ADDQ(event, &com->wake_me);
313 com->task = wakeup;
314 return com;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100315}
316
317/* This function purge all the pending signals when the LUA execution
318 * is finished. This prevent than a coprocess try to wake a deleted
319 * task. This function remove the memory associated to the signal.
320 */
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100321static void hlua_com_purge(struct list *purge)
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100322{
323 struct hlua_com *com, *back;
324
325 /* Delete all pending communication signals. */
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100326 list_for_each_entry_safe(com, back, purge, purge_me) {
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100327 LIST_DEL(&com->purge_me);
328 LIST_DEL(&com->wake_me);
329 pool_free2(pool2_hlua_com, com);
330 }
331}
332
333/* This function sends signals. It wakes all the tasks attached
334 * to a list head, and remove the signal, and free the used
335 * memory.
336 */
337static void hlua_com_wake(struct list *wake)
338{
339 struct hlua_com *com, *back;
340
341 /* Wake task and delete all pending communication signals. */
342 list_for_each_entry_safe(com, back, wake, wake_me) {
343 LIST_DEL(&com->purge_me);
344 LIST_DEL(&com->wake_me);
345 task_wakeup(com->task, TASK_WOKEN_MSG);
346 pool_free2(pool2_hlua_com, com);
347 }
348}
349
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100350/* This functions is used with sample fetch and converters. It
351 * converts the HAProxy configuration argument in a lua stack
352 * values.
353 *
354 * It takes an array of "arg", and each entry of the array is
355 * converted and pushed in the LUA stack.
356 */
357static int hlua_arg2lua(lua_State *L, const struct arg *arg)
358{
359 switch (arg->type) {
360 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100361 case ARGT_TIME:
362 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100363 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100364 break;
365
366 case ARGT_STR:
367 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
368 break;
369
370 case ARGT_IPV4:
371 case ARGT_IPV6:
372 case ARGT_MSK4:
373 case ARGT_MSK6:
374 case ARGT_FE:
375 case ARGT_BE:
376 case ARGT_TAB:
377 case ARGT_SRV:
378 case ARGT_USR:
379 case ARGT_MAP:
380 default:
381 lua_pushnil(L);
382 break;
383 }
384 return 1;
385}
386
387/* This function take one entrie in an LUA stack at the index "ud",
388 * and try to convert it in an HAProxy argument entry. This is useful
389 * with sample fetch wrappers. The input arguments are gived to the
390 * lua wrapper and converted as arg list by thi function.
391 */
392static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
393{
394 switch (lua_type(L, ud)) {
395
396 case LUA_TNUMBER:
397 case LUA_TBOOLEAN:
398 arg->type = ARGT_SINT;
399 arg->data.sint = lua_tointeger(L, ud);
400 break;
401
402 case LUA_TSTRING:
403 arg->type = ARGT_STR;
404 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
405 break;
406
407 case LUA_TUSERDATA:
408 case LUA_TNIL:
409 case LUA_TTABLE:
410 case LUA_TFUNCTION:
411 case LUA_TTHREAD:
412 case LUA_TLIGHTUSERDATA:
413 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200414 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100415 break;
416 }
417 return 1;
418}
419
420/* the following functions are used to convert a struct sample
421 * in Lua type. This useful to convert the return of the
422 * fetchs or converters.
423 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100424static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100425{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200426 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100427 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100428 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200429 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100430 break;
431
432 case SMP_T_BIN:
433 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200434 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100435 break;
436
437 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200438 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100439 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
440 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
441 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
442 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
443 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
444 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
445 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
446 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
447 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200448 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100449 break;
450 default:
451 lua_pushnil(L);
452 break;
453 }
454 break;
455
456 case SMP_T_IPV4:
457 case SMP_T_IPV6:
458 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200459 if (sample_casts[smp->data.type][SMP_T_STR] &&
460 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200461 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100462 else
463 lua_pushnil(L);
464 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100465 default:
466 lua_pushnil(L);
467 break;
468 }
469 return 1;
470}
471
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100472/* the following functions are used to convert a struct sample
473 * in Lua strings. This is useful to convert the return of the
474 * fetchs or converters.
475 */
476static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
477{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200478 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100479
480 case SMP_T_BIN:
481 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200482 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100483 break;
484
485 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200486 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100487 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
488 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
489 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
490 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
491 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
492 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
493 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
494 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
495 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200496 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100497 break;
498 default:
499 lua_pushstring(L, "");
500 break;
501 }
502 break;
503
504 case SMP_T_SINT:
505 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100506 case SMP_T_IPV4:
507 case SMP_T_IPV6:
508 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200509 if (sample_casts[smp->data.type][SMP_T_STR] &&
510 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200511 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100512 else
513 lua_pushstring(L, "");
514 break;
515 default:
516 lua_pushstring(L, "");
517 break;
518 }
519 return 1;
520}
521
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100522/* the following functions are used to convert an Lua type in a
523 * struct sample. This is useful to provide data from a converter
524 * to the LUA code.
525 */
526static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
527{
528 switch (lua_type(L, ud)) {
529
530 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200531 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200532 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100533 break;
534
535
536 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200537 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200538 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100539 break;
540
541 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200542 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100543 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200544 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100545 break;
546
547 case LUA_TUSERDATA:
548 case LUA_TNIL:
549 case LUA_TTABLE:
550 case LUA_TFUNCTION:
551 case LUA_TTHREAD:
552 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200553 case LUA_TNONE:
554 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200555 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200556 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100557 break;
558 }
559 return 1;
560}
561
562/* This function check the "argp" builded by another conversion function
563 * is in accord with the expected argp defined by the "mask". The fucntion
564 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100565 *
566 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
567 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100568 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100569__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
David Carlier0c437f42016-04-27 16:21:56 +0100570 uint64_t mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100571{
572 int min_arg;
573 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100574 struct proxy *px;
575 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100576
577 idx = 0;
578 min_arg = ARGM(mask);
579 mask >>= ARGM_BITS;
580
581 while (1) {
582
583 /* Check oversize. */
584 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100585 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100586 }
587
588 /* Check for mandatory arguments. */
589 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100590 if (idx < min_arg) {
591
592 /* If miss other argument than the first one, we return an error. */
593 if (idx > 0)
594 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
595
596 /* If first argument have a certain type, some default values
597 * may be used. See the function smp_resolve_args().
598 */
599 switch (mask & ARGT_MASK) {
600
601 case ARGT_FE:
602 if (!(p->cap & PR_CAP_FE))
603 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
604 argp[idx].data.prx = p;
605 argp[idx].type = ARGT_FE;
606 argp[idx+1].type = ARGT_STOP;
607 break;
608
609 case ARGT_BE:
610 if (!(p->cap & PR_CAP_BE))
611 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
612 argp[idx].data.prx = p;
613 argp[idx].type = ARGT_BE;
614 argp[idx+1].type = ARGT_STOP;
615 break;
616
617 case ARGT_TAB:
618 argp[idx].data.prx = p;
619 argp[idx].type = ARGT_TAB;
620 argp[idx+1].type = ARGT_STOP;
621 break;
622
623 default:
624 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
625 break;
626 }
627 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100628 return 0;
629 }
630
631 /* Check for exceed the number of requiered argument. */
632 if ((mask & ARGT_MASK) == ARGT_STOP &&
633 argp[idx].type != ARGT_STOP) {
634 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
635 }
636
637 if ((mask & ARGT_MASK) == ARGT_STOP &&
638 argp[idx].type == ARGT_STOP) {
639 return 0;
640 }
641
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100642 /* Convert some argument types. */
643 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100644 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100645 if (argp[idx].type != ARGT_SINT)
646 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
647 argp[idx].type = ARGT_SINT;
648 break;
649
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100650 case ARGT_TIME:
651 if (argp[idx].type != ARGT_SINT)
652 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200653 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100654 break;
655
656 case ARGT_SIZE:
657 if (argp[idx].type != ARGT_SINT)
658 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200659 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100660 break;
661
662 case ARGT_FE:
663 if (argp[idx].type != ARGT_STR)
664 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
665 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
666 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200667 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100668 if (!argp[idx].data.prx)
669 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
670 argp[idx].type = ARGT_FE;
671 break;
672
673 case ARGT_BE:
674 if (argp[idx].type != ARGT_STR)
675 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
676 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
677 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200678 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100679 if (!argp[idx].data.prx)
680 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
681 argp[idx].type = ARGT_BE;
682 break;
683
684 case ARGT_TAB:
685 if (argp[idx].type != ARGT_STR)
686 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
687 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
688 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200689 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100690 if (!argp[idx].data.prx)
691 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
692 argp[idx].type = ARGT_TAB;
693 break;
694
695 case ARGT_SRV:
696 if (argp[idx].type != ARGT_STR)
697 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
698 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
699 trash.str[argp[idx].data.str.len] = 0;
700 sname = strrchr(trash.str, '/');
701 if (sname) {
702 *sname++ = '\0';
703 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200704 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100705 if (!px)
706 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
707 }
708 else {
709 sname = trash.str;
710 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100711 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100712 argp[idx].data.srv = findserver(px, sname);
713 if (!argp[idx].data.srv)
714 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
715 argp[idx].type = ARGT_SRV;
716 break;
717
718 case ARGT_IPV4:
719 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
720 trash.str[argp[idx].data.str.len] = 0;
721 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
722 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
723 argp[idx].type = ARGT_IPV4;
724 break;
725
726 case ARGT_MSK4:
727 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
728 trash.str[argp[idx].data.str.len] = 0;
729 if (!str2mask(trash.str, &argp[idx].data.ipv4))
730 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
731 argp[idx].type = ARGT_MSK4;
732 break;
733
734 case ARGT_IPV6:
735 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
736 trash.str[argp[idx].data.str.len] = 0;
737 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
738 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
739 argp[idx].type = ARGT_IPV6;
740 break;
741
742 case ARGT_MSK6:
743 case ARGT_MAP:
744 case ARGT_REG:
745 case ARGT_USR:
746 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100747 break;
748 }
749
750 /* Check for type of argument. */
751 if ((mask & ARGT_MASK) != argp[idx].type) {
752 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
753 arg_type_names[(mask & ARGT_MASK)],
754 arg_type_names[argp[idx].type & ARGT_MASK]);
755 WILL_LJMP(luaL_argerror(L, first + idx, msg));
756 }
757
758 /* Next argument. */
759 mask >>= ARGT_BITS;
760 idx++;
761 }
762}
763
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100764/*
765 * The following functions are used to make correspondance between the the
766 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100767 *
768 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100769 * - hlua_sethlua : create the association between hlua context and lua_state.
770 */
771static inline struct hlua *hlua_gethlua(lua_State *L)
772{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100773 struct hlua **hlua = lua_getextraspace(L);
774 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100775}
776static inline void hlua_sethlua(struct hlua *hlua)
777{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100778 struct hlua **hlua_store = lua_getextraspace(hlua->T);
779 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100780}
781
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100782/* This function is used to send logs. It try to send on screen (stderr)
783 * and on the default syslog server.
784 */
785static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
786{
787 struct tm tm;
788 char *p;
789
790 /* Cleanup the log message. */
791 p = trash.str;
792 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200793 if (p >= trash.str + trash.size - 1) {
794 /* Break the message if exceed the buffer size. */
795 *(p-4) = ' ';
796 *(p-3) = '.';
797 *(p-2) = '.';
798 *(p-1) = '.';
799 break;
800 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100801 if (isprint(*msg))
802 *p = *msg;
803 else
804 *p = '.';
805 }
806 *p = '\0';
807
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200808 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100809 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200810 get_localtime(date.tv_sec, &tm);
811 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100812 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
813 (int)getpid(), trash.str);
814 fflush(stderr);
815 }
816}
817
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100818/* This function just ensure that the yield will be always
819 * returned with a timeout and permit to set some flags
820 */
821__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100822 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100823{
824 struct hlua *hlua = hlua_gethlua(L);
825
826 /* Set the wake timeout. If timeout is required, we set
827 * the expiration time.
828 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200829 hlua->wake_time = timeout;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100830
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100831 hlua->flags |= flags;
832
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100833 /* Process the yield. */
834 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
835}
836
Willy Tarreau87b09662015-04-03 00:22:06 +0200837/* This function initialises the Lua environment stored in the stream.
838 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100839 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200840 *
841 * This function is particular. it initialises a new Lua thread. If the
842 * initialisation fails (example: out of memory error), the lua function
843 * throws an error (longjmp).
844 *
845 * This function manipulates two Lua stack: the main and the thread. Only
846 * the main stack can fail. The thread is not manipulated. This function
847 * MUST NOT manipulate the created thread stack state, because is not
848 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100849 */
850int hlua_ctx_init(struct hlua *lua, struct task *task)
851{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200852 if (!SET_SAFE_LJMP(gL.T)) {
853 lua->Tref = LUA_REFNIL;
854 return 0;
855 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100856 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100857 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100858 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100859 lua->T = lua_newthread(gL.T);
860 if (!lua->T) {
861 lua->Tref = LUA_REFNIL;
862 return 0;
863 }
864 hlua_sethlua(lua);
865 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
866 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200867 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100868 return 1;
869}
870
Willy Tarreau87b09662015-04-03 00:22:06 +0200871/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100872 * is destroyed. The destroy also the memory context. The struct "lua"
873 * is not freed.
874 */
875void hlua_ctx_destroy(struct hlua *lua)
876{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100877 if (!lua->T)
878 return;
879
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100880 /* Purge all the pending signals. */
Thierry FOURNIER847ca662016-12-16 13:07:22 +0100881 hlua_com_purge(&lua->com);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100882
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100883 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
884 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200885
886 /* Forces a garbage collecting process. If the Lua program is finished
887 * without error, we run the GC on the thread pointer. Its freed all
888 * the unused memory.
889 * If the thread is finnish with an error or is currently yielded,
890 * it seems that the GC applied on the thread doesn't clean anything,
891 * so e run the GC on the main thread.
892 * NOTE: maybe this action locks all the Lua threads untiml the en of
893 * the garbage collection.
894 */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +0200895 if (lua->flags & HLUA_MUST_GC) {
896 lua_gc(lua->T, LUA_GCCOLLECT, 0);
897 if (lua_status(lua->T) != LUA_OK)
898 lua_gc(gL.T, LUA_GCCOLLECT, 0);
899 }
Thierry FOURNIER5a50a852015-09-23 16:59:28 +0200900
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200901 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100902}
903
904/* This function is used to restore the Lua context when a coroutine
905 * fails. This function copy the common memory between old coroutine
906 * and the new coroutine. The old coroutine is destroyed, and its
907 * replaced by the new coroutine.
908 * If the flag "keep_msg" is set, the last entry of the old is assumed
909 * as string error message and it is copied in the new stack.
910 */
911static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
912{
913 lua_State *T;
914 int new_ref;
915
916 /* Renew the main LUA stack doesn't have sense. */
917 if (lua == &gL)
918 return 0;
919
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100920 /* New Lua coroutine. */
921 T = lua_newthread(gL.T);
922 if (!T)
923 return 0;
924
925 /* Copy last error message. */
926 if (keep_msg)
927 lua_xmove(lua->T, T, 1);
928
929 /* Copy data between the coroutines. */
930 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
931 lua_xmove(lua->T, T, 1);
932 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
933
934 /* Destroy old data. */
935 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
936
937 /* The thread is garbage collected by Lua. */
938 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
939
940 /* Fill the struct with the new coroutine values. */
941 lua->Mref = new_ref;
942 lua->T = T;
943 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
944
945 /* Set context. */
946 hlua_sethlua(lua);
947
948 return 1;
949}
950
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100951void hlua_hook(lua_State *L, lua_Debug *ar)
952{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100953 struct hlua *hlua = hlua_gethlua(L);
954
955 /* Lua cannot yield when its returning from a function,
956 * so, we can fix the interrupt hook to 1 instruction,
957 * expecting that the function is finnished.
958 */
959 if (lua_gethookmask(L) & LUA_MASKRET) {
960 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
961 return;
962 }
963
964 /* restore the interrupt condition. */
965 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
966
967 /* If we interrupt the Lua processing in yieldable state, we yield.
968 * If the state is not yieldable, trying yield causes an error.
969 */
970 if (lua_isyieldable(L))
971 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
972
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100973 /* If we cannot yield, update the clock and check the timeout. */
974 tv_update_date(0, 1);
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200975 hlua->run_time += now_ms - hlua->start_time;
976 if (hlua->max_time && hlua->run_time >= hlua->max_time) {
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100977 lua_pushfstring(L, "execution timeout");
978 WILL_LJMP(lua_error(L));
979 }
980
Thierry FOURNIER10770fa2015-09-29 01:59:42 +0200981 /* Update the start time. */
982 hlua->start_time = now_ms;
983
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100984 /* Try to interrupt the process at the end of the current
985 * unyieldable function.
986 */
987 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100988}
989
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100990/* This function start or resumes the Lua stack execution. If the flag
991 * "yield_allowed" if no set and the LUA stack execution returns a yield
992 * The function return an error.
993 *
994 * The function can returns 4 values:
995 * - HLUA_E_OK : The execution is terminated without any errors.
996 * - HLUA_E_AGAIN : The execution must continue at the next associated
997 * task wakeup.
998 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
999 * the top of the stack.
1000 * - HLUA_E_ERR : An error has occured without error message.
1001 *
1002 * If an error occured, the stack is renewed and it is ready to run new
1003 * LUA code.
1004 */
1005static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1006{
1007 int ret;
1008 const char *msg;
1009
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001010 /* Initialise run time counter. */
1011 if (!HLUA_IS_RUNNING(lua))
1012 lua->run_time = 0;
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001013
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001014resume_execution:
1015
1016 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1017 * instructions. it is used for preventing infinite loops.
1018 */
1019 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1020
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001021 /* Remove all flags except the running flags. */
Thierry FOURNIER2f3867f2015-09-28 01:02:01 +02001022 HLUA_SET_RUN(lua);
1023 HLUA_CLR_CTRLYIELD(lua);
1024 HLUA_CLR_WAKERESWR(lua);
1025 HLUA_CLR_WAKEREQWR(lua);
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001026
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001027 /* Update the start time. */
1028 lua->start_time = now_ms;
1029
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001030 /* Call the function. */
1031 ret = lua_resume(lua->T, gL.T, lua->nargs);
1032 switch (ret) {
1033
1034 case LUA_OK:
1035 ret = HLUA_E_OK;
1036 break;
1037
1038 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001039 /* Check if the execution timeout is expired. It it is the case, we
1040 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001041 */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02001042 tv_update_date(0, 1);
1043 lua->run_time += now_ms - lua->start_time;
1044 if (lua->max_time && lua->run_time > lua->max_time) {
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001045 lua_settop(lua->T, 0); /* Empty the stack. */
1046 if (!lua_checkstack(lua->T, 1)) {
1047 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001048 break;
1049 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001050 lua_pushfstring(lua->T, "execution timeout");
1051 ret = HLUA_E_ERRMSG;
1052 break;
1053 }
1054 /* Process the forced yield. if the general yield is not allowed or
1055 * if no task were associated this the current Lua execution
1056 * coroutine, we resume the execution. Else we want to return in the
1057 * scheduler and we want to be waked up again, to continue the
1058 * current Lua execution. So we schedule our own task.
1059 */
1060 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001061 if (!yield_allowed || !lua->task)
1062 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001063 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001064 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001065 if (!yield_allowed) {
1066 lua_settop(lua->T, 0); /* Empty the stack. */
1067 if (!lua_checkstack(lua->T, 1)) {
1068 ret = HLUA_E_ERR;
1069 break;
1070 }
1071 lua_pushfstring(lua->T, "yield not allowed");
1072 ret = HLUA_E_ERRMSG;
1073 break;
1074 }
1075 ret = HLUA_E_AGAIN;
1076 break;
1077
1078 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001079
1080 /* Special exit case. The traditionnal exit is returned as an error
1081 * because the errors ares the only one mean to return immediately
1082 * from and lua execution.
1083 */
1084 if (lua->flags & HLUA_EXIT) {
1085 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001086 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001087 break;
1088 }
1089
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001090 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001091 if (!lua_checkstack(lua->T, 1)) {
1092 ret = HLUA_E_ERR;
1093 break;
1094 }
1095 msg = lua_tostring(lua->T, -1);
1096 lua_settop(lua->T, 0); /* Empty the stack. */
1097 lua_pop(lua->T, 1);
1098 if (msg)
1099 lua_pushfstring(lua->T, "runtime error: %s", msg);
1100 else
1101 lua_pushfstring(lua->T, "unknown runtime error");
1102 ret = HLUA_E_ERRMSG;
1103 break;
1104
1105 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001106 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001107 lua_settop(lua->T, 0); /* Empty the stack. */
1108 if (!lua_checkstack(lua->T, 1)) {
1109 ret = HLUA_E_ERR;
1110 break;
1111 }
1112 lua_pushfstring(lua->T, "out of memory error");
1113 ret = HLUA_E_ERRMSG;
1114 break;
1115
1116 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001117 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001118 if (!lua_checkstack(lua->T, 1)) {
1119 ret = HLUA_E_ERR;
1120 break;
1121 }
1122 msg = lua_tostring(lua->T, -1);
1123 lua_settop(lua->T, 0); /* Empty the stack. */
1124 lua_pop(lua->T, 1);
1125 if (msg)
1126 lua_pushfstring(lua->T, "message handler error: %s", msg);
1127 else
1128 lua_pushfstring(lua->T, "message handler error");
1129 ret = HLUA_E_ERRMSG;
1130 break;
1131
1132 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001133 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001134 lua_settop(lua->T, 0); /* Empty the stack. */
1135 if (!lua_checkstack(lua->T, 1)) {
1136 ret = HLUA_E_ERR;
1137 break;
1138 }
1139 lua_pushfstring(lua->T, "unknonwn error");
1140 ret = HLUA_E_ERRMSG;
1141 break;
1142 }
1143
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001144 /* This GC permits to destroy some object when a Lua timeout strikes. */
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02001145 if (lua->flags & HLUA_MUST_GC &&
1146 ret != HLUA_E_AGAIN)
Thierry FOURNIER6ab4d8e2015-09-27 22:17:19 +02001147 lua_gc(lua->T, LUA_GCCOLLECT, 0);
1148
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001149 switch (ret) {
1150 case HLUA_E_AGAIN:
1151 break;
1152
1153 case HLUA_E_ERRMSG:
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001154 hlua_com_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001155 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001156 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001157 break;
1158
1159 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001160 HLUA_CLR_RUN(lua);
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001161 hlua_com_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001162 hlua_ctx_renew(lua, 0);
1163 break;
1164
1165 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001166 HLUA_CLR_RUN(lua);
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001167 hlua_com_purge(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001168 break;
1169 }
1170
1171 return ret;
1172}
1173
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001174/* This function exit the current code. */
1175__LJMP static int hlua_done(lua_State *L)
1176{
1177 struct hlua *hlua = hlua_gethlua(L);
1178
1179 hlua->flags |= HLUA_EXIT;
1180 WILL_LJMP(lua_error(L));
1181
1182 return 0;
1183}
1184
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001185/* This function is an LUA binding. It provides a function
1186 * for deleting ACL from a referenced ACL file.
1187 */
1188__LJMP static int hlua_del_acl(lua_State *L)
1189{
1190 const char *name;
1191 const char *key;
1192 struct pat_ref *ref;
1193
1194 MAY_LJMP(check_args(L, 2, "del_acl"));
1195
1196 name = MAY_LJMP(luaL_checkstring(L, 1));
1197 key = MAY_LJMP(luaL_checkstring(L, 2));
1198
1199 ref = pat_ref_lookup(name);
1200 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001201 WILL_LJMP(luaL_error(L, "'del_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001202
1203 pat_ref_delete(ref, key);
1204 return 0;
1205}
1206
1207/* This function is an LUA binding. It provides a function
1208 * for deleting map entry from a referenced map file.
1209 */
1210static int hlua_del_map(lua_State *L)
1211{
1212 const char *name;
1213 const char *key;
1214 struct pat_ref *ref;
1215
1216 MAY_LJMP(check_args(L, 2, "del_map"));
1217
1218 name = MAY_LJMP(luaL_checkstring(L, 1));
1219 key = MAY_LJMP(luaL_checkstring(L, 2));
1220
1221 ref = pat_ref_lookup(name);
1222 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001223 WILL_LJMP(luaL_error(L, "'del_map': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001224
1225 pat_ref_delete(ref, key);
1226 return 0;
1227}
1228
1229/* This function is an LUA binding. It provides a function
1230 * for adding ACL pattern from a referenced ACL file.
1231 */
1232static int hlua_add_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, "add_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, "'add_acl': unknown acl file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001246
1247 if (pat_ref_find_elt(ref, key) == NULL)
1248 pat_ref_add(ref, key, NULL, NULL);
1249 return 0;
1250}
1251
1252/* This function is an LUA binding. It provides a function
1253 * for setting map pattern and sample from a referenced map
1254 * file.
1255 */
1256static int hlua_set_map(lua_State *L)
1257{
1258 const char *name;
1259 const char *key;
1260 const char *value;
1261 struct pat_ref *ref;
1262
1263 MAY_LJMP(check_args(L, 3, "set_map"));
1264
1265 name = MAY_LJMP(luaL_checkstring(L, 1));
1266 key = MAY_LJMP(luaL_checkstring(L, 2));
1267 value = MAY_LJMP(luaL_checkstring(L, 3));
1268
1269 ref = pat_ref_lookup(name);
1270 if (!ref)
Vincent Bernata72db182015-10-06 16:05:59 +02001271 WILL_LJMP(luaL_error(L, "'set_map': unknown map file '%s'", name));
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001272
1273 if (pat_ref_find_elt(ref, key) != NULL)
1274 pat_ref_set(ref, key, value, NULL);
1275 else
1276 pat_ref_add(ref, key, value, NULL);
1277 return 0;
1278}
1279
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001280/* A class is a lot of memory that contain data. This data can be a table,
1281 * an integer or user data. This data is associated with a metatable. This
1282 * metatable have an original version registred in the global context with
1283 * the name of the object (_G[<name>] = <metable> ).
1284 *
1285 * A metable is a table that modify the standard behavior of a standard
1286 * access to the associated data. The entries of this new metatable are
1287 * defined as is:
1288 *
1289 * http://lua-users.org/wiki/MetatableEvents
1290 *
1291 * __index
1292 *
1293 * we access an absent field in a table, the result is nil. This is
1294 * true, but it is not the whole truth. Actually, such access triggers
1295 * the interpreter to look for an __index metamethod: If there is no
1296 * such method, as usually happens, then the access results in nil;
1297 * otherwise, the metamethod will provide the result.
1298 *
1299 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1300 * the key does not appear in the table, but the metatable has an __index
1301 * property:
1302 *
1303 * - if the value is a function, the function is called, passing in the
1304 * table and the key; the return value of that function is returned as
1305 * the result.
1306 *
1307 * - if the value is another table, the value of the key in that table is
1308 * asked for and returned (and if it doesn't exist in that table, but that
1309 * table's metatable has an __index property, then it continues on up)
1310 *
1311 * - Use "rawget(myTable,key)" to skip this metamethod.
1312 *
1313 * http://www.lua.org/pil/13.4.1.html
1314 *
1315 * __newindex
1316 *
1317 * Like __index, but control property assignment.
1318 *
1319 * __mode - Control weak references. A string value with one or both
1320 * of the characters 'k' and 'v' which specifies that the the
1321 * keys and/or values in the table are weak references.
1322 *
1323 * __call - Treat a table like a function. When a table is followed by
1324 * parenthesis such as "myTable( 'foo' )" and the metatable has
1325 * a __call key pointing to a function, that function is invoked
1326 * (passing any specified arguments) and the return value is
1327 * returned.
1328 *
1329 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1330 * called, if the metatable for myTable has a __metatable
1331 * key, the value of that key is returned instead of the
1332 * actual metatable.
1333 *
1334 * __tostring - Control string representation. When the builtin
1335 * "tostring( myTable )" function is called, if the metatable
1336 * for myTable has a __tostring property set to a function,
1337 * that function is invoked (passing myTable to it) and the
1338 * return value is used as the string representation.
1339 *
1340 * __len - Control table length. When the table length is requested using
1341 * the length operator ( '#' ), if the metatable for myTable has
1342 * a __len key pointing to a function, that function is invoked
1343 * (passing myTable to it) and the return value used as the value
1344 * of "#myTable".
1345 *
1346 * __gc - Userdata finalizer code. When userdata is set to be garbage
1347 * collected, if the metatable has a __gc field pointing to a
1348 * function, that function is first invoked, passing the userdata
1349 * to it. The __gc metamethod is not called for tables.
1350 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1351 *
1352 * Special metamethods for redefining standard operators:
1353 * http://www.lua.org/pil/13.1.html
1354 *
1355 * __add "+"
1356 * __sub "-"
1357 * __mul "*"
1358 * __div "/"
1359 * __unm "!"
1360 * __pow "^"
1361 * __concat ".."
1362 *
1363 * Special methods for redfining standar relations
1364 * http://www.lua.org/pil/13.2.html
1365 *
1366 * __eq "=="
1367 * __lt "<"
1368 * __le "<="
1369 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001370
1371/*
1372 *
1373 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001374 * Class Map
1375 *
1376 *
1377 */
1378
1379/* Returns a struct hlua_map if the stack entry "ud" is
1380 * a class session, otherwise it throws an error.
1381 */
1382__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1383{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001384 return MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001385}
1386
1387/* This function is the map constructor. It don't need
1388 * the class Map object. It creates and return a new Map
1389 * object. It must be called only during "body" or "init"
1390 * context because it process some filesystem accesses.
1391 */
1392__LJMP static int hlua_map_new(struct lua_State *L)
1393{
1394 const char *fn;
1395 int match = PAT_MATCH_STR;
1396 struct sample_conv conv;
1397 const char *file = "";
1398 int line = 0;
1399 lua_Debug ar;
1400 char *err = NULL;
1401 struct arg args[2];
1402
1403 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1404 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1405
1406 fn = MAY_LJMP(luaL_checkstring(L, 1));
1407
1408 if (lua_gettop(L) >= 2) {
1409 match = MAY_LJMP(luaL_checkinteger(L, 2));
1410 if (match < 0 || match >= PAT_MATCH_NUM)
1411 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1412 }
1413
1414 /* Get Lua filename and line number. */
1415 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1416 lua_getinfo(L, "Sl", &ar); /* get info about it */
1417 if (ar.currentline > 0) { /* is there info? */
1418 file = ar.short_src;
1419 line = ar.currentline;
1420 }
1421 }
1422
1423 /* fill fake sample_conv struct. */
1424 conv.kw = ""; /* unused. */
1425 conv.process = NULL; /* unused. */
1426 conv.arg_mask = 0; /* unused. */
1427 conv.val_args = NULL; /* unused. */
1428 conv.out_type = SMP_T_STR;
1429 conv.private = (void *)(long)match;
1430 switch (match) {
1431 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1432 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1433 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1434 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1435 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1436 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1437 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001438 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001439 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1440 default:
1441 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1442 }
1443
1444 /* fill fake args. */
1445 args[0].type = ARGT_STR;
1446 args[0].data.str.str = (char *)fn;
1447 args[1].type = ARGT_STOP;
1448
1449 /* load the map. */
1450 if (!sample_load_map(args, &conv, file, line, &err)) {
1451 /* error case: we cant use luaL_error because we must
1452 * free the err variable.
1453 */
1454 luaL_where(L, 1);
1455 lua_pushfstring(L, "'new': %s.", err);
1456 lua_concat(L, 2);
1457 free(err);
1458 WILL_LJMP(lua_error(L));
1459 }
1460
1461 /* create the lua object. */
1462 lua_newtable(L);
1463 lua_pushlightuserdata(L, args[0].data.map);
1464 lua_rawseti(L, -2, 0);
1465
1466 /* Pop a class Map metatable and affect it to the userdata. */
1467 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1468 lua_setmetatable(L, -2);
1469
1470
1471 return 1;
1472}
1473
1474__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1475{
1476 struct map_descriptor *desc;
1477 struct pattern *pat;
1478 struct sample smp;
1479
1480 MAY_LJMP(check_args(L, 2, "lookup"));
1481 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001482 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001483 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001484 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001485 }
1486 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001487 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001488 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001489 smp.data.u.str.str = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.len));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001490 }
1491
1492 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001493 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001494 if (str)
1495 lua_pushstring(L, "");
1496 else
1497 lua_pushnil(L);
1498 return 1;
1499 }
1500
1501 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001502 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001503 return 1;
1504}
1505
1506__LJMP static int hlua_map_lookup(struct lua_State *L)
1507{
1508 return _hlua_map_lookup(L, 0);
1509}
1510
1511__LJMP static int hlua_map_slookup(struct lua_State *L)
1512{
1513 return _hlua_map_lookup(L, 1);
1514}
1515
1516/*
1517 *
1518 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001519 * Class Socket
1520 *
1521 *
1522 */
1523
1524__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1525{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02001526 return MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001527}
1528
1529/* This function is the handler called for each I/O on the established
1530 * connection. It is used for notify space avalaible to send or data
1531 * received.
1532 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001533static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001534{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001535 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001536 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001537
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001538 /* If the connection object is not avalaible, close all the
1539 * streams and wakeup everithing waiting for.
1540 */
1541 if (!c) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001542 si_shutw(si);
1543 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001544 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001545 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1546 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001547 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001548 }
1549
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001550 /* If we cant write, wakeup the pending write signals. */
1551 if (channel_output_closed(si_ic(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001552 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001553
1554 /* If we cant read, wakeup the pending read signals. */
1555 if (channel_input_closed(si_oc(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001556 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER6d695e62015-09-27 19:29:38 +02001557
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001558 /* if the connection is not estabkished, inform the stream that we want
1559 * to be notified whenever the connection completes.
1560 */
1561 if (!(c->flags & CO_FL_CONNECTED)) {
1562 si_applet_cant_get(si);
1563 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001564 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001565 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001566
1567 /* This function is called after the connect. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001568 appctx->ctx.hlua_cosocket.connected = 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001569
1570 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001571 if (channel_may_recv(si_ic(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001572 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001573
1574 /* Wake the tasks which wants to read if the buffer contains data. */
Thierry FOURNIEReba6f642015-09-26 22:01:07 +02001575 if (!channel_is_empty(si_oc(si)))
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001576 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001577}
1578
Willy Tarreau87b09662015-04-03 00:22:06 +02001579/* This function is called when the "struct stream" is destroyed.
1580 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001581 * Wake all the pending signals.
1582 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001583static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001584{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001585 /* Remove my link in the original object. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001586 if (appctx->ctx.hlua_cosocket.socket)
1587 appctx->ctx.hlua_cosocket.socket->s = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001588
1589 /* Wake all the task waiting for me. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001590 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_read);
1591 hlua_com_wake(&appctx->ctx.hlua_cosocket.wake_on_write);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001592}
1593
1594/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001595 * uses this object. If the stream does not exists, just quit.
1596 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001597 * pending signal can rest in the read and write lists. destroy
1598 * it.
1599 */
1600__LJMP static int hlua_socket_gc(lua_State *L)
1601{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001602 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001603 struct appctx *appctx;
1604
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001605 MAY_LJMP(check_args(L, 1, "__gc"));
1606
1607 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001608 if (!socket->s)
1609 return 0;
1610
Willy Tarreau87b09662015-04-03 00:22:06 +02001611 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001612 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001613 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001614 socket->s = NULL;
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001615 appctx->ctx.hlua_cosocket.socket = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001616
1617 return 0;
1618}
1619
1620/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001621 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001622 */
1623__LJMP static int hlua_socket_close(lua_State *L)
1624{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001625 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001626 struct appctx *appctx;
1627
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001628 MAY_LJMP(check_args(L, 1, "close"));
1629
1630 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001631 if (!socket->s)
1632 return 0;
1633
Willy Tarreau87b09662015-04-03 00:22:06 +02001634 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001635 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001636 appctx = objt_appctx(socket->s->si[0].end);
Thierry FOURNIER18d09902016-12-16 09:25:38 +01001637 appctx->ctx.hlua_cosocket.socket = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001638 socket->s = NULL;
1639
1640 return 0;
1641}
1642
1643/* This Lua function assumes that the stack contain three parameters.
1644 * 1 - USERDATA containing a struct socket
1645 * 2 - INTEGER with values of the macro defined below
1646 * If the integer is -1, we must read at most one line.
1647 * If the integer is -2, we ust read all the data until the
1648 * end of the stream.
1649 * If the integer is positive value, we must read a number of
1650 * bytes corresponding to this value.
1651 */
1652#define HLSR_READ_LINE (-1)
1653#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001654__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001655{
1656 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1657 int wanted = lua_tointeger(L, 2);
1658 struct hlua *hlua = hlua_gethlua(L);
1659 struct appctx *appctx;
1660 int len;
1661 int nblk;
1662 char *blk1;
1663 int len1;
1664 char *blk2;
1665 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001666 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001667 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001668
1669 /* Check if this lua stack is schedulable. */
1670 if (!hlua || !hlua->task)
1671 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1672 "'frontend', 'backend' or 'task'"));
1673
1674 /* check for connection closed. If some data where read, return it. */
1675 if (!socket->s)
1676 goto connection_closed;
1677
Willy Tarreau94aa6172015-03-13 14:19:06 +01001678 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001679 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001680 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001681 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001682 if (nblk < 0) /* Connection close. */
1683 goto connection_closed;
1684 if (nblk == 0) /* No data avalaible. */
1685 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001686
1687 /* remove final \r\n. */
1688 if (nblk == 1) {
1689 if (blk1[len1-1] == '\n') {
1690 len1--;
1691 skip_at_end++;
1692 if (blk1[len1-1] == '\r') {
1693 len1--;
1694 skip_at_end++;
1695 }
1696 }
1697 }
1698 else {
1699 if (blk2[len2-1] == '\n') {
1700 len2--;
1701 skip_at_end++;
1702 if (blk2[len2-1] == '\r') {
1703 len2--;
1704 skip_at_end++;
1705 }
1706 }
1707 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001708 }
1709
1710 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001711 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001712 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001713 if (nblk < 0) /* Connection close. */
1714 goto connection_closed;
1715 if (nblk == 0) /* No data avalaible. */
1716 goto connection_empty;
1717 }
1718
1719 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001720 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001721 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001722 if (nblk < 0) /* Connection close. */
1723 goto connection_closed;
1724 if (nblk == 0) /* No data avalaible. */
1725 goto connection_empty;
1726
1727 if (len1 > wanted) {
1728 nblk = 1;
1729 len1 = wanted;
1730 } if (nblk == 2 && len1 + len2 > wanted)
1731 len2 = wanted - len1;
1732 }
1733
1734 len = len1;
1735
1736 luaL_addlstring(&socket->b, blk1, len1);
1737 if (nblk == 2) {
1738 len += len2;
1739 luaL_addlstring(&socket->b, blk2, len2);
1740 }
1741
1742 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001743 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001744
1745 /* Don't wait anything. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001746 stream_int_notify(&socket->s->si[0]);
1747 stream_int_update_applet(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001748
1749 /* If the pattern reclaim to read all the data
1750 * in the connection, got out.
1751 */
1752 if (wanted == HLSR_READ_ALL)
1753 goto connection_empty;
1754 else if (wanted >= 0 && len < wanted)
1755 goto connection_empty;
1756
1757 /* Return result. */
1758 luaL_pushresult(&socket->b);
1759 return 1;
1760
1761connection_closed:
1762
1763 /* If the buffer containds data. */
1764 if (socket->b.n > 0) {
1765 luaL_pushresult(&socket->b);
1766 return 1;
1767 }
1768 lua_pushnil(L);
1769 lua_pushstring(L, "connection closed.");
1770 return 2;
1771
1772connection_empty:
1773
1774 appctx = objt_appctx(socket->s->si[0].end);
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001775 if (!hlua_com_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_read, hlua->task))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001776 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001777 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001778 return 0;
1779}
1780
1781/* This Lus function gets two parameters. The first one can be string
1782 * or a number. If the string is "*l", the user require one line. If
1783 * the string is "*a", the user require all the content of the stream.
1784 * If the value is a number, the user require a number of bytes equal
1785 * to the value. The default value is "*l" (a line).
1786 *
1787 * This paraeter with a variable type is converted in integer. This
1788 * integer takes this values:
1789 * -1 : read a line
1790 * -2 : read all the stream
1791 * >0 : amount if bytes.
1792 *
1793 * The second parameter is optinal. It contains a string that must be
1794 * concatenated with the read data.
1795 */
1796__LJMP static int hlua_socket_receive(struct lua_State *L)
1797{
1798 int wanted = HLSR_READ_LINE;
1799 const char *pattern;
1800 int type;
1801 char *error;
1802 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001803 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001804
1805 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1806 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1807
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001808 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001809
1810 /* check for pattern. */
1811 if (lua_gettop(L) >= 2) {
1812 type = lua_type(L, 2);
1813 if (type == LUA_TSTRING) {
1814 pattern = lua_tostring(L, 2);
1815 if (strcmp(pattern, "*a") == 0)
1816 wanted = HLSR_READ_ALL;
1817 else if (strcmp(pattern, "*l") == 0)
1818 wanted = HLSR_READ_LINE;
1819 else {
1820 wanted = strtoll(pattern, &error, 10);
1821 if (*error != '\0')
1822 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1823 }
1824 }
1825 else if (type == LUA_TNUMBER) {
1826 wanted = lua_tointeger(L, 2);
1827 if (wanted < 0)
1828 WILL_LJMP(luaL_error(L, "Unsupported size."));
1829 }
1830 }
1831
1832 /* Set pattern. */
1833 lua_pushinteger(L, wanted);
1834 lua_replace(L, 2);
1835
1836 /* init bufffer, and fiil it wih prefix. */
1837 luaL_buffinit(L, &socket->b);
1838
1839 /* Check prefix. */
1840 if (lua_gettop(L) >= 3) {
1841 if (lua_type(L, 3) != LUA_TSTRING)
1842 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1843 pattern = lua_tolstring(L, 3, &len);
1844 luaL_addlstring(&socket->b, pattern, len);
1845 }
1846
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001847 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001848}
1849
1850/* Write the Lua input string in the output buffer.
1851 * This fucntion returns a yield if no space are available.
1852 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001853static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001854{
1855 struct hlua_socket *socket;
1856 struct hlua *hlua = hlua_gethlua(L);
1857 struct appctx *appctx;
1858 size_t buf_len;
1859 const char *buf;
1860 int len;
1861 int send_len;
1862 int sent;
1863
1864 /* Check if this lua stack is schedulable. */
1865 if (!hlua || !hlua->task)
1866 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1867 "'frontend', 'backend' or 'task'"));
1868
1869 /* Get object */
1870 socket = MAY_LJMP(hlua_checksocket(L, 1));
1871 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001872 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001873
1874 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001875 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001876 lua_pushinteger(L, -1);
1877 return 1;
1878 }
1879
1880 /* Update the input buffer data. */
1881 buf += sent;
1882 send_len = buf_len - sent;
1883
1884 /* All the data are sent. */
1885 if (sent >= buf_len)
1886 return 1; /* Implicitly return the length sent. */
1887
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001888 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1889 * the request buffer if its not required.
1890 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001891 if (socket->s->req.buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01001892 si_applet_cant_put(&socket->s->si[0]);
1893 goto hlua_socket_write_yield_return;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001894 }
1895
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001896 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001897 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001898 if (len <= 0)
1899 goto hlua_socket_write_yield_return;
1900
1901 /* send data */
1902 if (len < send_len)
1903 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001904 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001905
1906 /* "Not enough space" (-1), "Buffer too little to contain
1907 * the data" (-2) are not expected because the available length
1908 * is tested.
1909 * Other unknown error are also not expected.
1910 */
1911 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001912 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001913 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001914
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001915 MAY_LJMP(hlua_socket_close(L));
1916 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001917 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001918 return 1;
1919 }
1920
1921 /* update buffers. */
Willy Tarreaude70fa12015-09-26 11:25:05 +02001922 stream_int_notify(&socket->s->si[0]);
1923 stream_int_update_applet(&socket->s->si[0]);
1924
Willy Tarreau94aa6172015-03-13 14:19:06 +01001925 socket->s->req.rex = TICK_ETERNITY;
1926 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001927
1928 /* Update length sent. */
1929 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001930 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001931
1932 /* All the data buffer is sent ? */
1933 if (sent + len >= buf_len)
1934 return 1;
1935
1936hlua_socket_write_yield_return:
1937 appctx = objt_appctx(socket->s->si[0].end);
Thierry FOURNIER847ca662016-12-16 13:07:22 +01001938 if (!hlua_com_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001939 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001940 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001941 return 0;
1942}
1943
1944/* This function initiate the send of data. It just check the input
1945 * parameters and push an integer in the Lua stack that contain the
1946 * amount of data writed in the buffer. This is used by the function
1947 * "hlua_socket_write_yield" that can yield.
1948 *
1949 * The Lua function gets between 3 and 4 parameters. The first one is
1950 * the associated object. The second is a string buffer. The third is
1951 * a facultative integer that represents where is the buffer position
1952 * of the start of the data that can send. The first byte is the
1953 * position "1". The default value is "1". The fourth argument is a
1954 * facultative integer that represents where is the buffer position
1955 * of the end of the data that can send. The default is the last byte.
1956 */
1957static int hlua_socket_send(struct lua_State *L)
1958{
1959 int i;
1960 int j;
1961 const char *buf;
1962 size_t buf_len;
1963
1964 /* Check number of arguments. */
1965 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1966 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1967
1968 /* Get the string. */
1969 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1970
1971 /* Get and check j. */
1972 if (lua_gettop(L) == 4) {
1973 j = MAY_LJMP(luaL_checkinteger(L, 4));
1974 if (j < 0)
1975 j = buf_len + j + 1;
1976 if (j > buf_len)
1977 j = buf_len + 1;
1978 lua_pop(L, 1);
1979 }
1980 else
1981 j = buf_len;
1982
1983 /* Get and check i. */
1984 if (lua_gettop(L) == 3) {
1985 i = MAY_LJMP(luaL_checkinteger(L, 3));
1986 if (i < 0)
1987 i = buf_len + i + 1;
1988 if (i > buf_len)
1989 i = buf_len + 1;
1990 lua_pop(L, 1);
1991 } else
1992 i = 1;
1993
1994 /* Check bth i and j. */
1995 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001996 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001997 return 1;
1998 }
1999 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002000 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002001 return 1;
2002 }
2003 if (i == 0)
2004 i = 1;
2005 if (j == 0)
2006 j = 1;
2007
2008 /* Pop the string. */
2009 lua_pop(L, 1);
2010
2011 /* Update the buffer length. */
2012 buf += i - 1;
2013 buf_len = j - i + 1;
2014 lua_pushlstring(L, buf, buf_len);
2015
2016 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002017 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002018
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002019 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002020}
2021
Willy Tarreau22b0a682015-06-17 19:43:49 +02002022#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002023__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2024{
2025 static char buffer[SOCKET_INFO_MAX_LEN];
2026 int ret;
2027 int len;
2028 char *p;
2029
2030 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2031 if (ret <= 0) {
2032 lua_pushnil(L);
2033 return 1;
2034 }
2035
2036 if (ret == AF_UNIX) {
2037 lua_pushstring(L, buffer+1);
2038 return 1;
2039 }
2040 else if (ret == AF_INET6) {
2041 buffer[0] = '[';
2042 len = strlen(buffer);
2043 buffer[len] = ']';
2044 len++;
2045 buffer[len] = ':';
2046 len++;
2047 p = buffer;
2048 }
2049 else if (ret == AF_INET) {
2050 p = buffer + 1;
2051 len = strlen(p);
2052 p[len] = ':';
2053 len++;
2054 }
2055 else {
2056 lua_pushnil(L);
2057 return 1;
2058 }
2059
2060 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2061 lua_pushnil(L);
2062 return 1;
2063 }
2064
2065 lua_pushstring(L, p);
2066 return 1;
2067}
2068
2069/* Returns information about the peer of the connection. */
2070__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2071{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002072 struct hlua_socket *socket;
2073 struct connection *conn;
2074
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002075 MAY_LJMP(check_args(L, 1, "getpeername"));
2076
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002077 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002078
2079 /* Check if the tcp object is avalaible. */
2080 if (!socket->s) {
2081 lua_pushnil(L);
2082 return 1;
2083 }
2084
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002085 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086 if (!conn) {
2087 lua_pushnil(L);
2088 return 1;
2089 }
2090
Willy Tarreaua71f6422016-11-16 17:00:14 +01002091 conn_get_to_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002092 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002093 lua_pushnil(L);
2094 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095 }
2096
2097 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2098}
2099
2100/* Returns information about my connection side. */
2101static int hlua_socket_getsockname(struct lua_State *L)
2102{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002103 struct hlua_socket *socket;
2104 struct connection *conn;
2105
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002106 MAY_LJMP(check_args(L, 1, "getsockname"));
2107
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002108 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002109
2110 /* Check if the tcp object is avalaible. */
2111 if (!socket->s) {
2112 lua_pushnil(L);
2113 return 1;
2114 }
2115
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002116 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002117 if (!conn) {
2118 lua_pushnil(L);
2119 return 1;
2120 }
2121
Willy Tarreaua71f6422016-11-16 17:00:14 +01002122 conn_get_from_addr(conn);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002123 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
Willy Tarreaua71f6422016-11-16 17:00:14 +01002124 lua_pushnil(L);
2125 return 1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002126 }
2127
2128 return hlua_socket_info(L, &conn->addr.from);
2129}
2130
2131/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002132static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002133 .obj_type = OBJ_TYPE_APPLET,
2134 .name = "<LUA_TCP>",
2135 .fct = hlua_socket_handler,
2136 .release = hlua_socket_release,
2137};
2138
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002139__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002140{
2141 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2142 struct hlua *hlua = hlua_gethlua(L);
2143 struct appctx *appctx;
2144
2145 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002146 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002147 lua_pushnil(L);
2148 lua_pushstring(L, "Can't connect");
2149 return 2;
2150 }
2151
2152 appctx = objt_appctx(socket->s->si[0].end);
2153
2154 /* Check for connection established. */
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002155 if (appctx->ctx.hlua_cosocket.connected) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002156 lua_pushinteger(L, 1);
2157 return 1;
2158 }
2159
Thierry FOURNIER847ca662016-12-16 13:07:22 +01002160 if (!hlua_com_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002162 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002163 return 0;
2164}
2165
2166/* This function fail or initite the connection. */
2167__LJMP static int hlua_socket_connect(struct lua_State *L)
2168{
2169 struct hlua_socket *socket;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002170 int port = -1;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002171 const char *ip;
2172 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002173 struct hlua *hlua;
2174 struct appctx *appctx;
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002175 int low, high;
2176 struct sockaddr_storage *addr;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002177
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002178 if (lua_gettop(L) < 2)
2179 WILL_LJMP(luaL_error(L, "connect: need at least 2 arguments"));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180
2181 /* Get args. */
2182 socket = MAY_LJMP(hlua_checksocket(L, 1));
2183 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002184 if (lua_gettop(L) >= 3)
2185 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186
Willy Tarreau973a5422015-08-05 21:47:23 +02002187 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002188 if (!conn)
2189 WILL_LJMP(luaL_error(L, "connect: internal error"));
2190
Willy Tarreau3adac082015-09-26 17:51:09 +02002191 /* needed for the connection not to be closed */
2192 conn->target = socket->s->target;
2193
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194 /* Parse ip address. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002195 addr = str2sa_range(ip, &low, &high, NULL, NULL, NULL, 0);
2196 if (!addr)
2197 WILL_LJMP(luaL_error(L, "connect: cannot parse destination address '%s'", ip));
2198 if (low != high)
2199 WILL_LJMP(luaL_error(L, "connect: port ranges not supported : address '%s'", ip));
2200 memcpy(&conn->addr.to, addr, sizeof(struct sockaddr_storage));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002201
2202 /* Set port. */
Thierry FOURNIERc2f56532015-09-26 20:23:30 +02002203 if (low == 0) {
2204 if (conn->addr.to.ss_family == AF_INET) {
2205 if (port == -1)
2206 WILL_LJMP(luaL_error(L, "connect: port missing"));
2207 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2208 } else if (conn->addr.to.ss_family == AF_INET6) {
2209 if (port == -1)
2210 WILL_LJMP(luaL_error(L, "connect: port missing"));
2211 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2212 }
2213 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002214
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002215 hlua = hlua_gethlua(L);
2216 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002217
2218 /* inform the stream that we want to be notified whenever the
2219 * connection completes.
2220 */
2221 si_applet_cant_get(&socket->s->si[0]);
2222 si_applet_cant_put(&socket->s->si[0]);
Thierry FOURNIER8c8fbbe2015-09-26 17:02:35 +02002223 appctx_wakeup(appctx);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002224
Thierry FOURNIER7c39ab42015-09-27 22:53:33 +02002225 hlua->flags |= HLUA_MUST_GC;
2226
Thierry FOURNIER847ca662016-12-16 13:07:22 +01002227 if (!hlua_com_new(&hlua->com, &appctx->ctx.hlua_cosocket.wake_on_write, hlua->task))
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002228 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002229 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230
2231 return 0;
2232}
2233
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002234#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002235__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2236{
2237 struct hlua_socket *socket;
2238
2239 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2240 socket = MAY_LJMP(hlua_checksocket(L, 1));
2241 socket->s->target = &socket_ssl.obj_type;
2242 return MAY_LJMP(hlua_socket_connect(L));
2243}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002244#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002245
2246__LJMP static int hlua_socket_setoption(struct lua_State *L)
2247{
2248 return 0;
2249}
2250
2251__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2252{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002253 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002254 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002255
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002256 MAY_LJMP(check_args(L, 2, "settimeout"));
2257
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002258 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002259 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002260
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002261 socket->s->req.rto = tmout;
2262 socket->s->req.wto = tmout;
2263 socket->s->res.rto = tmout;
2264 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002265
2266 return 0;
2267}
2268
2269__LJMP static int hlua_socket_new(lua_State *L)
2270{
2271 struct hlua_socket *socket;
2272 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002273 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002274 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002275 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002276
2277 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002278 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002279 hlua_pusherror(L, "socket: full stack");
2280 goto out_fail_conf;
2281 }
2282
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002283 /* Create the object: obj[0] = userdata. */
2284 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002285 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002286 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002287 memset(socket, 0, sizeof(*socket));
2288
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002289 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002290 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002291 hlua_pusherror(L, "socket: uninitialized pools.");
2292 goto out_fail_conf;
2293 }
2294
Willy Tarreau87b09662015-04-03 00:22:06 +02002295 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002296 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2297 lua_setmetatable(L, -2);
2298
Willy Tarreaud420a972015-04-06 00:39:18 +02002299 /* Create the applet context */
2300 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002301 if (!appctx) {
2302 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002303 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002304 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002305
Thierry FOURNIER18d09902016-12-16 09:25:38 +01002306 appctx->ctx.hlua_cosocket.socket = socket;
2307 appctx->ctx.hlua_cosocket.connected = 0;
2308 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_write);
2309 LIST_INIT(&appctx->ctx.hlua_cosocket.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002310
Willy Tarreaud420a972015-04-06 00:39:18 +02002311 /* Now create a session, task and stream for this applet */
2312 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2313 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002314 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002315 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002316 }
2317
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002318 task = task_new();
2319 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002320 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002321 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002322 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002323 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002324
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002325 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002326 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002327 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002328 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002329 }
2330
Willy Tarreaud420a972015-04-06 00:39:18 +02002331 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002332 socket->s = strm;
2333 strm->hlua.T = NULL;
2334 strm->hlua.Tref = LUA_REFNIL;
2335 strm->hlua.Mref = LUA_REFNIL;
2336 strm->hlua.nargs = 0;
2337 strm->hlua.flags = 0;
2338 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002339
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002340 /* Configure "right" stream interface. this "si" is used to connect
2341 * and retrieve data from the server. The connection is initialized
2342 * with the "struct server".
2343 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002344 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002345
2346 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002347 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2348 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002349
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002350 /* Update statistics counters. */
2351 socket_proxy.feconn++; /* beconn will be increased later */
2352 jobs++;
2353 totalconn++;
2354
2355 /* Return yield waiting for connection. */
2356 return 1;
2357
Willy Tarreaud420a972015-04-06 00:39:18 +02002358 out_fail_stream:
2359 task_free(task);
2360 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002361 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002362 out_fail_sess:
2363 appctx_free(appctx);
2364 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002365 WILL_LJMP(lua_error(L));
2366 return 0;
2367}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002368
2369/*
2370 *
2371 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002372 * Class Channel
2373 *
2374 *
2375 */
2376
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002377/* The state between the channel data and the HTTP parser state can be
2378 * unconsistent, so reset the parser and call it again. Warning, this
2379 * action not revalidate the request and not send a 400 if the modified
2380 * resuest is not valid.
2381 *
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002382 * This function never fails. The direction is set using dir, which equals
2383 * either SMP_OPT_DIR_REQ or SMP_OPT_DIR_RES.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002384 */
2385static void hlua_resynchonize_proto(struct stream *stream, int dir)
2386{
2387 /* Protocol HTTP. */
2388 if (stream->be->mode == PR_MODE_HTTP) {
2389
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002390 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002391 http_txn_reset_req(stream->txn);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002392 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002393 http_txn_reset_res(stream->txn);
2394
2395 if (stream->txn->hdr_idx.v)
2396 hdr_idx_init(&stream->txn->hdr_idx);
2397
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002398 if (dir == SMP_OPT_DIR_REQ)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002399 http_msg_analyzer(&stream->txn->req, &stream->txn->hdr_idx);
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01002400 else if (dir == SMP_OPT_DIR_RES)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002401 http_msg_analyzer(&stream->txn->rsp, &stream->txn->hdr_idx);
2402 }
2403}
2404
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002405/* This function is called before the Lua execution. It stores
2406 * the differents parsers state before executing some Lua code.
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002407 */
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002408static inline void consistency_set(struct stream *stream, int opt, struct hlua_consistency *c)
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002409{
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002410 c->mode = stream->be->mode;
2411 switch (c->mode) {
2412 case PR_MODE_HTTP:
2413 c->data.http.dir = opt & SMP_OPT_DIR;
2414 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2415 c->data.http.state = stream->txn->req.msg_state;
2416 else
2417 c->data.http.state = stream->txn->rsp.msg_state;
2418 break;
2419 default:
2420 break;
2421 }
2422}
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002423
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002424/* This function is called after the Lua execution. it
2425 * returns true if the parser state is consistent, otherwise,
2426 * it return false.
2427 *
2428 * In HTTP mode, the parser state must be in the same state
2429 * or greater when we exit the function. Even if we do a
2430 * control yield. This prevent to break the HTTP message
2431 * from the Lua code.
2432 */
2433static inline int consistency_check(struct stream *stream, int opt, struct hlua_consistency *c)
2434{
2435 if (c->mode != stream->be->mode)
2436 return 0;
2437
2438 switch (c->mode) {
2439 case PR_MODE_HTTP:
2440 if (c->data.http.dir != (opt & SMP_OPT_DIR))
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002441 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01002442 if (c->data.http.dir == SMP_OPT_DIR_REQ)
2443 return stream->txn->req.msg_state >= c->data.http.state;
2444 else
2445 return stream->txn->rsp.msg_state >= c->data.http.state;
2446 default:
2447 return 1;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002448 }
2449 return 1;
2450}
2451
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002452/* Returns the struct hlua_channel join to the class channel in the
2453 * stack entry "ud" or throws an argument error.
2454 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002455__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002456{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002457 return MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002458}
2459
Willy Tarreau47860ed2015-03-10 14:07:50 +01002460/* Pushes the channel onto the top of the stack. If the stask does not have a
2461 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002462 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002463static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002464{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002465 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002466 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002467 return 0;
2468
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002469 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002470 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002471 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002472
2473 /* Pop a class sesison metatable and affect it to the userdata. */
2474 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2475 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002476 return 1;
2477}
2478
2479/* Duplicate all the data present in the input channel and put it
2480 * in a string LUA variables. Returns -1 and push a nil value in
2481 * the stack if the channel is closed and all the data are consumed,
2482 * returns 0 if no data are available, otherwise it returns the length
2483 * of the builded string.
2484 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002485static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002486{
2487 char *blk1;
2488 char *blk2;
2489 int len1;
2490 int len2;
2491 int ret;
2492 luaL_Buffer b;
2493
Willy Tarreau47860ed2015-03-10 14:07:50 +01002494 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002495 if (unlikely(ret == 0))
2496 return 0;
2497
2498 if (unlikely(ret < 0)) {
2499 lua_pushnil(L);
2500 return -1;
2501 }
2502
2503 luaL_buffinit(L, &b);
2504 luaL_addlstring(&b, blk1, len1);
2505 if (unlikely(ret == 2))
2506 luaL_addlstring(&b, blk2, len2);
2507 luaL_pushresult(&b);
2508
2509 if (unlikely(ret == 2))
2510 return len1 + len2;
2511 return len1;
2512}
2513
2514/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2515 * a yield. This function keep the data in the buffer.
2516 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002517__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002518{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002519 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002520
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002521 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2522
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002523 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002524 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002525 return 1;
2526}
2527
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002528/* Check arguments for the function "hlua_channel_dup_yield". */
2529__LJMP static int hlua_channel_dup(lua_State *L)
2530{
2531 MAY_LJMP(check_args(L, 1, "dup"));
2532 MAY_LJMP(hlua_checkchannel(L, 1));
2533 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2534}
2535
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002536/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2537 * a yield. This function consumes the data in the buffer. It returns
2538 * a string containing the data or a nil pointer if no data are available
2539 * and the channel is closed.
2540 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002541__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002542{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002543 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002544 int ret;
2545
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002546 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002547
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002548 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002549 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002550 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002551
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002552 if (unlikely(ret == -1))
2553 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002554
Willy Tarreau47860ed2015-03-10 14:07:50 +01002555 chn->buf->i -= ret;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002556 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002557 return 1;
2558}
2559
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002560/* Check arguments for the fucntion "hlua_channel_get_yield". */
2561__LJMP static int hlua_channel_get(lua_State *L)
2562{
2563 MAY_LJMP(check_args(L, 1, "get"));
2564 MAY_LJMP(hlua_checkchannel(L, 1));
2565 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2566}
2567
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002568/* This functions consumes and returns one line. If the channel is closed,
2569 * and the last data does not contains a final '\n', the data are returned
2570 * without the final '\n'. When no more data are avalaible, it returns nil
2571 * value.
2572 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002573__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002574{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002575 char *blk1;
2576 char *blk2;
2577 int len1;
2578 int len2;
2579 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002580 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002581 int ret;
2582 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002583
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002584 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2585
Willy Tarreau47860ed2015-03-10 14:07:50 +01002586 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002587 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002588 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002589
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002590 if (ret == -1) {
2591 lua_pushnil(L);
2592 return 1;
2593 }
2594
2595 luaL_buffinit(L, &b);
2596 luaL_addlstring(&b, blk1, len1);
2597 len = len1;
2598 if (unlikely(ret == 2)) {
2599 luaL_addlstring(&b, blk2, len2);
2600 len += len2;
2601 }
2602 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002603 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002604 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002605 return 1;
2606}
2607
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002608/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2609__LJMP static int hlua_channel_getline(lua_State *L)
2610{
2611 MAY_LJMP(check_args(L, 1, "getline"));
2612 MAY_LJMP(hlua_checkchannel(L, 1));
2613 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2614}
2615
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002616/* This function takes a string as input, and append it at the
2617 * input side of channel. If the data is too big, but a space
2618 * is probably available after sending some data, the function
2619 * yield. If the data is bigger than the buffer, or if the
2620 * channel is closed, it returns -1. otherwise, it returns the
2621 * amount of data writed.
2622 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002623__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002624{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002625 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002626 size_t len;
2627 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2628 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2629 int ret;
2630 int max;
2631
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002632 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2633 * the request buffer if its not required.
2634 */
2635 if (chn->buf->size == 0) {
2636 si_applet_cant_put(chn_prod(chn));
2637 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
2638 }
2639
Willy Tarreau47860ed2015-03-10 14:07:50 +01002640 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002641 if (max > len - l)
2642 max = len - l;
2643
Willy Tarreau47860ed2015-03-10 14:07:50 +01002644 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002645 if (ret == -2 || ret == -3) {
2646 lua_pushinteger(L, -1);
2647 return 1;
2648 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002649 if (ret == -1) {
2650 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002651 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002652 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002653 l += ret;
2654 lua_pop(L, 1);
2655 lua_pushinteger(L, l);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02002656 hlua_resynchonize_proto(chn_strm(chn), !!(chn->flags & CF_ISRESP));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002657
Willy Tarreau47860ed2015-03-10 14:07:50 +01002658 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2659 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002660 /* There are no space avalaible, and the output buffer is empty.
2661 * in this case, we cannot add more data, so we cannot yield,
2662 * we return the amount of copyied data.
2663 */
2664 return 1;
2665 }
2666 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002667 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002668 return 1;
2669}
2670
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002671/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002672 * of the writed string, or -1 if the channel is closed or if the
2673 * buffer size is too little for the data.
2674 */
2675__LJMP static int hlua_channel_append(lua_State *L)
2676{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002677 size_t len;
2678
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002679 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002680 MAY_LJMP(hlua_checkchannel(L, 1));
2681 MAY_LJMP(luaL_checklstring(L, 2, &len));
2682 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002683 lua_pushinteger(L, 0);
2684
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002685 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002686}
2687
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002688/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002689 * his process by cleaning the buffer. The result is a replacement
2690 * of the current data. It returns the length of the writed string,
2691 * or -1 if the channel is closed or if the buffer size is too
2692 * little for the data.
2693 */
2694__LJMP static int hlua_channel_set(lua_State *L)
2695{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002696 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002697
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002698 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002699 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002700 lua_pushinteger(L, 0);
2701
Willy Tarreau47860ed2015-03-10 14:07:50 +01002702 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002703
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002704 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002705}
2706
2707/* Append data in the output side of the buffer. This data is immediatly
2708 * sent. The fcuntion returns the ammount of data writed. If the buffer
2709 * cannot contains the data, the function yield. The function returns -1
2710 * if the channel is closed.
2711 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002712__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002713{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002714 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002715 size_t len;
2716 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2717 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2718 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002719 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002720
Willy Tarreau47860ed2015-03-10 14:07:50 +01002721 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002722 lua_pushinteger(L, -1);
2723 return 1;
2724 }
2725
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002726 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2727 * the request buffer if its not required.
2728 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002729 if (chn->buf->size == 0) {
Christopher Fauleta73e59b2016-12-09 17:30:18 +01002730 si_applet_cant_put(chn_prod(chn));
2731 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002732 }
2733
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002734 /* the writed data will be immediatly sent, so we can check
2735 * the avalaible space without taking in account the reserve.
2736 * The reserve is guaranted for the processing of incoming
2737 * data, because the buffer will be flushed.
2738 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002739 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002740
2741 /* If there are no space avalaible, and the output buffer is empty.
2742 * in this case, we cannot add more data, so we cannot yield,
2743 * we return the amount of copyied data.
2744 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002745 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002746 return 1;
2747
2748 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002749 if (max > len - l)
2750 max = len - l;
2751
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002752 /* The buffer avalaible size may be not contiguous. This test
2753 * detects a non contiguous buffer and realign it.
2754 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002755 if (bi_space_for_replace(chn->buf) < max)
2756 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002757
2758 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002759 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002760
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002761 /* buffer replace considers that the input part is filled.
2762 * so, I must forward these new data in the output part.
2763 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002764 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002765
2766 l += max;
2767 lua_pop(L, 1);
2768 lua_pushinteger(L, l);
2769
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002770 /* If there are no space avalaible, and the output buffer is empty.
2771 * in this case, we cannot add more data, so we cannot yield,
2772 * we return the amount of copyied data.
2773 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002774 max = chn->buf->size - buffer_len(chn->buf);
2775 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002776 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002777
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002778 if (l < len) {
2779 /* If we are waiting for space in the response buffer, we
2780 * must set the flag WAKERESWR. This flag required the task
2781 * wake up if any activity is detected on the response buffer.
2782 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002783 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002784 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002785 else
2786 HLUA_SET_WAKEREQWR(hlua);
2787 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002788 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002789
2790 return 1;
2791}
2792
2793/* Just a wraper of "_hlua_channel_send". This wrapper permits
2794 * yield the LUA process, and resume it without checking the
2795 * input arguments.
2796 */
2797__LJMP static int hlua_channel_send(lua_State *L)
2798{
2799 MAY_LJMP(check_args(L, 2, "send"));
2800 lua_pushinteger(L, 0);
2801
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002802 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002803}
2804
2805/* This function forward and amount of butes. The data pass from
2806 * the input side of the buffer to the output side, and can be
2807 * forwarded. This function never fails.
2808 *
2809 * The Lua function takes an amount of bytes to be forwarded in
2810 * imput. It returns the number of bytes forwarded.
2811 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002812__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002813{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002814 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002815 int len;
2816 int l;
2817 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002818 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002819
2820 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2821 len = MAY_LJMP(luaL_checkinteger(L, 2));
2822 l = MAY_LJMP(luaL_checkinteger(L, -1));
2823
2824 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002825 if (max > chn->buf->i)
2826 max = chn->buf->i;
2827 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002828 l += max;
2829
2830 lua_pop(L, 1);
2831 lua_pushinteger(L, l);
2832
2833 /* Check if it miss bytes to forward. */
2834 if (l < len) {
2835 /* The the input channel or the output channel are closed, we
2836 * must return the amount of data forwarded.
2837 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002838 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002839 return 1;
2840
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002841 /* If we are waiting for space data in the response buffer, we
2842 * must set the flag WAKERESWR. This flag required the task
2843 * wake up if any activity is detected on the response buffer.
2844 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002845 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002846 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002847 else
2848 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002849
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002850 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002851 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002852 }
2853
2854 return 1;
2855}
2856
2857/* Just check the input and prepare the stack for the previous
2858 * function "hlua_channel_forward_yield"
2859 */
2860__LJMP static int hlua_channel_forward(lua_State *L)
2861{
2862 MAY_LJMP(check_args(L, 2, "forward"));
2863 MAY_LJMP(hlua_checkchannel(L, 1));
2864 MAY_LJMP(luaL_checkinteger(L, 2));
2865
2866 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002867 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002868}
2869
2870/* Just returns the number of bytes available in the input
2871 * side of the buffer. This function never fails.
2872 */
2873__LJMP static int hlua_channel_get_in_len(lua_State *L)
2874{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002875 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002876
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002877 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002878 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002879 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002880 return 1;
2881}
2882
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01002883/* Returns true if the channel is full. */
2884__LJMP static int hlua_channel_is_full(lua_State *L)
2885{
2886 struct channel *chn;
2887 int rem;
2888
2889 MAY_LJMP(check_args(L, 1, "is_full"));
2890 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2891
2892 rem = chn->buf->size;
2893 rem -= chn->buf->o; /* Output size */
2894 rem -= chn->buf->i; /* Input size */
2895 rem -= global.tune.maxrewrite; /* Rewrite reserved size */
2896
2897 lua_pushboolean(L, rem <= 0);
2898 return 1;
2899}
2900
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002901/* Just returns the number of bytes available in the output
2902 * side of the buffer. This function never fails.
2903 */
2904__LJMP static int hlua_channel_get_out_len(lua_State *L)
2905{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002906 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002907
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002908 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002909 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002910 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002911 return 1;
2912}
2913
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002914/*
2915 *
2916 *
2917 * Class Fetches
2918 *
2919 *
2920 */
2921
2922/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002923 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002924 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002925__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002926{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002927 return MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002928}
2929
2930/* This function creates and push in the stack a fetch object according
2931 * with a current TXN.
2932 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002933static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002934{
Willy Tarreau7073c472015-04-06 11:15:40 +02002935 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002936
2937 /* Check stack size. */
2938 if (!lua_checkstack(L, 3))
2939 return 0;
2940
2941 /* Create the object: obj[0] = userdata.
2942 * Note that the base of the Fetches object is the
2943 * transaction object.
2944 */
2945 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002946 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002947 lua_rawseti(L, -2, 0);
2948
Willy Tarreau7073c472015-04-06 11:15:40 +02002949 hsmp->s = txn->s;
2950 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01002951 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01002952 hsmp->flags = flags;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002953
2954 /* Pop a class sesison metatable and affect it to the userdata. */
2955 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2956 lua_setmetatable(L, -2);
2957
2958 return 1;
2959}
2960
2961/* This function is an LUA binding. It is called with each sample-fetch.
2962 * It uses closure argument to store the associated sample-fetch. It
2963 * returns only one argument or throws an error. An error is thrown
2964 * only if an error is encountered during the argument parsing. If
2965 * the "sample-fetch" function fails, nil is returned.
2966 */
2967__LJMP static int hlua_run_sample_fetch(lua_State *L)
2968{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002969 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002970 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002971 struct arg args[ARGM_NBARGS + 1];
2972 int i;
2973 struct sample smp;
2974
2975 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002976 f = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002977
2978 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002979 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002980
Thierry FOURNIERca988662015-12-20 18:43:03 +01002981 /* Check execution authorization. */
2982 if (f->use & SMP_USE_HTTP_ANY &&
2983 !(hsmp->flags & HLUA_F_MAY_USE_HTTP)) {
2984 lua_pushfstring(L, "the sample-fetch '%s' needs an HTTP parser which "
2985 "is not available in Lua services", f->kw);
2986 WILL_LJMP(lua_error(L));
2987 }
2988
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002989 /* Get extra arguments. */
2990 for (i = 0; i < lua_gettop(L) - 1; i++) {
2991 if (i >= ARGM_NBARGS)
2992 break;
2993 hlua_lua2arg(L, i + 2, &args[i]);
2994 }
2995 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01002996 args[i].data.str.str = NULL;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002997
2998 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002999 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003000
3001 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01003002 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003003 lua_pushfstring(L, "error in arguments");
3004 WILL_LJMP(lua_error(L));
3005 }
3006
3007 /* Initialise the sample. */
3008 memset(&smp, 0, sizeof(smp));
3009
3010 /* Run the sample fetch process. */
Willy Tarreau1777ea62016-03-10 16:15:46 +01003011 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003012 if (!f->process(args, &smp, f->kw, f->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003013 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003014 lua_pushstring(L, "");
3015 else
3016 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003017 return 1;
3018 }
3019
3020 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003021 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003022 hlua_smp2lua_str(L, &smp);
3023 else
3024 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003025 return 1;
3026}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01003027
3028/*
3029 *
3030 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003031 * Class Converters
3032 *
3033 *
3034 */
3035
3036/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003037 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003038 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003039__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003040{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003041 return MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003042}
3043
3044/* This function creates and push in the stack a Converters object
3045 * according with a current TXN.
3046 */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003047static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, unsigned int flags)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003048{
Willy Tarreau7073c472015-04-06 11:15:40 +02003049 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003050
3051 /* Check stack size. */
3052 if (!lua_checkstack(L, 3))
3053 return 0;
3054
3055 /* Create the object: obj[0] = userdata.
3056 * Note that the base of the Converters object is the
3057 * same than the TXN object.
3058 */
3059 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02003060 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003061 lua_rawseti(L, -2, 0);
3062
Willy Tarreau7073c472015-04-06 11:15:40 +02003063 hsmp->s = txn->s;
3064 hsmp->p = txn->p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01003065 hsmp->dir = txn->dir;
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003066 hsmp->flags = flags;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003067
Willy Tarreau87b09662015-04-03 00:22:06 +02003068 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003069 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
3070 lua_setmetatable(L, -2);
3071
3072 return 1;
3073}
3074
3075/* This function is an LUA binding. It is called with each converter.
3076 * It uses closure argument to store the associated converter. It
3077 * returns only one argument or throws an error. An error is thrown
3078 * only if an error is encountered during the argument parsing. If
3079 * the converter function function fails, nil is returned.
3080 */
3081__LJMP static int hlua_run_sample_conv(lua_State *L)
3082{
Willy Tarreauda5f1082015-04-06 11:17:13 +02003083 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003084 struct sample_conv *conv;
3085 struct arg args[ARGM_NBARGS + 1];
3086 int i;
3087 struct sample smp;
3088
3089 /* Get closure arguments. */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003090 conv = lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003091
3092 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003093 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003094
3095 /* Get extra arguments. */
3096 for (i = 0; i < lua_gettop(L) - 2; i++) {
3097 if (i >= ARGM_NBARGS)
3098 break;
3099 hlua_lua2arg(L, i + 3, &args[i]);
3100 }
3101 args[i].type = ARGT_STOP;
David Carlierabdb00f2016-04-27 16:14:50 +01003102 args[i].data.str.str = NULL;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003103
3104 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003105 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003106
3107 /* Run the special args checker. */
3108 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
3109 hlua_pusherror(L, "error in arguments");
3110 WILL_LJMP(lua_error(L));
3111 }
3112
3113 /* Initialise the sample. */
3114 if (!hlua_lua2smp(L, 2, &smp)) {
3115 hlua_pusherror(L, "error in the input argument");
3116 WILL_LJMP(lua_error(L));
3117 }
3118
Willy Tarreau1777ea62016-03-10 16:15:46 +01003119 smp_set_owner(&smp, hsmp->p, hsmp->s->sess, hsmp->s, hsmp->dir & SMP_OPT_DIR);
3120
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003121 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003122 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003123 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003124 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003125 WILL_LJMP(lua_error(L));
3126 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003127 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3128 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003129 hlua_pusherror(L, "error during the input argument casting");
3130 WILL_LJMP(lua_error(L));
3131 }
3132
3133 /* Run the sample conversion process. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003134 if (!conv->process(args, &smp, conv->private)) {
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003135 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003136 lua_pushstring(L, "");
3137 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003138 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003139 return 1;
3140 }
3141
3142 /* Convert the returned sample in lua value. */
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003143 if (hsmp->flags & HLUA_F_AS_STRING)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003144 hlua_smp2lua_str(L, &smp);
3145 else
3146 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003147 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003148}
3149
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003150/*
3151 *
3152 *
3153 * Class AppletTCP
3154 *
3155 *
3156 */
3157
3158/* Returns a struct hlua_txn if the stack entry "ud" is
3159 * a class stream, otherwise it throws an error.
3160 */
3161__LJMP static struct hlua_appctx *hlua_checkapplet_tcp(lua_State *L, int ud)
3162{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003163 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_tcp_ref));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003164}
3165
3166/* This function creates and push in the stack an Applet object
3167 * according with a current TXN.
3168 */
3169static int hlua_applet_tcp_new(lua_State *L, struct appctx *ctx)
3170{
3171 struct hlua_appctx *appctx;
3172 struct stream_interface *si = ctx->owner;
3173 struct stream *s = si_strm(si);
3174 struct proxy *p = s->be;
3175
3176 /* Check stack size. */
3177 if (!lua_checkstack(L, 3))
3178 return 0;
3179
3180 /* Create the object: obj[0] = userdata.
3181 * Note that the base of the Converters object is the
3182 * same than the TXN object.
3183 */
3184 lua_newtable(L);
3185 appctx = lua_newuserdata(L, sizeof(*appctx));
3186 lua_rawseti(L, -2, 0);
3187 appctx->appctx = ctx;
3188 appctx->htxn.s = s;
3189 appctx->htxn.p = p;
3190
3191 /* Create the "f" field that contains a list of fetches. */
3192 lua_pushstring(L, "f");
3193 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3194 return 0;
3195 lua_settable(L, -3);
3196
3197 /* Create the "sf" field that contains a list of stringsafe fetches. */
3198 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003199 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003200 return 0;
3201 lua_settable(L, -3);
3202
3203 /* Create the "c" field that contains a list of converters. */
3204 lua_pushstring(L, "c");
3205 if (!hlua_converters_new(L, &appctx->htxn, 0))
3206 return 0;
3207 lua_settable(L, -3);
3208
3209 /* Create the "sc" field that contains a list of stringsafe converters. */
3210 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003211 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003212 return 0;
3213 lua_settable(L, -3);
3214
3215 /* Pop a class stream metatable and affect it to the table. */
3216 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_tcp_ref);
3217 lua_setmetatable(L, -2);
3218
3219 return 1;
3220}
3221
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003222__LJMP static int hlua_applet_tcp_set_var(lua_State *L)
3223{
3224 struct hlua_appctx *appctx;
3225 struct stream *s;
3226 const char *name;
3227 size_t len;
3228 struct sample smp;
3229
3230 MAY_LJMP(check_args(L, 3, "set_var"));
3231
3232 /* It is useles to retrieve the stream, but this function
3233 * runs only in a stream context.
3234 */
3235 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3236 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3237 s = appctx->htxn.s;
3238
3239 /* Converts the third argument in a sample. */
3240 hlua_lua2smp(L, 3, &smp);
3241
3242 /* Store the sample in a variable. */
3243 smp_set_owner(&smp, s->be, s->sess, s, 0);
3244 vars_set_by_name(name, len, &smp);
3245 return 0;
3246}
3247
3248__LJMP static int hlua_applet_tcp_unset_var(lua_State *L)
3249{
3250 struct hlua_appctx *appctx;
3251 struct stream *s;
3252 const char *name;
3253 size_t len;
3254 struct sample smp;
3255
3256 MAY_LJMP(check_args(L, 2, "unset_var"));
3257
3258 /* It is useles to retrieve the stream, but this function
3259 * runs only in a stream context.
3260 */
3261 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3262 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3263 s = appctx->htxn.s;
3264
3265 /* Unset the variable. */
3266 smp_set_owner(&smp, s->be, s->sess, s, 0);
3267 vars_unset_by_name(name, len, &smp);
3268 return 0;
3269}
3270
3271__LJMP static int hlua_applet_tcp_get_var(lua_State *L)
3272{
3273 struct hlua_appctx *appctx;
3274 struct stream *s;
3275 const char *name;
3276 size_t len;
3277 struct sample smp;
3278
3279 MAY_LJMP(check_args(L, 2, "get_var"));
3280
3281 /* It is useles to retrieve the stream, but this function
3282 * runs only in a stream context.
3283 */
3284 appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3285 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3286 s = appctx->htxn.s;
3287
3288 smp_set_owner(&smp, s->be, s->sess, s, 0);
3289 if (!vars_get_by_name(name, len, &smp)) {
3290 lua_pushnil(L);
3291 return 1;
3292 }
3293
3294 return hlua_smp2lua(L, &smp);
3295}
3296
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003297__LJMP static int hlua_applet_tcp_set_priv(lua_State *L)
3298{
3299 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3300 struct stream *s = appctx->htxn.s;
3301 struct hlua *hlua = &s->hlua;
3302
3303 MAY_LJMP(check_args(L, 2, "set_priv"));
3304
3305 /* Remove previous value. */
3306 if (hlua->Mref != -1)
3307 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3308
3309 /* Get and store new value. */
3310 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3311 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3312
3313 return 0;
3314}
3315
3316__LJMP static int hlua_applet_tcp_get_priv(lua_State *L)
3317{
3318 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3319 struct stream *s = appctx->htxn.s;
3320 struct hlua *hlua = &s->hlua;
3321
3322 /* Push configuration index in the stack. */
3323 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3324
3325 return 1;
3326}
3327
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02003328/* If expected data not yet available, it returns a yield. This function
3329 * consumes the data in the buffer. It returns a string containing the
3330 * data. This string can be empty.
3331 */
3332__LJMP static int hlua_applet_tcp_getline_yield(lua_State *L, int status, lua_KContext ctx)
3333{
3334 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3335 struct stream_interface *si = appctx->appctx->owner;
3336 int ret;
3337 char *blk1;
3338 int len1;
3339 char *blk2;
3340 int len2;
3341
3342 /* Read the maximum amount of data avalaible. */
3343 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3344
3345 /* Data not yet avalaible. return yield. */
3346 if (ret == 0) {
3347 si_applet_cant_get(si);
3348 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_getline_yield, TICK_ETERNITY, 0));
3349 }
3350
3351 /* End of data: commit the total strings and return. */
3352 if (ret < 0) {
3353 luaL_pushresult(&appctx->b);
3354 return 1;
3355 }
3356
3357 /* Ensure that the block 2 length is usable. */
3358 if (ret == 1)
3359 len2 = 0;
3360
3361 /* dont check the max length read and dont check. */
3362 luaL_addlstring(&appctx->b, blk1, len1);
3363 luaL_addlstring(&appctx->b, blk2, len2);
3364
3365 /* Consume input channel output buffer data. */
3366 bo_skip(si_oc(si), len1 + len2);
3367 luaL_pushresult(&appctx->b);
3368 return 1;
3369}
3370
3371/* Check arguments for the fucntion "hlua_channel_get_yield". */
3372__LJMP static int hlua_applet_tcp_getline(lua_State *L)
3373{
3374 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3375
3376 /* Initialise the string catenation. */
3377 luaL_buffinit(L, &appctx->b);
3378
3379 return MAY_LJMP(hlua_applet_tcp_getline_yield(L, 0, 0));
3380}
3381
3382/* If expected data not yet available, it returns a yield. This function
3383 * consumes the data in the buffer. It returns a string containing the
3384 * data. This string can be empty.
3385 */
3386__LJMP static int hlua_applet_tcp_recv_yield(lua_State *L, int status, lua_KContext ctx)
3387{
3388 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3389 struct stream_interface *si = appctx->appctx->owner;
3390 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3391 int ret;
3392 char *blk1;
3393 int len1;
3394 char *blk2;
3395 int len2;
3396
3397 /* Read the maximum amount of data avalaible. */
3398 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
3399
3400 /* Data not yet avalaible. return yield. */
3401 if (ret == 0) {
3402 si_applet_cant_get(si);
3403 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3404 }
3405
3406 /* End of data: commit the total strings and return. */
3407 if (ret < 0) {
3408 luaL_pushresult(&appctx->b);
3409 return 1;
3410 }
3411
3412 /* Ensure that the block 2 length is usable. */
3413 if (ret == 1)
3414 len2 = 0;
3415
3416 if (len == -1) {
3417
3418 /* If len == -1, catenate all the data avalaile and
3419 * yield because we want to get all the data until
3420 * the end of data stream.
3421 */
3422 luaL_addlstring(&appctx->b, blk1, len1);
3423 luaL_addlstring(&appctx->b, blk2, len2);
3424 bo_skip(si_oc(si), len1 + len2);
3425 si_applet_cant_get(si);
3426 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3427
3428 } else {
3429
3430 /* Copy the fisrt block caping to the length required. */
3431 if (len1 > len)
3432 len1 = len;
3433 luaL_addlstring(&appctx->b, blk1, len1);
3434 len -= len1;
3435
3436 /* Copy the second block. */
3437 if (len2 > len)
3438 len2 = len;
3439 luaL_addlstring(&appctx->b, blk2, len2);
3440 len -= len2;
3441
3442 /* Consume input channel output buffer data. */
3443 bo_skip(si_oc(si), len1 + len2);
3444
3445 /* If we are no other data avalaible, yield waiting for new data. */
3446 if (len > 0) {
3447 lua_pushinteger(L, len);
3448 lua_replace(L, 2);
3449 si_applet_cant_get(si);
3450 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_recv_yield, TICK_ETERNITY, 0));
3451 }
3452
3453 /* return the result. */
3454 luaL_pushresult(&appctx->b);
3455 return 1;
3456 }
3457
3458 /* we never executes this */
3459 hlua_pusherror(L, "Lua: internal error");
3460 WILL_LJMP(lua_error(L));
3461 return 0;
3462}
3463
3464/* Check arguments for the fucntion "hlua_channel_get_yield". */
3465__LJMP static int hlua_applet_tcp_recv(lua_State *L)
3466{
3467 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3468 int len = -1;
3469
3470 if (lua_gettop(L) > 2)
3471 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3472 if (lua_gettop(L) >= 2) {
3473 len = MAY_LJMP(luaL_checkinteger(L, 2));
3474 lua_pop(L, 1);
3475 }
3476
3477 /* Confirm or set the required length */
3478 lua_pushinteger(L, len);
3479
3480 /* Initialise the string catenation. */
3481 luaL_buffinit(L, &appctx->b);
3482
3483 return MAY_LJMP(hlua_applet_tcp_recv_yield(L, 0, 0));
3484}
3485
3486/* Append data in the output side of the buffer. This data is immediatly
3487 * sent. The fcuntion returns the ammount of data writed. If the buffer
3488 * cannot contains the data, the function yield. The function returns -1
3489 * if the channel is closed.
3490 */
3491__LJMP static int hlua_applet_tcp_send_yield(lua_State *L, int status, lua_KContext ctx)
3492{
3493 size_t len;
3494 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_tcp(L, 1));
3495 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3496 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3497 struct stream_interface *si = appctx->appctx->owner;
3498 struct channel *chn = si_ic(si);
3499 int max;
3500
3501 /* Get the max amount of data which can write as input in the channel. */
3502 max = channel_recv_max(chn);
3503 if (max > (len - l))
3504 max = len - l;
3505
3506 /* Copy data. */
3507 bi_putblk(chn, str + l, max);
3508
3509 /* update counters. */
3510 l += max;
3511 lua_pop(L, 1);
3512 lua_pushinteger(L, l);
3513
3514 /* If some data is not send, declares the situation to the
3515 * applet, and returns a yield.
3516 */
3517 if (l < len) {
3518 si_applet_cant_put(si);
3519 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_tcp_send_yield, TICK_ETERNITY, 0));
3520 }
3521
3522 return 1;
3523}
3524
3525/* Just a wraper of "hlua_applet_tcp_send_yield". This wrapper permits
3526 * yield the LUA process, and resume it without checking the
3527 * input arguments.
3528 */
3529__LJMP static int hlua_applet_tcp_send(lua_State *L)
3530{
3531 MAY_LJMP(check_args(L, 2, "send"));
3532 lua_pushinteger(L, 0);
3533
3534 return MAY_LJMP(hlua_applet_tcp_send_yield(L, 0, 0));
3535}
3536
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003537/*
3538 *
3539 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003540 * Class AppletHTTP
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003541 *
3542 *
3543 */
3544
3545/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003546 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003547 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003548__LJMP static struct hlua_appctx *hlua_checkapplet_http(lua_State *L, int ud)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003549{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02003550 return MAY_LJMP(hlua_checkudata(L, ud, class_applet_http_ref));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003551}
3552
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003553/* This function creates and push in the stack an Applet object
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003554 * according with a current TXN.
3555 */
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003556static int hlua_applet_http_new(lua_State *L, struct appctx *ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003557{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003558 struct hlua_appctx *appctx;
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003559 struct hlua_txn htxn;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003560 struct stream_interface *si = ctx->owner;
3561 struct stream *s = si_strm(si);
3562 struct proxy *px = s->be;
3563 struct http_txn *txn = s->txn;
3564 const char *path;
3565 const char *end;
3566 const char *p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003567
3568 /* Check stack size. */
3569 if (!lua_checkstack(L, 3))
3570 return 0;
3571
3572 /* Create the object: obj[0] = userdata.
3573 * Note that the base of the Converters object is the
3574 * same than the TXN object.
3575 */
3576 lua_newtable(L);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003577 appctx = lua_newuserdata(L, sizeof(*appctx));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003578 lua_rawseti(L, -2, 0);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003579 appctx->appctx = ctx;
3580 appctx->appctx->ctx.hlua_apphttp.status = 200; /* Default status code returned. */
3581 appctx->htxn.s = s;
3582 appctx->htxn.p = px;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003583
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003584 /* Create the "f" field that contains a list of fetches. */
3585 lua_pushstring(L, "f");
3586 if (!hlua_fetches_new(L, &appctx->htxn, 0))
3587 return 0;
3588 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003589
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003590 /* Create the "sf" field that contains a list of stringsafe fetches. */
3591 lua_pushstring(L, "sf");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003592 if (!hlua_fetches_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003593 return 0;
3594 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003595
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003596 /* Create the "c" field that contains a list of converters. */
3597 lua_pushstring(L, "c");
3598 if (!hlua_converters_new(L, &appctx->htxn, 0))
3599 return 0;
3600 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003601
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003602 /* Create the "sc" field that contains a list of stringsafe converters. */
3603 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01003604 if (!hlua_converters_new(L, &appctx->htxn, HLUA_F_AS_STRING))
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003605 return 0;
3606 lua_settable(L, -3);
Willy Tarreaueee5b512015-04-03 23:46:31 +02003607
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003608 /* Stores the request method. */
3609 lua_pushstring(L, "method");
3610 lua_pushlstring(L, txn->req.chn->buf->p, txn->req.sl.rq.m_l);
3611 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003612
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003613 /* Stores the http version. */
3614 lua_pushstring(L, "version");
3615 lua_pushlstring(L, txn->req.chn->buf->p + txn->req.sl.rq.v, txn->req.sl.rq.v_l);
3616 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003617
Thierry FOURNIER841475e2015-12-11 17:10:09 +01003618 /* creates an array of headers. hlua_http_get_headers() crates and push
3619 * the array on the top of the stack.
3620 */
3621 lua_pushstring(L, "headers");
3622 htxn.s = s;
3623 htxn.p = px;
3624 htxn.dir = SMP_OPT_DIR_REQ;
3625 if (!hlua_http_get_headers(L, &htxn, &htxn.s->txn->req))
3626 return 0;
3627 lua_settable(L, -3);
3628
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003629 /* Get path and qs */
3630 path = http_get_path(txn);
3631 end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
3632 p = path;
3633 while (p < end && *p != '?')
3634 p++;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003635
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003636 /* Stores the request path. */
3637 lua_pushstring(L, "path");
3638 lua_pushlstring(L, path, p - path);
3639 lua_settable(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003640
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003641 /* Stores the query string. */
3642 lua_pushstring(L, "qs");
3643 if (*p == '?')
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003644 p++;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003645 lua_pushlstring(L, p, end - p);
3646 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003647
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003648 /* Stores the request path. */
3649 lua_pushstring(L, "length");
3650 lua_pushinteger(L, txn->req.body_len);
3651 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003652
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003653 /* Create an array of HTTP request headers. */
3654 lua_pushstring(L, "headers");
3655 MAY_LJMP(hlua_http_get_headers(L, &appctx->htxn, &appctx->htxn.s->txn->req));
3656 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003657
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003658 /* Create an empty array of HTTP request headers. */
3659 lua_pushstring(L, "response");
3660 lua_newtable(L);
3661 lua_settable(L, -3);
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003662
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003663 /* Pop a class stream metatable and affect it to the table. */
3664 lua_rawgeti(L, LUA_REGISTRYINDEX, class_applet_http_ref);
3665 lua_setmetatable(L, -2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003666
3667 return 1;
3668}
3669
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01003670__LJMP static int hlua_applet_http_set_var(lua_State *L)
3671{
3672 struct hlua_appctx *appctx;
3673 struct stream *s;
3674 const char *name;
3675 size_t len;
3676 struct sample smp;
3677
3678 MAY_LJMP(check_args(L, 3, "set_var"));
3679
3680 /* It is useles to retrieve the stream, but this function
3681 * runs only in a stream context.
3682 */
3683 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3684 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3685 s = appctx->htxn.s;
3686
3687 /* Converts the third argument in a sample. */
3688 hlua_lua2smp(L, 3, &smp);
3689
3690 /* Store the sample in a variable. */
3691 smp_set_owner(&smp, s->be, s->sess, s, 0);
3692 vars_set_by_name(name, len, &smp);
3693 return 0;
3694}
3695
3696__LJMP static int hlua_applet_http_unset_var(lua_State *L)
3697{
3698 struct hlua_appctx *appctx;
3699 struct stream *s;
3700 const char *name;
3701 size_t len;
3702 struct sample smp;
3703
3704 MAY_LJMP(check_args(L, 2, "unset_var"));
3705
3706 /* It is useles to retrieve the stream, but this function
3707 * runs only in a stream context.
3708 */
3709 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3710 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3711 s = appctx->htxn.s;
3712
3713 /* Unset the variable. */
3714 smp_set_owner(&smp, s->be, s->sess, s, 0);
3715 vars_unset_by_name(name, len, &smp);
3716 return 0;
3717}
3718
3719__LJMP static int hlua_applet_http_get_var(lua_State *L)
3720{
3721 struct hlua_appctx *appctx;
3722 struct stream *s;
3723 const char *name;
3724 size_t len;
3725 struct sample smp;
3726
3727 MAY_LJMP(check_args(L, 2, "get_var"));
3728
3729 /* It is useles to retrieve the stream, but this function
3730 * runs only in a stream context.
3731 */
3732 appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3733 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3734 s = appctx->htxn.s;
3735
3736 smp_set_owner(&smp, s->be, s->sess, s, 0);
3737 if (!vars_get_by_name(name, len, &smp)) {
3738 lua_pushnil(L);
3739 return 1;
3740 }
3741
3742 return hlua_smp2lua(L, &smp);
3743}
3744
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01003745__LJMP static int hlua_applet_http_set_priv(lua_State *L)
3746{
3747 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3748 struct stream *s = appctx->htxn.s;
3749 struct hlua *hlua = &s->hlua;
3750
3751 MAY_LJMP(check_args(L, 2, "set_priv"));
3752
3753 /* Remove previous value. */
3754 if (hlua->Mref != -1)
3755 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3756
3757 /* Get and store new value. */
3758 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3759 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3760
3761 return 0;
3762}
3763
3764__LJMP static int hlua_applet_http_get_priv(lua_State *L)
3765{
3766 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3767 struct stream *s = appctx->htxn.s;
3768 struct hlua *hlua = &s->hlua;
3769
3770 /* Push configuration index in the stack. */
3771 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3772
3773 return 1;
3774}
3775
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003776/* If expected data not yet available, it returns a yield. This function
3777 * consumes the data in the buffer. It returns a string containing the
3778 * data. This string can be empty.
3779 */
3780__LJMP static int hlua_applet_http_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003781{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003782 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3783 struct stream_interface *si = appctx->appctx->owner;
3784 struct channel *chn = si_ic(si);
3785 int ret;
3786 char *blk1;
3787 int len1;
3788 char *blk2;
3789 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003790
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003791 /* Maybe we cant send a 100-continue ? */
3792 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3793 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3794 /* if ret == -2 or -3 the channel closed or the message si too
3795 * big for the buffers. We cant send anything. So, we ignoring
3796 * the error, considers that the 100-continue is sent, and try
3797 * to receive.
3798 * If ret is -1, we dont have room in the buffer, so we yield.
3799 */
3800 if (ret == -1) {
3801 si_applet_cant_put(si);
3802 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3803 }
3804 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3805 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003806
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003807 /* Check for the end of the data. */
3808 if (appctx->appctx->ctx.hlua_apphttp.left_bytes <= 0) {
3809 luaL_pushresult(&appctx->b);
3810 return 1;
3811 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003812
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003813 /* Read the maximum amount of data avalaible. */
3814 ret = bo_getline_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003815
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003816 /* Data not yet avalaible. return yield. */
3817 if (ret == 0) {
3818 si_applet_cant_get(si);
3819 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_getline_yield, TICK_ETERNITY, 0));
3820 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003821
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003822 /* End of data: commit the total strings and return. */
3823 if (ret < 0) {
3824 luaL_pushresult(&appctx->b);
3825 return 1;
3826 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003827
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003828 /* Ensure that the block 2 length is usable. */
3829 if (ret == 1)
3830 len2 = 0;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003831
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003832 /* Copy the fisrt block caping to the length required. */
3833 if (len1 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3834 len1 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3835 luaL_addlstring(&appctx->b, blk1, len1);
3836 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003837
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003838 /* Copy the second block. */
3839 if (len2 > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3840 len2 = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3841 luaL_addlstring(&appctx->b, blk2, len2);
3842 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003843
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003844 /* Consume input channel output buffer data. */
3845 bo_skip(si_oc(si), len1 + len2);
3846 luaL_pushresult(&appctx->b);
3847 return 1;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003848}
3849
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003850/* Check arguments for the fucntion "hlua_channel_get_yield". */
3851__LJMP static int hlua_applet_http_getline(lua_State *L)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003852{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003853 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003854
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003855 /* Initialise the string catenation. */
3856 luaL_buffinit(L, &appctx->b);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003857
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003858 return MAY_LJMP(hlua_applet_http_getline_yield(L, 0, 0));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003859}
3860
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003861/* If expected data not yet available, it returns a yield. This function
3862 * consumes the data in the buffer. It returns a string containing the
3863 * data. This string can be empty.
3864 */
3865__LJMP static int hlua_applet_http_recv_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003866{
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003867 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3868 struct stream_interface *si = appctx->appctx->owner;
3869 int len = MAY_LJMP(luaL_checkinteger(L, 2));
3870 struct channel *chn = si_ic(si);
3871 int ret;
3872 char *blk1;
3873 int len1;
3874 char *blk2;
3875 int len2;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003876
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003877 /* Maybe we cant send a 100-continue ? */
3878 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_100C) {
3879 ret = bi_putblk(chn, HTTP_100C, strlen(HTTP_100C));
3880 /* if ret == -2 or -3 the channel closed or the message si too
3881 * big for the buffers. We cant send anything. So, we ignoring
3882 * the error, considers that the 100-continue is sent, and try
3883 * to receive.
3884 * If ret is -1, we dont have room in the buffer, so we yield.
3885 */
3886 if (ret == -1) {
3887 si_applet_cant_put(si);
3888 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3889 }
3890 appctx->appctx->ctx.hlua_apphttp.flags &= ~APPLET_100C;
3891 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003892
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003893 /* Read the maximum amount of data avalaible. */
3894 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003895
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02003896 /* Data not yet avalaible. return yield. */
3897 if (ret == 0) {
3898 si_applet_cant_get(si);
3899 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3900 }
3901
3902 /* End of data: commit the total strings and return. */
3903 if (ret < 0) {
3904 luaL_pushresult(&appctx->b);
3905 return 1;
3906 }
3907
3908 /* Ensure that the block 2 length is usable. */
3909 if (ret == 1)
3910 len2 = 0;
3911
3912 /* Copy the fisrt block caping to the length required. */
3913 if (len1 > len)
3914 len1 = len;
3915 luaL_addlstring(&appctx->b, blk1, len1);
3916 len -= len1;
3917
3918 /* Copy the second block. */
3919 if (len2 > len)
3920 len2 = len;
3921 luaL_addlstring(&appctx->b, blk2, len2);
3922 len -= len2;
3923
3924 /* Consume input channel output buffer data. */
3925 bo_skip(si_oc(si), len1 + len2);
3926 if (appctx->appctx->ctx.hlua_apphttp.left_bytes != -1)
3927 appctx->appctx->ctx.hlua_apphttp.left_bytes -= len;
3928
3929 /* If we are no other data avalaible, yield waiting for new data. */
3930 if (len > 0) {
3931 lua_pushinteger(L, len);
3932 lua_replace(L, 2);
3933 si_applet_cant_get(si);
3934 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_recv_yield, TICK_ETERNITY, 0));
3935 }
3936
3937 /* return the result. */
3938 luaL_pushresult(&appctx->b);
3939 return 1;
3940}
3941
3942/* Check arguments for the fucntion "hlua_channel_get_yield". */
3943__LJMP static int hlua_applet_http_recv(lua_State *L)
3944{
3945 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3946 int len = -1;
3947
3948 /* Check arguments. */
3949 if (lua_gettop(L) > 2)
3950 WILL_LJMP(luaL_error(L, "The 'recv' function requires between 1 and 2 arguments."));
3951 if (lua_gettop(L) >= 2) {
3952 len = MAY_LJMP(luaL_checkinteger(L, 2));
3953 lua_pop(L, 1);
3954 }
3955
3956 /* Check the required length */
3957 if (len == -1 || len > appctx->appctx->ctx.hlua_apphttp.left_bytes)
3958 len = appctx->appctx->ctx.hlua_apphttp.left_bytes;
3959 lua_pushinteger(L, len);
3960
3961 /* Initialise the string catenation. */
3962 luaL_buffinit(L, &appctx->b);
3963
3964 return MAY_LJMP(hlua_applet_http_recv_yield(L, 0, 0));
3965}
3966
3967/* Append data in the output side of the buffer. This data is immediatly
3968 * sent. The fcuntion returns the ammount of data writed. If the buffer
3969 * cannot contains the data, the function yield. The function returns -1
3970 * if the channel is closed.
3971 */
3972__LJMP static int hlua_applet_http_send_yield(lua_State *L, int status, lua_KContext ctx)
3973{
3974 size_t len;
3975 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
3976 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
3977 int l = MAY_LJMP(luaL_checkinteger(L, 3));
3978 struct stream_interface *si = appctx->appctx->owner;
3979 struct channel *chn = si_ic(si);
3980 int max;
3981
3982 /* Get the max amount of data which can write as input in the channel. */
3983 max = channel_recv_max(chn);
3984 if (max > (len - l))
3985 max = len - l;
3986
3987 /* Copy data. */
3988 bi_putblk(chn, str + l, max);
3989
3990 /* update counters. */
3991 l += max;
3992 lua_pop(L, 1);
3993 lua_pushinteger(L, l);
3994
3995 /* If some data is not send, declares the situation to the
3996 * applet, and returns a yield.
3997 */
3998 if (l < len) {
3999 si_applet_cant_put(si);
4000 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_send_yield, TICK_ETERNITY, 0));
4001 }
4002
4003 return 1;
4004}
4005
4006/* Just a wraper of "hlua_applet_send_yield". This wrapper permits
4007 * yield the LUA process, and resume it without checking the
4008 * input arguments.
4009 */
4010__LJMP static int hlua_applet_http_send(lua_State *L)
4011{
4012 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4013 size_t len;
4014 char hex[10];
4015
4016 MAY_LJMP(luaL_checklstring(L, 2, &len));
4017
4018 /* If transfer encoding chunked is selected, we surround the data
4019 * by chunk data.
4020 */
4021 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED) {
4022 snprintf(hex, 9, "%x", (unsigned int)len);
4023 lua_pushfstring(L, "%s\r\n", hex);
4024 lua_insert(L, 2); /* swap the last 2 entries. */
4025 lua_pushstring(L, "\r\n");
4026 lua_concat(L, 3);
4027 }
4028
4029 /* This interger is used for followinf the amount of data sent. */
4030 lua_pushinteger(L, 0);
4031
4032 /* We want to send some data. Headers must be sent. */
4033 if (!(appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HDR_SENT)) {
4034 hlua_pusherror(L, "Lua: 'send' you must call start_response() before sending data.");
4035 WILL_LJMP(lua_error(L));
4036 }
4037
4038 return MAY_LJMP(hlua_applet_http_send_yield(L, 0, 0));
4039}
4040
4041__LJMP static int hlua_applet_http_addheader(lua_State *L)
4042{
4043 const char *name;
4044 int ret;
4045
4046 MAY_LJMP(hlua_checkapplet_http(L, 1));
4047 name = MAY_LJMP(luaL_checkstring(L, 2));
4048 MAY_LJMP(luaL_checkstring(L, 3));
4049
4050 /* Push in the stack the "response" entry. */
4051 ret = lua_getfield(L, 1, "response");
4052 if (ret != LUA_TTABLE) {
4053 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response'] "
4054 "is expected as an array. %s found", lua_typename(L, ret));
4055 WILL_LJMP(lua_error(L));
4056 }
4057
4058 /* check if the header is already registered if it is not
4059 * the case, register it.
4060 */
4061 ret = lua_getfield(L, -1, name);
4062 if (ret == LUA_TNIL) {
4063
4064 /* Entry not found. */
4065 lua_pop(L, 1); /* remove the nil. The "response" table is the top of the stack. */
4066
4067 /* Insert the new header name in the array in the top of the stack.
4068 * It left the new array in the top of the stack.
4069 */
4070 lua_newtable(L);
4071 lua_pushvalue(L, 2);
4072 lua_pushvalue(L, -2);
4073 lua_settable(L, -4);
4074
4075 } else if (ret != LUA_TTABLE) {
4076
4077 /* corruption error. */
4078 hlua_pusherror(L, "Lua: 'add_header' internal error: AppletHTTP['response']['%s'] "
4079 "is expected as an array. %s found", name, lua_typename(L, ret));
4080 WILL_LJMP(lua_error(L));
4081 }
4082
4083 /* Now the top od thestack is an array of values. We push
4084 * the header value as new entry.
4085 */
4086 lua_pushvalue(L, 3);
4087 ret = lua_rawlen(L, -2);
4088 lua_rawseti(L, -2, ret + 1);
4089 lua_pushboolean(L, 1);
4090 return 1;
4091}
4092
4093__LJMP static int hlua_applet_http_status(lua_State *L)
4094{
4095 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4096 int status = MAY_LJMP(luaL_checkinteger(L, 2));
4097
4098 if (status < 100 || status > 599) {
4099 lua_pushboolean(L, 0);
4100 return 1;
4101 }
4102
4103 appctx->appctx->ctx.hlua_apphttp.status = status;
4104 lua_pushboolean(L, 1);
4105 return 1;
4106}
4107
4108/* We will build the status line and the headers of the HTTP response.
4109 * We will try send at once if its not possible, we give back the hand
4110 * waiting for more room.
4111 */
4112__LJMP static int hlua_applet_http_start_response_yield(lua_State *L, int status, lua_KContext ctx)
4113{
4114 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
4115 struct stream_interface *si = appctx->appctx->owner;
4116 struct channel *chn = si_ic(si);
4117 int ret;
4118 size_t len;
4119 const char *msg;
4120
4121 /* Get the message as the first argument on the stack. */
4122 msg = MAY_LJMP(luaL_checklstring(L, 2, &len));
4123
4124 /* Send the message at once. */
4125 ret = bi_putblk(chn, msg, len);
4126
4127 /* if ret == -2 or -3 the channel closed or the message si too
4128 * big for the buffers.
4129 */
4130 if (ret == -2 || ret == -3) {
4131 hlua_pusherror(L, "Lua: 'start_response': response header block too big");
4132 WILL_LJMP(lua_error(L));
4133 }
4134
4135 /* If ret is -1, we dont have room in the buffer, so we yield. */
4136 if (ret == -1) {
4137 si_applet_cant_put(si);
4138 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_applet_http_start_response_yield, TICK_ETERNITY, 0));
4139 }
4140
4141 /* Headers sent, set the flag. */
4142 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_HDR_SENT;
4143 return 0;
4144}
4145
4146__LJMP static int hlua_applet_http_start_response(lua_State *L)
4147{
4148 struct chunk *tmp = get_trash_chunk();
4149 struct hlua_appctx *appctx = MAY_LJMP(hlua_checkapplet_http(L, 1));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004150 const char *name;
4151 const char *value;
4152 int id;
4153 int hdr_connection = 0;
4154 int hdr_contentlength = -1;
4155 int hdr_chunked = 0;
4156
4157 /* Use the same http version than the request. */
4158 chunk_appendf(tmp, "HTTP/1.%c %d %s\r\n",
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004159 appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 ? '1' : '0',
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004160 appctx->appctx->ctx.hlua_apphttp.status,
4161 get_reason(appctx->appctx->ctx.hlua_apphttp.status));
4162
4163 /* Get the array associated to the field "response" in the object AppletHTTP. */
4164 lua_pushvalue(L, 0);
4165 if (lua_getfield(L, 1, "response") != LUA_TTABLE) {
4166 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'] missing.\n",
4167 appctx->appctx->rule->arg.hlua_rule->fcn.name);
4168 WILL_LJMP(lua_error(L));
4169 }
4170
4171 /* Browse the list of headers. */
4172 lua_pushnil(L);
4173 while(lua_next(L, -2) != 0) {
4174
4175 /* We expect a string as -2. */
4176 if (lua_type(L, -2) != LUA_TSTRING) {
4177 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response'][] element must be a string. got %s.\n",
4178 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4179 lua_typename(L, lua_type(L, -2)));
4180 WILL_LJMP(lua_error(L));
4181 }
4182 name = lua_tostring(L, -2);
4183
4184 /* We expect an array as -1. */
4185 if (lua_type(L, -1) != LUA_TTABLE) {
4186 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'] element must be an table. got %s.\n",
4187 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4188 name,
4189 lua_typename(L, lua_type(L, -1)));
4190 WILL_LJMP(lua_error(L));
4191 }
4192
4193 /* Browse the table who is on the top of the stack. */
4194 lua_pushnil(L);
4195 while(lua_next(L, -2) != 0) {
4196
4197 /* We expect a number as -2. */
4198 if (lua_type(L, -2) != LUA_TNUMBER) {
4199 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][] element must be a number. got %s.\n",
4200 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4201 name,
4202 lua_typename(L, lua_type(L, -2)));
4203 WILL_LJMP(lua_error(L));
4204 }
4205 id = lua_tointeger(L, -2);
4206
4207 /* We expect a string as -2. */
4208 if (lua_type(L, -1) != LUA_TSTRING) {
4209 hlua_pusherror(L, "Lua applet http '%s': AppletHTTP['response']['%s'][%d] element must be a string. got %s.\n",
4210 appctx->appctx->rule->arg.hlua_rule->fcn.name,
4211 name, id,
4212 lua_typename(L, lua_type(L, -1)));
4213 WILL_LJMP(lua_error(L));
4214 }
4215 value = lua_tostring(L, -1);
4216
4217 /* Catenate a new header. */
4218 chunk_appendf(tmp, "%s: %s\r\n", name, value);
4219
4220 /* Protocol checks. */
4221
4222 /* Check if the header conneciton is present. */
4223 if (strcasecmp("connection", name) == 0)
4224 hdr_connection = 1;
4225
4226 /* Copy the header content length. The length conversion
4227 * is done without control. If it contains a ad value, this
4228 * is not our problem.
4229 */
4230 if (strcasecmp("content-length", name) == 0)
4231 hdr_contentlength = atoi(value);
4232
4233 /* Check if the client annouces a transfer-encoding chunked it self. */
4234 if (strcasecmp("transfer-encoding", name) == 0 &&
4235 strcasecmp("chunked", value) == 0)
4236 hdr_chunked = 1;
4237
4238 /* Remove the array from the stack, and get next element with a remaining string. */
4239 lua_pop(L, 1);
4240 }
4241
4242 /* Remove the array from the stack, and get next element with a remaining string. */
4243 lua_pop(L, 1);
4244 }
4245
4246 /* If the http protocol version is 1.1, we expect an header "connection" set
4247 * to "close" to be HAProxy/keeplive compliant. Otherwise, we expect nothing.
4248 * If the header conneciton is present, don't change it, if it is not present,
4249 * we must set.
4250 *
4251 * we set a "connection: close" header for ensuring that the keepalive will be
4252 * respected by haproxy. HAProcy considers that the application cloe the connection
4253 * and it keep the connection from the client open.
4254 */
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01004255 if (appctx->appctx->ctx.hlua_apphttp.flags & APPLET_HTTP11 && !hdr_connection)
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004256 chunk_appendf(tmp, "Connection: close\r\n");
4257
4258 /* If we dont have a content-length set, we must announce a transfer enconding
4259 * chunked. This is required by haproxy for the keepalive compliance.
4260 * If the applet annouce a transfer-encoding chunked itslef, don't
4261 * do anything.
4262 */
4263 if (hdr_contentlength == -1 && hdr_chunked == 0) {
4264 chunk_appendf(tmp, "Transfer-encoding: chunked\r\n");
4265 appctx->appctx->ctx.hlua_apphttp.flags |= APPLET_CHUNKED;
4266 }
4267
4268 /* Finalize headers. */
4269 chunk_appendf(tmp, "\r\n");
4270
4271 /* Remove the last entry and the array of headers */
4272 lua_pop(L, 2);
4273
4274 /* Push the headers block. */
4275 lua_pushlstring(L, tmp->str, tmp->len);
4276
4277 return MAY_LJMP(hlua_applet_http_start_response_yield(L, 0, 0));
4278}
4279
4280/*
4281 *
4282 *
4283 * Class HTTP
4284 *
4285 *
4286 */
4287
4288/* Returns a struct hlua_txn if the stack entry "ud" is
4289 * a class stream, otherwise it throws an error.
4290 */
4291__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
4292{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004293 return MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004294}
4295
4296/* This function creates and push in the stack a HTTP object
4297 * according with a current TXN.
4298 */
4299static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
4300{
4301 struct hlua_txn *htxn;
4302
4303 /* Check stack size. */
4304 if (!lua_checkstack(L, 3))
4305 return 0;
4306
4307 /* Create the object: obj[0] = userdata.
4308 * Note that the base of the Converters object is the
4309 * same than the TXN object.
4310 */
4311 lua_newtable(L);
4312 htxn = lua_newuserdata(L, sizeof(*htxn));
4313 lua_rawseti(L, -2, 0);
4314
4315 htxn->s = txn->s;
4316 htxn->p = txn->p;
4317
4318 /* Pop a class stream metatable and affect it to the table. */
4319 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
4320 lua_setmetatable(L, -2);
4321
4322 return 1;
4323}
4324
4325/* This function creates ans returns an array of HTTP headers.
4326 * This function does not fails. It is used as wrapper with the
4327 * 2 following functions.
4328 */
4329__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4330{
4331 const char *cur_ptr, *cur_next, *p;
4332 int old_idx, cur_idx;
4333 struct hdr_idx_elem *cur_hdr;
4334 const char *hn, *hv;
4335 int hnl, hvl;
4336 int type;
4337 const char *in;
4338 char *out;
4339 int len;
4340
4341 /* Create the table. */
4342 lua_newtable(L);
4343
4344 if (!htxn->s->txn)
4345 return 1;
4346
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004347 /* Check if a valid response is parsed */
4348 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4349 return 1;
4350
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004351 /* Build array of headers. */
4352 old_idx = 0;
4353 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
4354
4355 while (1) {
4356 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
4357 if (!cur_idx)
4358 break;
4359 old_idx = cur_idx;
4360
4361 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
4362 cur_ptr = cur_next;
4363 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
4364
4365 /* Now we have one full header at cur_ptr of len cur_hdr->len,
4366 * and the next header starts at cur_next. We'll check
4367 * this header in the list as well as against the default
4368 * rule.
4369 */
4370
4371 /* look for ': *'. */
4372 hn = cur_ptr;
4373 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
4374 if (p >= cur_ptr+cur_hdr->len)
4375 continue;
4376 hnl = p - hn;
4377 p++;
4378 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
4379 p++;
4380 if (p >= cur_ptr+cur_hdr->len)
4381 continue;
4382 hv = p;
4383 hvl = cur_ptr+cur_hdr->len-p;
4384
4385 /* Lowercase the key. Don't check the size of trash, it have
4386 * the size of one buffer and the input data contains in one
4387 * buffer.
4388 */
4389 out = trash.str;
4390 for (in=hn; in<hn+hnl; in++, out++)
4391 *out = tolower(*in);
4392 *out = '\0';
4393
4394 /* Check for existing entry:
4395 * assume that the table is on the top of the stack, and
4396 * push the key in the stack, the function lua_gettable()
4397 * perform the lookup.
4398 */
4399 lua_pushlstring(L, trash.str, hnl);
4400 lua_gettable(L, -2);
4401 type = lua_type(L, -1);
4402
4403 switch (type) {
4404 case LUA_TNIL:
4405 /* Table not found, create it. */
4406 lua_pop(L, 1); /* remove the nil value. */
4407 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
4408 lua_newtable(L); /* create and push empty table. */
4409 lua_pushlstring(L, hv, hvl); /* push header value. */
4410 lua_rawseti(L, -2, 0); /* index header value (pop it). */
4411 lua_rawset(L, -3); /* index new table with header name (pop the values). */
4412 break;
4413
4414 case LUA_TTABLE:
4415 /* Entry found: push the value in the table. */
4416 len = lua_rawlen(L, -1);
4417 lua_pushlstring(L, hv, hvl); /* push header value. */
4418 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
4419 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
4420 break;
4421
4422 default:
4423 /* Other cases are errors. */
4424 hlua_pusherror(L, "internal error during the parsing of headers.");
4425 WILL_LJMP(lua_error(L));
4426 }
4427 }
4428
4429 return 1;
4430}
4431
4432__LJMP static int hlua_http_req_get_headers(lua_State *L)
4433{
4434 struct hlua_txn *htxn;
4435
4436 MAY_LJMP(check_args(L, 1, "req_get_headers"));
4437 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4438
4439 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
4440}
4441
4442__LJMP static int hlua_http_res_get_headers(lua_State *L)
4443{
4444 struct hlua_txn *htxn;
4445
4446 MAY_LJMP(check_args(L, 1, "res_get_headers"));
4447 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4448
4449 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
4450}
4451
4452/* This function replace full header, or just a value in
4453 * the request or in the response. It is a wrapper fir the
4454 * 4 following functions.
4455 */
4456__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
4457 struct http_msg *msg, int action)
4458{
4459 size_t name_len;
4460 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4461 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
4462 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
4463 struct my_regex re;
4464
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004465 /* Check if a valid response is parsed */
4466 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4467 return 0;
4468
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02004469 if (!regex_comp(reg, &re, 1, 1, NULL))
4470 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
4471
4472 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
4473 regex_free(&re);
4474 return 0;
4475}
4476
4477__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
4478{
4479 struct hlua_txn *htxn;
4480
4481 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4482 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4483
4484 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
4485}
4486
4487__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
4488{
4489 struct hlua_txn *htxn;
4490
4491 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
4492 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4493
4494 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
4495}
4496
4497__LJMP static int hlua_http_req_rep_val(lua_State *L)
4498{
4499 struct hlua_txn *htxn;
4500
4501 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
4502 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4503
4504 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
4505}
4506
4507__LJMP static int hlua_http_res_rep_val(lua_State *L)
4508{
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004509 struct hlua_txn *htxn;
4510
4511 MAY_LJMP(check_args(L, 4, "res_rep_val"));
4512 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4513
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02004514 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004515}
4516
4517/* This function deletes all the occurences of an header.
4518 * It is a wrapper for the 2 following functions.
4519 */
4520__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4521{
4522 size_t len;
4523 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4524 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02004525 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004526
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004527 /* Check if a valid response is parsed */
4528 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4529 return 0;
4530
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004531 ctx.idx = 0;
4532 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
4533 http_remove_header2(msg, &txn->hdr_idx, &ctx);
4534 return 0;
4535}
4536
4537__LJMP static int hlua_http_req_del_hdr(lua_State *L)
4538{
4539 struct hlua_txn *htxn;
4540
4541 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4542 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4543
Willy Tarreaueee5b512015-04-03 23:46:31 +02004544 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004545}
4546
4547__LJMP static int hlua_http_res_del_hdr(lua_State *L)
4548{
4549 struct hlua_txn *htxn;
4550
4551 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
4552 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4553
Willy Tarreaueee5b512015-04-03 23:46:31 +02004554 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004555}
4556
4557/* This function adds an header. It is a wrapper used by
4558 * the 2 following functions.
4559 */
4560__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
4561{
4562 size_t name_len;
4563 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
4564 size_t value_len;
4565 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
4566 char *p;
4567
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004568 /* Check if a valid message is parsed */
4569 if (unlikely(msg->msg_state < HTTP_MSG_BODY))
4570 return 0;
4571
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004572 /* Check length. */
4573 trash.len = value_len + name_len + 2;
4574 if (trash.len > trash.size)
4575 return 0;
4576
4577 /* Creates the header string. */
4578 p = trash.str;
4579 memcpy(p, name, name_len);
4580 p += name_len;
4581 *p = ':';
4582 p++;
4583 *p = ' ';
4584 p++;
4585 memcpy(p, value, value_len);
4586
Willy Tarreaueee5b512015-04-03 23:46:31 +02004587 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004588 trash.str, trash.len) != 0);
4589
4590 return 0;
4591}
4592
4593__LJMP static int hlua_http_req_add_hdr(lua_State *L)
4594{
4595 struct hlua_txn *htxn;
4596
4597 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
4598 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4599
Willy Tarreaueee5b512015-04-03 23:46:31 +02004600 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004601}
4602
4603__LJMP static int hlua_http_res_add_hdr(lua_State *L)
4604{
4605 struct hlua_txn *htxn;
4606
4607 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
4608 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4609
Willy Tarreaueee5b512015-04-03 23:46:31 +02004610 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004611}
4612
4613static int hlua_http_req_set_hdr(lua_State *L)
4614{
4615 struct hlua_txn *htxn;
4616
4617 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
4618 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4619
Willy Tarreaueee5b512015-04-03 23:46:31 +02004620 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
4621 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004622}
4623
4624static int hlua_http_res_set_hdr(lua_State *L)
4625{
4626 struct hlua_txn *htxn;
4627
4628 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
4629 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4630
Willy Tarreaueee5b512015-04-03 23:46:31 +02004631 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
4632 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004633}
4634
4635/* This function set the method. */
4636static int hlua_http_req_set_meth(lua_State *L)
4637{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004638 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004639 size_t name_len;
4640 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004641
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004642 /* Check if a valid request is parsed */
4643 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4644 lua_pushboolean(L, 0);
4645 return 1;
4646 }
4647
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004648 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004649 return 1;
4650}
4651
4652/* This function set the method. */
4653static int hlua_http_req_set_path(lua_State *L)
4654{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004655 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004656 size_t name_len;
4657 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004658
4659 /* Check if a valid request is parsed */
4660 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4661 lua_pushboolean(L, 0);
4662 return 1;
4663 }
4664
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004665 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004666 return 1;
4667}
4668
4669/* This function set the query-string. */
4670static int hlua_http_req_set_query(lua_State *L)
4671{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004672 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004673 size_t name_len;
4674 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004675
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004676 /* Check if a valid request is parsed */
4677 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4678 lua_pushboolean(L, 0);
4679 return 1;
4680 }
4681
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004682 /* Check length. */
4683 if (name_len > trash.size - 1) {
4684 lua_pushboolean(L, 0);
4685 return 1;
4686 }
4687
4688 /* Add the mark question as prefix. */
4689 chunk_reset(&trash);
4690 trash.str[trash.len++] = '?';
4691 memcpy(trash.str + trash.len, name, name_len);
4692 trash.len += name_len;
4693
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004694 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004695 return 1;
4696}
4697
4698/* This function set the uri. */
4699static int hlua_http_req_set_uri(lua_State *L)
4700{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02004701 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004702 size_t name_len;
4703 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004704
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004705 /* Check if a valid request is parsed */
4706 if (unlikely(htxn->s->txn->req.msg_state < HTTP_MSG_BODY)) {
4707 lua_pushboolean(L, 0);
4708 return 1;
4709 }
4710
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004711 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004712 return 1;
4713}
4714
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004715/* This function set the response code. */
4716static int hlua_http_res_set_status(lua_State *L)
4717{
4718 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
4719 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
4720
Thierry FOURNIER / OZON.IOb84ae922016-08-02 23:44:58 +02004721 /* Check if a valid response is parsed */
4722 if (unlikely(htxn->s->txn->rsp.msg_state < HTTP_MSG_BODY))
4723 return 0;
4724
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004725 http_set_status(code, htxn->s);
4726 return 0;
4727}
4728
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004729/*
4730 *
4731 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004732 * Class TXN
4733 *
4734 *
4735 */
4736
4737/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02004738 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004739 */
4740__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
4741{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02004742 return MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004743}
4744
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004745__LJMP static int hlua_set_var(lua_State *L)
4746{
4747 struct hlua_txn *htxn;
4748 const char *name;
4749 size_t len;
4750 struct sample smp;
4751
4752 MAY_LJMP(check_args(L, 3, "set_var"));
4753
4754 /* It is useles to retrieve the stream, but this function
4755 * runs only in a stream context.
4756 */
4757 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4758 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4759
4760 /* Converts the third argument in a sample. */
4761 hlua_lua2smp(L, 3, &smp);
4762
4763 /* Store the sample in a variable. */
Willy Tarreau7560dd42016-03-10 16:28:58 +01004764 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004765 vars_set_by_name(name, len, &smp);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004766 return 0;
4767}
4768
Christopher Faulet85d79c92016-11-09 16:54:56 +01004769__LJMP static int hlua_unset_var(lua_State *L)
4770{
4771 struct hlua_txn *htxn;
4772 const char *name;
4773 size_t len;
4774 struct sample smp;
4775
4776 MAY_LJMP(check_args(L, 2, "unset_var"));
4777
4778 /* It is useles to retrieve the stream, but this function
4779 * runs only in a stream context.
4780 */
4781 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4782 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4783
4784 /* Unset the variable. */
4785 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
4786 vars_unset_by_name(name, len, &smp);
4787 return 0;
4788}
4789
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004790__LJMP static int hlua_get_var(lua_State *L)
4791{
4792 struct hlua_txn *htxn;
4793 const char *name;
4794 size_t len;
4795 struct sample smp;
4796
4797 MAY_LJMP(check_args(L, 2, "get_var"));
4798
4799 /* It is useles to retrieve the stream, but this function
4800 * runs only in a stream context.
4801 */
4802 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4803 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
4804
Willy Tarreau7560dd42016-03-10 16:28:58 +01004805 smp_set_owner(&smp, htxn->p, htxn->s->sess, htxn->s, htxn->dir & SMP_OPT_DIR);
Willy Tarreau6204cd92016-03-10 16:33:04 +01004806 if (!vars_get_by_name(name, len, &smp)) {
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004807 lua_pushnil(L);
4808 return 1;
4809 }
4810
4811 return hlua_smp2lua(L, &smp);
4812}
4813
Willy Tarreau59551662015-03-10 14:23:13 +01004814__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004815{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004816 struct hlua *hlua;
4817
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004818 MAY_LJMP(check_args(L, 2, "set_priv"));
4819
Willy Tarreau87b09662015-04-03 00:22:06 +02004820 /* It is useles to retrieve the stream, but this function
4821 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004822 */
4823 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004824 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004825
4826 /* Remove previous value. */
4827 if (hlua->Mref != -1)
4828 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
4829
4830 /* Get and store new value. */
4831 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
4832 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
4833
4834 return 0;
4835}
4836
Willy Tarreau59551662015-03-10 14:23:13 +01004837__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004838{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004839 struct hlua *hlua;
4840
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004841 MAY_LJMP(check_args(L, 1, "get_priv"));
4842
Willy Tarreau87b09662015-04-03 00:22:06 +02004843 /* It is useles to retrieve the stream, but this function
4844 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004845 */
4846 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004847 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004848
4849 /* Push configuration index in the stack. */
4850 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
4851
4852 return 1;
4853}
4854
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004855/* Create stack entry containing a class TXN. This function
4856 * return 0 if the stack does not contains free slots,
4857 * otherwise it returns 1.
4858 */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004859static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p, int dir, int flags)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004860{
Willy Tarreaude491382015-04-06 11:04:28 +02004861 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004862
4863 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004864 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004865 return 0;
4866
4867 /* NOTE: The allocation never fails. The failure
4868 * throw an error, and the function never returns.
4869 * if the throw is not avalaible, the process is aborted.
4870 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004871 /* Create the object: obj[0] = userdata. */
4872 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02004873 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01004874 lua_rawseti(L, -2, 0);
4875
Willy Tarreaude491382015-04-06 11:04:28 +02004876 htxn->s = s;
4877 htxn->p = p;
Thierry FOURNIERc4eebc82015-11-02 10:01:59 +01004878 htxn->dir = dir;
Thierry FOURNIERab00df62016-07-14 11:42:37 +02004879 htxn->flags = flags;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004880
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004881 /* Create the "f" field that contains a list of fetches. */
4882 lua_pushstring(L, "f");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004883 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004884 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004885 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004886
4887 /* Create the "sf" field that contains a list of stringsafe fetches. */
4888 lua_pushstring(L, "sf");
Thierry FOURNIERca988662015-12-20 18:43:03 +01004889 if (!hlua_fetches_new(L, htxn, HLUA_F_MAY_USE_HTTP | HLUA_F_AS_STRING))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004890 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004891 lua_rawset(L, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004892
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004893 /* Create the "c" field that contains a list of converters. */
4894 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02004895 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004896 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004897 lua_rawset(L, -3);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01004898
4899 /* Create the "sc" field that contains a list of stringsafe converters. */
4900 lua_pushstring(L, "sc");
Thierry FOURNIER7fa05492015-12-20 18:42:25 +01004901 if (!hlua_converters_new(L, htxn, HLUA_F_AS_STRING))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004902 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004903 lua_rawset(L, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004904
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004905 /* Create the "req" field that contains the request channel object. */
4906 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004907 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004908 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004909 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004910
4911 /* Create the "res" field that contains the response channel object. */
4912 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01004913 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004914 return 0;
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004915 lua_rawset(L, -3);
Thierry FOURNIER397826a2015-03-11 19:39:09 +01004916
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004917 /* Creates the HTTP object is the current proxy allows http. */
4918 lua_pushstring(L, "http");
4919 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02004920 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004921 return 0;
4922 }
4923 else
4924 lua_pushnil(L);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02004925 lua_rawset(L, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004926
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004927 /* Pop a class sesison metatable and affect it to the userdata. */
4928 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
4929 lua_setmetatable(L, -2);
4930
4931 return 1;
4932}
4933
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004934__LJMP static int hlua_txn_deflog(lua_State *L)
4935{
4936 const char *msg;
4937 struct hlua_txn *htxn;
4938
4939 MAY_LJMP(check_args(L, 2, "deflog"));
4940 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4941 msg = MAY_LJMP(luaL_checkstring(L, 2));
4942
4943 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
4944 return 0;
4945}
4946
4947__LJMP static int hlua_txn_log(lua_State *L)
4948{
4949 int level;
4950 const char *msg;
4951 struct hlua_txn *htxn;
4952
4953 MAY_LJMP(check_args(L, 3, "log"));
4954 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4955 level = MAY_LJMP(luaL_checkinteger(L, 2));
4956 msg = MAY_LJMP(luaL_checkstring(L, 3));
4957
4958 if (level < 0 || level >= NB_LOG_LEVELS)
4959 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
4960
4961 hlua_sendlog(htxn->s->be, level, msg);
4962 return 0;
4963}
4964
4965__LJMP static int hlua_txn_log_debug(lua_State *L)
4966{
4967 const char *msg;
4968 struct hlua_txn *htxn;
4969
4970 MAY_LJMP(check_args(L, 2, "Debug"));
4971 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4972 msg = MAY_LJMP(luaL_checkstring(L, 2));
4973 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
4974 return 0;
4975}
4976
4977__LJMP static int hlua_txn_log_info(lua_State *L)
4978{
4979 const char *msg;
4980 struct hlua_txn *htxn;
4981
4982 MAY_LJMP(check_args(L, 2, "Info"));
4983 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4984 msg = MAY_LJMP(luaL_checkstring(L, 2));
4985 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
4986 return 0;
4987}
4988
4989__LJMP static int hlua_txn_log_warning(lua_State *L)
4990{
4991 const char *msg;
4992 struct hlua_txn *htxn;
4993
4994 MAY_LJMP(check_args(L, 2, "Warning"));
4995 htxn = MAY_LJMP(hlua_checktxn(L, 1));
4996 msg = MAY_LJMP(luaL_checkstring(L, 2));
4997 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
4998 return 0;
4999}
5000
5001__LJMP static int hlua_txn_log_alert(lua_State *L)
5002{
5003 const char *msg;
5004 struct hlua_txn *htxn;
5005
5006 MAY_LJMP(check_args(L, 2, "Alert"));
5007 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5008 msg = MAY_LJMP(luaL_checkstring(L, 2));
5009 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
5010 return 0;
5011}
5012
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005013__LJMP static int hlua_txn_set_loglevel(lua_State *L)
5014{
5015 struct hlua_txn *htxn;
5016 int ll;
5017
5018 MAY_LJMP(check_args(L, 2, "set_loglevel"));
5019 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5020 ll = MAY_LJMP(luaL_checkinteger(L, 2));
5021
5022 if (ll < 0 || ll > 7)
5023 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
5024
5025 htxn->s->logs.level = ll;
5026 return 0;
5027}
5028
5029__LJMP static int hlua_txn_set_tos(lua_State *L)
5030{
5031 struct hlua_txn *htxn;
5032 struct connection *cli_conn;
5033 int tos;
5034
5035 MAY_LJMP(check_args(L, 2, "set_tos"));
5036 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5037 tos = MAY_LJMP(luaL_checkinteger(L, 2));
5038
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005039 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Vincent Bernat6e615892016-05-18 16:17:44 +02005040 inet_set_tos(cli_conn->t.sock.fd, &cli_conn->addr.from, tos);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005041
5042 return 0;
5043}
5044
5045__LJMP static int hlua_txn_set_mark(lua_State *L)
5046{
5047#ifdef SO_MARK
5048 struct hlua_txn *htxn;
5049 struct connection *cli_conn;
5050 int mark;
5051
5052 MAY_LJMP(check_args(L, 2, "set_mark"));
5053 htxn = MAY_LJMP(hlua_checktxn(L, 1));
5054 mark = MAY_LJMP(luaL_checkinteger(L, 2));
5055
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02005056 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02005057 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005058#endif
5059 return 0;
5060}
5061
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005062/* This function is an Lua binding that send pending data
5063 * to the client, and close the stream interface.
5064 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005065__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005066{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005067 struct hlua_txn *htxn;
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005068 struct hlua *hlua;
Willy Tarreau81389672015-03-10 12:03:52 +01005069 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005070
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005071 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005072 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005073 hlua = hlua_gethlua(L);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005074
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005075 /* If the flags NOTERM is set, we cannot terminate the http
5076 * session, so we just end the execution of the current
5077 * lua code.
5078 */
5079 if (htxn->flags & HLUA_TXN_NOTERM) {
5080 WILL_LJMP(hlua_done(L));
5081 return 0;
5082 }
5083
Willy Tarreaub2ccb562015-04-06 11:11:15 +02005084 ic = &htxn->s->req;
5085 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01005086
Willy Tarreau630ef452015-08-28 10:06:15 +02005087 if (htxn->s->txn) {
5088 /* HTTP mode, let's stay in sync with the stream */
5089 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
5090 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
5091 htxn->s->txn->req.sov = 0;
5092 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
5093 oc->analysers = AN_RES_HTTP_XFER_BODY;
5094 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
5095 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
5096
Willy Tarreau630ef452015-08-28 10:06:15 +02005097 /* Note that if we want to support keep-alive, we need
5098 * to bypass the close/shutr_now calls below, but that
5099 * may only be done if the HTTP request was already
5100 * processed and the connection header is known (ie
5101 * not during TCP rules).
5102 */
5103 }
5104
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005105 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01005106 channel_abort(ic);
5107 channel_auto_close(ic);
5108 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02005109
5110 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01005111 channel_auto_read(oc);
5112 channel_auto_close(oc);
5113 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005114
Willy Tarreau0458b082015-08-28 09:40:04 +02005115 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005116
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005117 hlua->flags |= HLUA_STOP;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005118 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005119 return 0;
5120}
5121
5122__LJMP static int hlua_log(lua_State *L)
5123{
5124 int level;
5125 const char *msg;
5126
5127 MAY_LJMP(check_args(L, 2, "log"));
5128 level = MAY_LJMP(luaL_checkinteger(L, 1));
5129 msg = MAY_LJMP(luaL_checkstring(L, 2));
5130
5131 if (level < 0 || level >= NB_LOG_LEVELS)
5132 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
5133
5134 hlua_sendlog(NULL, level, msg);
5135 return 0;
5136}
5137
5138__LJMP static int hlua_log_debug(lua_State *L)
5139{
5140 const char *msg;
5141
5142 MAY_LJMP(check_args(L, 1, "debug"));
5143 msg = MAY_LJMP(luaL_checkstring(L, 1));
5144 hlua_sendlog(NULL, LOG_DEBUG, msg);
5145 return 0;
5146}
5147
5148__LJMP static int hlua_log_info(lua_State *L)
5149{
5150 const char *msg;
5151
5152 MAY_LJMP(check_args(L, 1, "info"));
5153 msg = MAY_LJMP(luaL_checkstring(L, 1));
5154 hlua_sendlog(NULL, LOG_INFO, msg);
5155 return 0;
5156}
5157
5158__LJMP static int hlua_log_warning(lua_State *L)
5159{
5160 const char *msg;
5161
5162 MAY_LJMP(check_args(L, 1, "warning"));
5163 msg = MAY_LJMP(luaL_checkstring(L, 1));
5164 hlua_sendlog(NULL, LOG_WARNING, msg);
5165 return 0;
5166}
5167
5168__LJMP static int hlua_log_alert(lua_State *L)
5169{
5170 const char *msg;
5171
5172 MAY_LJMP(check_args(L, 1, "alert"));
5173 msg = MAY_LJMP(luaL_checkstring(L, 1));
5174 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01005175 return 0;
5176}
5177
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005178__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005179{
5180 int wakeup_ms = lua_tointeger(L, -1);
5181 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005182 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005183 return 0;
5184}
5185
5186__LJMP static int hlua_sleep(lua_State *L)
5187{
5188 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005189 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005190
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005191 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005192
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005193 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005194 wakeup_ms = tick_add(now_ms, delay);
5195 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005196
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005197 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5198 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005199}
5200
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005201__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005202{
5203 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005204 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005205
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005206 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005207
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005208 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005209 wakeup_ms = tick_add(now_ms, delay);
5210 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005211
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005212 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
5213 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01005214}
5215
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005216/* This functionis an LUA binding. it permits to give back
5217 * the hand at the HAProxy scheduler. It is used when the
5218 * LUA processing consumes a lot of time.
5219 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01005220__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005221{
5222 return 0;
5223}
5224
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005225__LJMP static int hlua_yield(lua_State *L)
5226{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01005227 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
5228 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01005229}
5230
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005231/* This function change the nice of the currently executed
5232 * task. It is used set low or high priority at the current
5233 * task.
5234 */
Willy Tarreau59551662015-03-10 14:23:13 +01005235__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005236{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005237 struct hlua *hlua;
5238 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005239
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005240 MAY_LJMP(check_args(L, 1, "set_nice"));
5241 hlua = hlua_gethlua(L);
5242 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005243
5244 /* If he task is not set, I'm in a start mode. */
5245 if (!hlua || !hlua->task)
5246 return 0;
5247
5248 if (nice < -1024)
5249 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01005250 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01005251 nice = 1024;
5252
5253 hlua->task->nice = nice;
5254 return 0;
5255}
5256
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005257/* This function is used as a calback of a task. It is called by the
5258 * HAProxy task subsystem when the task is awaked. The LUA runtime can
5259 * return an E_AGAIN signal, the emmiter of this signal must set a
5260 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005261 *
5262 * Task wrapper are longjmp safe because the only one Lua code
5263 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005264 */
5265static struct task *hlua_process_task(struct task *task)
5266{
5267 struct hlua *hlua = task->context;
5268 enum hlua_exec status;
5269
5270 /* We need to remove the task from the wait queue before executing
5271 * the Lua code because we don't know if it needs to wait for
5272 * another timer or not in the case of E_AGAIN.
5273 */
5274 task_delete(task);
5275
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005276 /* If it is the first call to the task, we must initialize the
5277 * execution timeouts.
5278 */
5279 if (!HLUA_IS_RUNNING(hlua))
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005280 hlua->max_time = hlua_timeout_task;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005281
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005282 /* Execute the Lua code. */
5283 status = hlua_ctx_resume(hlua, 1);
5284
5285 switch (status) {
5286 /* finished or yield */
5287 case HLUA_E_OK:
5288 hlua_ctx_destroy(hlua);
5289 task_delete(task);
5290 task_free(task);
5291 break;
5292
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005293 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
5294 if (hlua->wake_time != TICK_ETERNITY)
5295 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005296 break;
5297
5298 /* finished with error. */
5299 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005300 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005301 hlua_ctx_destroy(hlua);
5302 task_delete(task);
5303 task_free(task);
5304 break;
5305
5306 case HLUA_E_ERR:
5307 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005308 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005309 hlua_ctx_destroy(hlua);
5310 task_delete(task);
5311 task_free(task);
5312 break;
5313 }
5314 return NULL;
5315}
5316
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005317/* This function is an LUA binding that register LUA function to be
5318 * executed after the HAProxy configuration parsing and before the
5319 * HAProxy scheduler starts. This function expect only one LUA
5320 * argument that is a function. This function returns nothing, but
5321 * throws if an error is encountered.
5322 */
5323__LJMP static int hlua_register_init(lua_State *L)
5324{
5325 struct hlua_init_function *init;
5326 int ref;
5327
5328 MAY_LJMP(check_args(L, 1, "register_init"));
5329
5330 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5331
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005332 init = calloc(1, sizeof(*init));
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01005333 if (!init)
5334 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5335
5336 init->function_ref = ref;
5337 LIST_ADDQ(&hlua_init_functions, &init->l);
5338 return 0;
5339}
5340
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005341/* This functio is an LUA binding. It permits to register a task
5342 * executed in parallel of the main HAroxy activity. The task is
5343 * created and it is set in the HAProxy scheduler. It can be called
5344 * from the "init" section, "post init" or during the runtime.
5345 *
5346 * Lua prototype:
5347 *
5348 * <none> core.register_task(<function>)
5349 */
5350static int hlua_register_task(lua_State *L)
5351{
5352 struct hlua *hlua;
5353 struct task *task;
5354 int ref;
5355
5356 MAY_LJMP(check_args(L, 1, "register_task"));
5357
5358 ref = MAY_LJMP(hlua_checkfunction(L, 1));
5359
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005360 hlua = calloc(1, sizeof(*hlua));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01005361 if (!hlua)
5362 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5363
5364 task = task_new();
5365 task->context = hlua;
5366 task->process = hlua_process_task;
5367
5368 if (!hlua_ctx_init(hlua, task))
5369 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5370
5371 /* Restore the function in the stack. */
5372 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
5373 hlua->nargs = 0;
5374
5375 /* Schedule task. */
5376 task_schedule(task, now_ms);
5377
5378 return 0;
5379}
5380
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005381/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
5382 * doesn't allow "yield" functions because the HAProxy engine cannot
5383 * resume converters.
5384 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005385static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005386{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005387 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005388 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005389 const char *error;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005390
Willy Tarreaube508f12016-03-10 11:47:01 +01005391 if (!stream)
5392 return 0;
5393
Willy Tarreau87b09662015-04-03 00:22:06 +02005394 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005395 * Lua context can be not initialized. This behavior
5396 * permits to save performances because a systematic
5397 * Lua initialization cause 5% performances loss.
5398 */
Willy Tarreau87b09662015-04-03 00:22:06 +02005399 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005400 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005401 return 0;
5402 }
5403
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005404 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005405 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005406
5407 /* The following Lua calls can fail. */
5408 if (!SET_SAFE_LJMP(stream->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005409 if (lua_type(stream->hlua.T, -1) == LUA_TSTRING)
5410 error = lua_tostring(stream->hlua.T, -1);
5411 else
5412 error = "critical error";
5413 SEND_ERR(stream->be, "Lua converter '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005414 return 0;
5415 }
5416
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005417 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005418 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005419 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005420 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005421 return 0;
5422 }
5423
5424 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005425 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005426
5427 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005428 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005429 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005430 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005431 return 0;
5432 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005433 hlua_smp2lua(stream->hlua.T, smp);
Thierry Fournier4a53bfd2016-05-27 16:35:01 +02005434 stream->hlua.nargs = 1;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005435
5436 /* push keywords in the stack. */
5437 if (arg_p) {
5438 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02005439 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005440 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005441 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005442 return 0;
5443 }
Willy Tarreau87b09662015-04-03 00:22:06 +02005444 hlua_arg2lua(stream->hlua.T, arg_p);
5445 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005446 }
5447 }
5448
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005449 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005450 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005451
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005452 /* At this point the execution is safe. */
5453 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005454 }
5455
5456 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005457 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005458 /* finished. */
5459 case HLUA_E_OK:
5460 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02005461 hlua_lua2smp(stream->hlua.T, -1, smp);
5462 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005463 return 1;
5464
5465 /* yield. */
5466 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005467 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005468 return 0;
5469
5470 /* finished with error. */
5471 case HLUA_E_ERRMSG:
5472 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005473 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
5474 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02005475 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005476 return 0;
5477
5478 case HLUA_E_ERR:
5479 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005480 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005481
5482 default:
5483 return 0;
5484 }
5485}
5486
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005487/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
5488 * doesn't allow "yield" functions because the HAProxy engine cannot
Willy Tarreaube508f12016-03-10 11:47:01 +01005489 * resume sample-fetches. This function will be called by the sample
5490 * fetch engine to call lua-based fetch operations.
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005491 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02005492static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
5493 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005494{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02005495 struct hlua_function *fcn = private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005496 struct stream *stream = smp->strm;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005497 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005498 const struct chunk msg = { .len = 0 };
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005499
Willy Tarreaube508f12016-03-10 11:47:01 +01005500 if (!stream)
5501 return 0;
5502
Willy Tarreau87b09662015-04-03 00:22:06 +02005503 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005504 * Lua context can be not initialized. This behavior
5505 * permits to save performances because a systematic
5506 * Lua initialization cause 5% performances loss.
5507 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005508 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005509 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005510 return 0;
5511 }
5512
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005513 consistency_set(stream, smp->opt, &stream->hlua.cons);
5514
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005515 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005516 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005517
5518 /* The following Lua calls can fail. */
5519 if (!SET_SAFE_LJMP(stream->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005520 if (lua_type(stream->hlua.T, -1) == LUA_TSTRING)
5521 error = lua_tostring(stream->hlua.T, -1);
5522 else
5523 error = "critical error";
5524 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n", fcn->name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005525 return 0;
5526 }
5527
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005528 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005529 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005530 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005531 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005532 return 0;
5533 }
5534
5535 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005536 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005537
5538 /* push arguments in the stack. */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005539 if (!hlua_txn_new(stream->hlua.T, stream, smp->px, smp->opt & SMP_OPT_DIR,
5540 HLUA_TXN_NOTERM)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005541 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005542 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005543 return 0;
5544 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005545 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005546
5547 /* push keywords in the stack. */
5548 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
5549 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005550 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005551 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005552 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005553 return 0;
5554 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005555 hlua_arg2lua(stream->hlua.T, arg_p);
5556 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005557 }
5558
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005559 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005560 stream->hlua.max_time = hlua_timeout_session;
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005561
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005562 /* At this point the execution is safe. */
5563 RESET_SAFE_LJMP(stream->hlua.T);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005564 }
5565
5566 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005567 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005568 /* finished. */
5569 case HLUA_E_OK:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005570 if (!consistency_check(stream, smp->opt, &stream->hlua.cons)) {
5571 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005572 return 0;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005573 }
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005574 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005575 hlua_lua2smp(stream->hlua.T, -1, smp);
5576 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005577
5578 /* Set the end of execution flag. */
5579 smp->flags &= ~SMP_F_MAY_CHANGE;
5580 return 1;
5581
5582 /* yield. */
5583 case HLUA_E_AGAIN:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005584 if (!consistency_check(stream, smp->opt, &stream->hlua.cons))
5585 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005586 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005587 return 0;
5588
5589 /* finished with error. */
5590 case HLUA_E_ERRMSG:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005591 if (!consistency_check(stream, smp->opt, &stream->hlua.cons))
5592 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005593 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005594 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
5595 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02005596 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005597 return 0;
5598
5599 case HLUA_E_ERR:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005600 if (!consistency_check(stream, smp->opt, &stream->hlua.cons))
5601 stream_int_retnclose(&stream->si[0], &msg);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005602 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005603 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005604
5605 default:
5606 return 0;
5607 }
5608}
5609
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005610/* This function is an LUA binding used for registering
5611 * "sample-conv" functions. It expects a converter name used
5612 * in the haproxy configuration file, and an LUA function.
5613 */
5614__LJMP static int hlua_register_converters(lua_State *L)
5615{
5616 struct sample_conv_kw_list *sck;
5617 const char *name;
5618 int ref;
5619 int len;
5620 struct hlua_function *fcn;
5621
5622 MAY_LJMP(check_args(L, 2, "register_converters"));
5623
5624 /* First argument : converter name. */
5625 name = MAY_LJMP(luaL_checkstring(L, 1));
5626
5627 /* Second argument : lua function. */
5628 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5629
5630 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005631 sck = calloc(1, sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005632 if (!sck)
5633 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005634 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005635 if (!fcn)
5636 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5637
5638 /* Fill fcn. */
5639 fcn->name = strdup(name);
5640 if (!fcn->name)
5641 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5642 fcn->function_ref = ref;
5643
5644 /* List head */
5645 sck->list.n = sck->list.p = NULL;
5646
5647 /* converter keyword. */
5648 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005649 sck->kw[0].kw = calloc(1, len);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005650 if (!sck->kw[0].kw)
5651 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5652
5653 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
5654 sck->kw[0].process = hlua_sample_conv_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005655 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 +01005656 sck->kw[0].val_args = NULL;
5657 sck->kw[0].in_type = SMP_T_STR;
5658 sck->kw[0].out_type = SMP_T_STR;
5659 sck->kw[0].private = fcn;
5660
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01005661 /* Register this new converter */
5662 sample_register_convs(sck);
5663
5664 return 0;
5665}
5666
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005667/* This fucntion is an LUA binding used for registering
5668 * "sample-fetch" functions. It expects a converter name used
5669 * in the haproxy configuration file, and an LUA function.
5670 */
5671__LJMP static int hlua_register_fetches(lua_State *L)
5672{
5673 const char *name;
5674 int ref;
5675 int len;
5676 struct sample_fetch_kw_list *sfk;
5677 struct hlua_function *fcn;
5678
5679 MAY_LJMP(check_args(L, 2, "register_fetches"));
5680
5681 /* First argument : sample-fetch name. */
5682 name = MAY_LJMP(luaL_checkstring(L, 1));
5683
5684 /* Second argument : lua function. */
5685 ref = MAY_LJMP(hlua_checkfunction(L, 2));
5686
5687 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005688 sfk = calloc(1, sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005689 if (!sfk)
5690 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005691 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005692 if (!fcn)
5693 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5694
5695 /* Fill fcn. */
5696 fcn->name = strdup(name);
5697 if (!fcn->name)
5698 WILL_LJMP(luaL_error(L, "lua out of memory error."));
5699 fcn->function_ref = ref;
5700
5701 /* List head */
5702 sfk->list.n = sfk->list.p = NULL;
5703
5704 /* sample-fetch keyword. */
5705 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02005706 sfk->kw[0].kw = calloc(1, len);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005707 if (!sfk->kw[0].kw)
5708 return luaL_error(L, "lua out of memory error.");
5709
5710 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
5711 sfk->kw[0].process = hlua_sample_fetch_wrapper;
David Carlier0c437f42016-04-27 16:21:56 +01005712 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 +01005713 sfk->kw[0].val_args = NULL;
5714 sfk->kw[0].out_type = SMP_T_STR;
5715 sfk->kw[0].use = SMP_USE_HTTP_ANY;
5716 sfk->kw[0].val = 0;
5717 sfk->kw[0].private = fcn;
5718
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01005719 /* Register this new fetch. */
5720 sample_register_fetches(sfk);
5721
5722 return 0;
5723}
5724
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005725/* This function is a wrapper to execute each LUA function declared
5726 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005727 * return ACT_RET_CONT if the processing is finished (with or without
5728 * error) and return ACT_RET_YIELD if the function must be called again
5729 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005730 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005731static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
Willy Tarreau658b85b2015-09-27 10:00:49 +02005732 struct session *sess, struct stream *s, int flags)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005733{
5734 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005735 unsigned int analyzer;
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005736 int dir;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005737 const char *error;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005738 const struct chunk msg = { .len = 0 };
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005739
5740 switch (rule->from) {
Thierry FOURNIER6e01f382015-11-02 09:52:54 +01005741 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; dir = SMP_OPT_DIR_REQ; break;
5742 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; dir = SMP_OPT_DIR_RES; break;
5743 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; dir = SMP_OPT_DIR_REQ; break;
5744 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; dir = SMP_OPT_DIR_RES; break;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005745 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005746 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005747 return ACT_RET_CONT;
5748 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005749
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005750 consistency_set(s, dir, &s->hlua.cons);
5751
Willy Tarreau87b09662015-04-03 00:22:06 +02005752 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005753 * Lua context can be not initialized. This behavior
5754 * permits to save performances because a systematic
5755 * Lua initialization cause 5% performances loss.
5756 */
5757 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005758 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005759 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005760 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01005761 }
5762
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005763 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01005764 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005765
5766 /* The following Lua calls can fail. */
5767 if (!SET_SAFE_LJMP(s->hlua.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005768 if (lua_type(s->hlua.T, -1) == LUA_TSTRING)
5769 error = lua_tostring(s->hlua.T, -1);
5770 else
5771 error = "critical error";
5772 SEND_ERR(px, "Lua function '%s': %s.\n",
5773 rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005774 return ACT_RET_CONT;
5775 }
5776
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005777 /* Check stack available size. */
5778 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005779 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005780 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005781 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005782 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005783 }
5784
5785 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005786 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005787
Willy Tarreau87b09662015-04-03 00:22:06 +02005788 /* Create and and push object stream in the stack. */
Thierry FOURNIERab00df62016-07-14 11:42:37 +02005789 if (!hlua_txn_new(s->hlua.T, s, px, dir, 0)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005790 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005791 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005792 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005793 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005794 }
5795 s->hlua.nargs = 1;
5796
5797 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005798 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005799 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005800 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005801 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER10e5bc72015-09-25 23:51:34 +02005802 RESET_SAFE_LJMP(s->hlua.T);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005803 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005804 }
5805 lua_pushstring(s->hlua.T, *arg);
5806 s->hlua.nargs++;
5807 }
5808
Thierry FOURNIERbabae282015-09-17 11:36:37 +02005809 /* Now the execution is safe. */
5810 RESET_SAFE_LJMP(s->hlua.T);
5811
Thierry FOURNIERbd413492015-03-03 16:52:26 +01005812 /* We must initialize the execution timeouts. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005813 s->hlua.max_time = hlua_timeout_session;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005814 }
5815
5816 /* Execute the function. */
Willy Tarreau528192d2015-09-27 10:48:01 +02005817 switch (hlua_ctx_resume(&s->hlua, !(flags & ACT_FLAG_FINAL))) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005818 /* finished. */
5819 case HLUA_E_OK:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005820 if (!consistency_check(s, dir, &s->hlua.cons)) {
5821 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005822 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005823 }
Thierry FOURNIER9bd52d42016-07-14 11:45:33 +02005824 if (s->hlua.flags & HLUA_STOP)
5825 return ACT_RET_STOP;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005826 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005827
5828 /* yield. */
5829 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005830 /* Set timeout in the required channel. */
5831 if (s->hlua.wake_time != TICK_ETERNITY) {
5832 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005833 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005834 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005835 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01005836 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005837 /* Some actions can be wake up when a "write" event
5838 * is detected on a response channel. This is useful
5839 * only for actions targetted on the requests.
5840 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01005841 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005842 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01005843 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005844 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005845 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01005846 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01005847 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005848 /* We can quit the fcuntion without consistency check
5849 * because HAProxy is not able to manipulate data, it
5850 * is only allowed to call me again. */
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005851 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005852
5853 /* finished with error. */
5854 case HLUA_E_ERRMSG:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005855 if (!consistency_check(s, dir, &s->hlua.cons)) {
5856 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005857 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005858 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005859 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005860 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005861 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005862 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005863 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005864
5865 case HLUA_E_ERR:
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005866 if (!consistency_check(s, dir, &s->hlua.cons)) {
5867 stream_int_retnclose(&s->si[0], &msg);
Thierry FOURNIERd75cb0f2015-09-25 19:22:44 +02005868 return ACT_RET_ERR;
Thierry FOURNIER11cfb3d2016-12-13 13:06:23 +01005869 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005870 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02005871 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02005872 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005873
5874 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02005875 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01005876 }
5877}
5878
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005879struct task *hlua_applet_wakeup(struct task *t)
5880{
5881 struct appctx *ctx = t->context;
5882 struct stream_interface *si = ctx->owner;
5883
5884 /* If the applet is wake up without any expected work, the sheduler
5885 * remove it from the run queue. This flag indicate that the applet
5886 * is waiting for write. If the buffer is full, the main processing
5887 * will send some data and after call the applet, otherwise it call
5888 * the applet ASAP.
5889 */
5890 si_applet_cant_put(si);
5891 appctx_wakeup(ctx);
5892 return NULL;
5893}
5894
5895static int hlua_applet_tcp_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
5896{
5897 struct stream_interface *si = ctx->owner;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01005898 struct hlua *hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005899 struct task *task;
5900 char **arg;
Thierry Fournierfd107a22016-02-19 19:57:23 +01005901 const char *error;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005902
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01005903 hlua = pool_alloc2(pool2_hlua);
5904 if (!hlua) {
5905 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5906 ctx->rule->arg.hlua_rule->fcn.name);
5907 return 0;
5908 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005909 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01005910 ctx->ctx.hlua_apptcp.hlua = hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005911 ctx->ctx.hlua_apptcp.flags = 0;
5912
5913 /* Create task used by signal to wakeup applets. */
5914 task = task_new();
5915 if (!task) {
5916 SEND_ERR(px, "Lua applet tcp '%s': out of memory.\n",
5917 ctx->rule->arg.hlua_rule->fcn.name);
5918 return 0;
5919 }
5920 task->nice = 0;
5921 task->context = ctx;
5922 task->process = hlua_applet_wakeup;
5923 ctx->ctx.hlua_apptcp.task = task;
5924
5925 /* In the execution wrappers linked with a stream, the
5926 * Lua context can be not initialized. This behavior
5927 * permits to save performances because a systematic
5928 * Lua initialization cause 5% performances loss.
5929 */
5930 if (!hlua_ctx_init(hlua, task)) {
5931 SEND_ERR(px, "Lua applet tcp '%s': can't initialize Lua context.\n",
5932 ctx->rule->arg.hlua_rule->fcn.name);
5933 return 0;
5934 }
5935
5936 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02005937 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005938
5939 /* The following Lua calls can fail. */
5940 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01005941 if (lua_type(hlua->T, -1) == LUA_TSTRING)
5942 error = lua_tostring(hlua->T, -1);
5943 else
5944 error = "critical error";
5945 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
5946 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02005947 RESET_SAFE_LJMP(hlua->T);
5948 return 0;
5949 }
5950
5951 /* Check stack available size. */
5952 if (!lua_checkstack(hlua->T, 1)) {
5953 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5954 ctx->rule->arg.hlua_rule->fcn.name);
5955 RESET_SAFE_LJMP(hlua->T);
5956 return 0;
5957 }
5958
5959 /* Restore the function in the stack. */
5960 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
5961
5962 /* Create and and push object stream in the stack. */
5963 if (!hlua_applet_tcp_new(hlua->T, ctx)) {
5964 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5965 ctx->rule->arg.hlua_rule->fcn.name);
5966 RESET_SAFE_LJMP(hlua->T);
5967 return 0;
5968 }
5969 hlua->nargs = 1;
5970
5971 /* push keywords in the stack. */
5972 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
5973 if (!lua_checkstack(hlua->T, 1)) {
5974 SEND_ERR(px, "Lua applet tcp '%s': full stack.\n",
5975 ctx->rule->arg.hlua_rule->fcn.name);
5976 RESET_SAFE_LJMP(hlua->T);
5977 return 0;
5978 }
5979 lua_pushstring(hlua->T, *arg);
5980 hlua->nargs++;
5981 }
5982
5983 RESET_SAFE_LJMP(hlua->T);
5984
5985 /* Wakeup the applet ASAP. */
5986 si_applet_cant_get(si);
5987 si_applet_cant_put(si);
5988
5989 return 1;
5990}
5991
5992static void hlua_applet_tcp_fct(struct appctx *ctx)
5993{
5994 struct stream_interface *si = ctx->owner;
5995 struct stream *strm = si_strm(si);
5996 struct channel *res = si_ic(si);
5997 struct act_rule *rule = ctx->rule;
5998 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01005999 struct hlua *hlua = ctx->ctx.hlua_apptcp.hlua;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006000
6001 /* The applet execution is already done. */
6002 if (ctx->ctx.hlua_apptcp.flags & APPLET_DONE)
6003 return;
6004
6005 /* If the stream is disconnect or closed, ldo nothing. */
6006 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6007 return;
6008
6009 /* Execute the function. */
6010 switch (hlua_ctx_resume(hlua, 1)) {
6011 /* finished. */
6012 case HLUA_E_OK:
6013 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6014
6015 /* log time */
6016 strm->logs.tv_request = now;
6017
6018 /* eat the whole request */
6019 bo_skip(si_oc(si), si_ob(si)->o);
6020 res->flags |= CF_READ_NULL;
6021 si_shutr(si);
6022 return;
6023
6024 /* yield. */
6025 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006026 if (hlua->wake_time != TICK_ETERNITY)
6027 task_schedule(ctx->ctx.hlua_apptcp.task, hlua->wake_time);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006028 return;
6029
6030 /* finished with error. */
6031 case HLUA_E_ERRMSG:
6032 /* Display log. */
6033 SEND_ERR(px, "Lua applet tcp '%s': %s.\n",
6034 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6035 lua_pop(hlua->T, 1);
6036 goto error;
6037
6038 case HLUA_E_ERR:
6039 /* Display log. */
6040 SEND_ERR(px, "Lua applet tcp '%s' return an unknown error.\n",
6041 rule->arg.hlua_rule->fcn.name);
6042 goto error;
6043
6044 default:
6045 goto error;
6046 }
6047
6048error:
6049
6050 /* For all other cases, just close the stream. */
6051 si_shutw(si);
6052 si_shutr(si);
6053 ctx->ctx.hlua_apptcp.flags |= APPLET_DONE;
6054}
6055
6056static void hlua_applet_tcp_release(struct appctx *ctx)
6057{
6058 task_free(ctx->ctx.hlua_apptcp.task);
6059 ctx->ctx.hlua_apptcp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006060 hlua_ctx_destroy(ctx->ctx.hlua_apptcp.hlua);
6061 pool_free2(pool2_hlua, ctx->ctx.hlua_apptcp.hlua);
6062 ctx->ctx.hlua_apptcp.hlua = NULL;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006063}
6064
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006065/* The function returns 1 if the initialisation is complete, 0 if
6066 * an errors occurs and -1 if more data are required for initializing
6067 * the applet.
6068 */
6069static int hlua_applet_http_init(struct appctx *ctx, struct proxy *px, struct stream *strm)
6070{
6071 struct stream_interface *si = ctx->owner;
6072 struct channel *req = si_oc(si);
6073 struct http_msg *msg;
6074 struct http_txn *txn;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006075 struct hlua *hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006076 char **arg;
6077 struct hdr_ctx hdr;
6078 struct task *task;
6079 struct sample smp; /* just used for a valid call to smp_prefetch_http. */
Thierry Fournierfd107a22016-02-19 19:57:23 +01006080 const char *error;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006081
6082 /* Wait for a full HTTP request. */
6083 if (!smp_prefetch_http(px, strm, 0, NULL, &smp, 0)) {
6084 if (smp.flags & SMP_F_MAY_CHANGE)
6085 return -1;
6086 return 0;
6087 }
6088 txn = strm->txn;
6089 msg = &txn->req;
6090
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006091 /* We want two things in HTTP mode :
6092 * - enforce server-close mode if we were in keep-alive, so that the
6093 * applet is released after each response ;
6094 * - enable request body transfer to the applet in order to resync
6095 * with the response body.
6096 */
6097 if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)
6098 txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL;
Willy Tarreau0078bfc2015-10-07 20:20:28 +02006099
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006100 hlua = pool_alloc2(pool2_hlua);
6101 if (!hlua) {
6102 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6103 ctx->rule->arg.hlua_rule->fcn.name);
6104 return 0;
6105 }
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006106 HLUA_INIT(hlua);
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006107 ctx->ctx.hlua_apphttp.hlua = hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006108 ctx->ctx.hlua_apphttp.left_bytes = -1;
6109 ctx->ctx.hlua_apphttp.flags = 0;
6110
Thierry FOURNIERd93ea2b2015-12-20 19:14:52 +01006111 if (txn->req.flags & HTTP_MSGF_VER_11)
6112 ctx->ctx.hlua_apphttp.flags |= APPLET_HTTP11;
6113
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006114 /* Create task used by signal to wakeup applets. */
6115 task = task_new();
6116 if (!task) {
6117 SEND_ERR(px, "Lua applet http '%s': out of memory.\n",
6118 ctx->rule->arg.hlua_rule->fcn.name);
6119 return 0;
6120 }
6121 task->nice = 0;
6122 task->context = ctx;
6123 task->process = hlua_applet_wakeup;
6124 ctx->ctx.hlua_apphttp.task = task;
6125
6126 /* In the execution wrappers linked with a stream, the
6127 * Lua context can be not initialized. This behavior
6128 * permits to save performances because a systematic
6129 * Lua initialization cause 5% performances loss.
6130 */
6131 if (!hlua_ctx_init(hlua, task)) {
6132 SEND_ERR(px, "Lua applet http '%s': can't initialize Lua context.\n",
6133 ctx->rule->arg.hlua_rule->fcn.name);
6134 return 0;
6135 }
6136
6137 /* Set timeout according with the applet configuration. */
Thierry FOURNIER10770fa2015-09-29 01:59:42 +02006138 hlua->max_time = ctx->applet->timeout;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006139
6140 /* The following Lua calls can fail. */
6141 if (!SET_SAFE_LJMP(hlua->T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01006142 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6143 error = lua_tostring(hlua->T, -1);
6144 else
6145 error = "critical error";
6146 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6147 ctx->rule->arg.hlua_rule->fcn.name, error);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006148 return 0;
6149 }
6150
6151 /* Check stack available size. */
6152 if (!lua_checkstack(hlua->T, 1)) {
6153 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6154 ctx->rule->arg.hlua_rule->fcn.name);
6155 RESET_SAFE_LJMP(hlua->T);
6156 return 0;
6157 }
6158
6159 /* Restore the function in the stack. */
6160 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ctx->rule->arg.hlua_rule->fcn.function_ref);
6161
6162 /* Create and and push object stream in the stack. */
6163 if (!hlua_applet_http_new(hlua->T, ctx)) {
6164 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6165 ctx->rule->arg.hlua_rule->fcn.name);
6166 RESET_SAFE_LJMP(hlua->T);
6167 return 0;
6168 }
6169 hlua->nargs = 1;
6170
6171 /* Look for a 100-continue expected. */
6172 if (msg->flags & HTTP_MSGF_VER_11) {
6173 hdr.idx = 0;
6174 if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &hdr) &&
6175 unlikely(hdr.vlen == 12 && strncasecmp(hdr.line+hdr.val, "100-continue", 12) == 0))
6176 ctx->ctx.hlua_apphttp.flags |= APPLET_100C;
6177 }
6178
6179 /* push keywords in the stack. */
6180 for (arg = ctx->rule->arg.hlua_rule->args; arg && *arg; arg++) {
6181 if (!lua_checkstack(hlua->T, 1)) {
6182 SEND_ERR(px, "Lua applet http '%s': full stack.\n",
6183 ctx->rule->arg.hlua_rule->fcn.name);
6184 RESET_SAFE_LJMP(hlua->T);
6185 return 0;
6186 }
6187 lua_pushstring(hlua->T, *arg);
6188 hlua->nargs++;
6189 }
6190
6191 RESET_SAFE_LJMP(hlua->T);
6192
6193 /* Wakeup the applet when data is ready for read. */
6194 si_applet_cant_get(si);
6195
6196 return 1;
6197}
6198
6199static void hlua_applet_http_fct(struct appctx *ctx)
6200{
6201 struct stream_interface *si = ctx->owner;
6202 struct stream *strm = si_strm(si);
6203 struct channel *res = si_ic(si);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006204 struct act_rule *rule = ctx->rule;
6205 struct proxy *px = strm->be;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006206 struct hlua *hlua = ctx->ctx.hlua_apphttp.hlua;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006207 char *blk1;
6208 int len1;
6209 char *blk2;
6210 int len2;
6211 int ret;
6212
6213 /* If the stream is disconnect or closed, ldo nothing. */
6214 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6215 return;
6216
6217 /* Set the currently running flag. */
6218 if (!HLUA_IS_RUNNING(hlua) &&
6219 !(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6220
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006221 /* Wait for full HTTP analysys. */
6222 if (unlikely(strm->txn->req.msg_state < HTTP_MSG_BODY)) {
6223 si_applet_cant_get(si);
6224 return;
6225 }
6226
6227 /* Store the max amount of bytes that we can read. */
6228 ctx->ctx.hlua_apphttp.left_bytes = strm->txn->req.body_len;
6229
6230 /* We need to flush the request header. This left the body
6231 * for the Lua.
6232 */
6233
6234 /* Read the maximum amount of data avalaible. */
6235 ret = bo_getblk_nc(si_oc(si), &blk1, &len1, &blk2, &len2);
6236 if (ret == -1)
6237 return;
6238
6239 /* No data available, ask for more data. */
6240 if (ret == 1)
6241 len2 = 0;
6242 if (ret == 0)
6243 len1 = 0;
6244 if (len1 + len2 < strm->txn->req.eoh + 2) {
6245 si_applet_cant_get(si);
6246 return;
6247 }
6248
6249 /* skip the requests bytes. */
6250 bo_skip(si_oc(si), strm->txn->req.eoh + 2);
6251 }
6252
6253 /* Executes The applet if it is not done. */
6254 if (!(ctx->ctx.hlua_apphttp.flags & APPLET_DONE)) {
6255
6256 /* Execute the function. */
6257 switch (hlua_ctx_resume(hlua, 1)) {
6258 /* finished. */
6259 case HLUA_E_OK:
6260 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6261 break;
6262
6263 /* yield. */
6264 case HLUA_E_AGAIN:
Thierry Fournier0164f202016-02-20 17:47:43 +01006265 if (hlua->wake_time != TICK_ETERNITY)
6266 task_schedule(ctx->ctx.hlua_apphttp.task, hlua->wake_time);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006267 return;
6268
6269 /* finished with error. */
6270 case HLUA_E_ERRMSG:
6271 /* Display log. */
6272 SEND_ERR(px, "Lua applet http '%s': %s.\n",
6273 rule->arg.hlua_rule->fcn.name, lua_tostring(hlua->T, -1));
6274 lua_pop(hlua->T, 1);
6275 goto error;
6276
6277 case HLUA_E_ERR:
6278 /* Display log. */
6279 SEND_ERR(px, "Lua applet http '%s' return an unknown error.\n",
6280 rule->arg.hlua_rule->fcn.name);
6281 goto error;
6282
6283 default:
6284 goto error;
6285 }
6286 }
6287
6288 if (ctx->ctx.hlua_apphttp.flags & APPLET_DONE) {
6289
6290 /* We must send the final chunk. */
6291 if (ctx->ctx.hlua_apphttp.flags & APPLET_CHUNKED &&
6292 !(ctx->ctx.hlua_apphttp.flags & APPLET_LAST_CHK)) {
6293
6294 /* sent last chunk at once. */
6295 ret = bi_putblk(res, "0\r\n\r\n", 5);
6296
6297 /* critical error. */
6298 if (ret == -2 || ret == -3) {
6299 SEND_ERR(px, "Lua applet http '%s'cannont send last chunk.\n",
6300 rule->arg.hlua_rule->fcn.name);
6301 goto error;
6302 }
6303
6304 /* no enough space error. */
6305 if (ret == -1) {
6306 si_applet_cant_put(si);
6307 return;
6308 }
6309
6310 /* set the last chunk sent. */
6311 ctx->ctx.hlua_apphttp.flags |= APPLET_LAST_CHK;
6312 }
6313
6314 /* close the connection. */
6315
6316 /* status / log */
6317 strm->txn->status = ctx->ctx.hlua_apphttp.status;
6318 strm->logs.tv_request = now;
6319
6320 /* eat the whole request */
6321 bo_skip(si_oc(si), si_ob(si)->o);
6322 res->flags |= CF_READ_NULL;
6323 si_shutr(si);
6324
6325 return;
6326 }
6327
6328error:
6329
6330 /* If we are in HTTP mode, and we are not send any
6331 * data, return a 500 server error in best effort:
6332 * if there are no room avalaible in the buffer,
6333 * just close the connection.
6334 */
6335 bi_putblk(res, error_500, strlen(error_500));
6336 if (!(strm->flags & SF_ERR_MASK))
6337 strm->flags |= SF_ERR_RESOURCE;
6338 si_shutw(si);
6339 si_shutr(si);
6340 ctx->ctx.hlua_apphttp.flags |= APPLET_DONE;
6341}
6342
6343static void hlua_applet_http_release(struct appctx *ctx)
6344{
6345 task_free(ctx->ctx.hlua_apphttp.task);
6346 ctx->ctx.hlua_apphttp.task = NULL;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006347 hlua_ctx_destroy(ctx->ctx.hlua_apphttp.hlua);
6348 pool_free2(pool2_hlua, ctx->ctx.hlua_apphttp.hlua);
6349 ctx->ctx.hlua_apphttp.hlua = NULL;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006350}
6351
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006352/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
6353 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006354 *
6355 * This function can fail with an abort() due to an Lua critical error.
6356 * We are in the configuration parsing process of HAProxy, this abort() is
6357 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006358 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006359static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
6360 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006361{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006362 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006363 int i;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006364
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006365 /* Memory for the rule. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006366 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006367 if (!rule->arg.hlua_rule) {
6368 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006369 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006370 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006371
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006372 /* Memory for arguments. */
6373 rule->arg.hlua_rule->args = calloc(fcn->nargs + 1, sizeof(char *));
6374 if (!rule->arg.hlua_rule->args) {
6375 memprintf(err, "out of memory error");
6376 return ACT_RET_PRS_ERR;
6377 }
6378
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006379 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006380 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006381
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006382 /* Expect some arguments */
6383 for (i = 0; i < fcn->nargs; i++) {
6384 if (*args[i+1] == '\0') {
6385 memprintf(err, "expect %d arguments", fcn->nargs);
6386 return ACT_RET_PRS_ERR;
6387 }
6388 rule->arg.hlua_rule->args[i] = strdup(args[i + 1]);
6389 if (!rule->arg.hlua_rule->args[i]) {
6390 memprintf(err, "out of memory error");
6391 return ACT_RET_PRS_ERR;
6392 }
6393 (*cur_arg)++;
6394 }
6395 rule->arg.hlua_rule->args[i] = NULL;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006396
Thierry FOURNIER42148732015-09-02 17:17:33 +02006397 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02006398 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02006399 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01006400}
6401
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006402static enum act_parse_ret action_register_service_http(const char **args, int *cur_arg, struct proxy *px,
6403 struct act_rule *rule, char **err)
6404{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006405 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006406
Thierry FOURNIER718e2a72015-12-20 20:13:14 +01006407 /* HTTP applets are forbidden in tcp-request rules.
6408 * HTTP applet request requires everything initilized by
6409 * "http_process_request" (analyzer flag AN_REQ_HTTP_INNER).
6410 * The applet will be immediately initilized, but its before
6411 * the call of this analyzer.
6412 */
6413 if (rule->from != ACT_F_HTTP_REQ) {
6414 memprintf(err, "HTTP applets are forbidden from 'tcp-request' rulesets");
6415 return ACT_RET_PRS_ERR;
6416 }
6417
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006418 /* Memory for the rule. */
6419 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6420 if (!rule->arg.hlua_rule) {
6421 memprintf(err, "out of memory error");
6422 return ACT_RET_PRS_ERR;
6423 }
6424
6425 /* Reference the Lua function and store the reference. */
6426 rule->arg.hlua_rule->fcn = *fcn;
6427
6428 /* TODO: later accept arguments. */
6429 rule->arg.hlua_rule->args = NULL;
6430
6431 /* Add applet pointer in the rule. */
6432 rule->applet.obj_type = OBJ_TYPE_APPLET;
6433 rule->applet.name = fcn->name;
6434 rule->applet.init = hlua_applet_http_init;
6435 rule->applet.fct = hlua_applet_http_fct;
6436 rule->applet.release = hlua_applet_http_release;
6437 rule->applet.timeout = hlua_timeout_applet;
6438
6439 return ACT_RET_PRS_OK;
6440}
6441
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006442/* This function is an LUA binding used for registering
6443 * "sample-conv" functions. It expects a converter name used
6444 * in the haproxy configuration file, and an LUA function.
6445 */
6446__LJMP static int hlua_register_action(lua_State *L)
6447{
6448 struct action_kw_list *akl;
6449 const char *name;
6450 int ref;
6451 int len;
6452 struct hlua_function *fcn;
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006453 int nargs;
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006454
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006455 /* Initialise the number of expected arguments at 0. */
6456 nargs = 0;
6457
6458 if (lua_gettop(L) < 3 || lua_gettop(L) > 4)
6459 WILL_LJMP(luaL_error(L, "'register_action' needs between 3 and 4 arguments"));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006460
6461 /* First argument : converter name. */
6462 name = MAY_LJMP(luaL_checkstring(L, 1));
6463
6464 /* Second argument : environment. */
6465 if (lua_type(L, 2) != LUA_TTABLE)
6466 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6467
6468 /* Third argument : lua function. */
6469 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6470
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006471 /* Fouth argument : number of mandatories arguments expected on the configuration line. */
6472 if (lua_gettop(L) >= 4)
6473 nargs = MAY_LJMP(luaL_checkinteger(L, 4));
6474
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006475 /* browse the second argulent as an array. */
6476 lua_pushnil(L);
6477 while (lua_next(L, 2) != 0) {
6478 if (lua_type(L, -1) != LUA_TSTRING)
6479 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
6480
6481 /* Check required environment. Only accepted "http" or "tcp". */
6482 /* Allocate and fill the sample fetch keyword struct. */
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006483 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006484 if (!akl)
6485 WILL_LJMP(luaL_error(L, "lua out of memory error."));
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006486 fcn = calloc(1, sizeof(*fcn));
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006487 if (!fcn)
6488 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6489
6490 /* Fill fcn. */
6491 fcn->name = strdup(name);
6492 if (!fcn->name)
6493 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6494 fcn->function_ref = ref;
6495
Thierry FOURNIER / OZON.IO4b123be2016-12-09 18:03:31 +01006496 /* Set the expected number od arguments. */
6497 fcn->nargs = nargs;
6498
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006499 /* List head */
6500 akl->list.n = akl->list.p = NULL;
6501
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006502 /* action keyword. */
6503 len = strlen("lua.") + strlen(name) + 1;
Thierry FOURNIER3c7a77c2015-09-26 00:51:16 +02006504 akl->kw[0].kw = calloc(1, len);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006505 if (!akl->kw[0].kw)
6506 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6507
6508 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6509
6510 akl->kw[0].match_pfx = 0;
6511 akl->kw[0].private = fcn;
6512 akl->kw[0].parse = action_register_lua;
6513
6514 /* select the action registering point. */
6515 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
6516 tcp_req_cont_keywords_register(akl);
6517 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
6518 tcp_res_cont_keywords_register(akl);
6519 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
6520 http_req_keywords_register(akl);
6521 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
6522 http_res_keywords_register(akl);
6523 else
6524 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
6525 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
6526 "are expected.", lua_tostring(L, -1)));
6527
6528 /* pop the environment string. */
6529 lua_pop(L, 1);
6530 }
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006531 return ACT_RET_PRS_OK;
6532}
6533
6534static enum act_parse_ret action_register_service_tcp(const char **args, int *cur_arg, struct proxy *px,
6535 struct act_rule *rule, char **err)
6536{
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02006537 struct hlua_function *fcn = rule->kw->private;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006538
6539 /* Memory for the rule. */
6540 rule->arg.hlua_rule = calloc(1, sizeof(*rule->arg.hlua_rule));
6541 if (!rule->arg.hlua_rule) {
6542 memprintf(err, "out of memory error");
6543 return ACT_RET_PRS_ERR;
6544 }
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006545
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006546 /* Reference the Lua function and store the reference. */
6547 rule->arg.hlua_rule->fcn = *fcn;
6548
6549 /* TODO: later accept arguments. */
6550 rule->arg.hlua_rule->args = NULL;
6551
6552 /* Add applet pointer in the rule. */
6553 rule->applet.obj_type = OBJ_TYPE_APPLET;
6554 rule->applet.name = fcn->name;
6555 rule->applet.init = hlua_applet_tcp_init;
6556 rule->applet.fct = hlua_applet_tcp_fct;
6557 rule->applet.release = hlua_applet_tcp_release;
6558 rule->applet.timeout = hlua_timeout_applet;
6559
6560 return 0;
6561}
6562
6563/* This function is an LUA binding used for registering
6564 * "sample-conv" functions. It expects a converter name used
6565 * in the haproxy configuration file, and an LUA function.
6566 */
6567__LJMP static int hlua_register_service(lua_State *L)
6568{
6569 struct action_kw_list *akl;
6570 const char *name;
6571 const char *env;
6572 int ref;
6573 int len;
6574 struct hlua_function *fcn;
6575
6576 MAY_LJMP(check_args(L, 3, "register_service"));
6577
6578 /* First argument : converter name. */
6579 name = MAY_LJMP(luaL_checkstring(L, 1));
6580
6581 /* Second argument : environment. */
6582 env = MAY_LJMP(luaL_checkstring(L, 2));
6583
6584 /* Third argument : lua function. */
6585 ref = MAY_LJMP(hlua_checkfunction(L, 3));
6586
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006587 /* Allocate and fill the sample fetch keyword struct. */
6588 akl = calloc(1, sizeof(*akl) + sizeof(struct action_kw) * 2);
6589 if (!akl)
6590 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6591 fcn = calloc(1, sizeof(*fcn));
6592 if (!fcn)
6593 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6594
6595 /* Fill fcn. */
6596 len = strlen("<lua.>") + strlen(name) + 1;
6597 fcn->name = calloc(1, len);
6598 if (!fcn->name)
6599 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6600 snprintf((char *)fcn->name, len, "<lua.%s>", name);
6601 fcn->function_ref = ref;
6602
6603 /* List head */
6604 akl->list.n = akl->list.p = NULL;
6605
6606 /* converter keyword. */
6607 len = strlen("lua.") + strlen(name) + 1;
6608 akl->kw[0].kw = calloc(1, len);
6609 if (!akl->kw[0].kw)
6610 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6611
6612 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
6613
Thierry FOURNIER / OZON.IO02564fd2016-11-12 11:07:05 +01006614 /* Check required environment. Only accepted "http" or "tcp". */
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006615 if (strcmp(env, "tcp") == 0)
6616 akl->kw[0].parse = action_register_service_tcp;
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006617 else if (strcmp(env, "http") == 0)
6618 akl->kw[0].parse = action_register_service_http;
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006619 else
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02006620 WILL_LJMP(luaL_error(L, "lua service environment '%s' is unknown. "
6621 "'tcp' or 'http' are expected."));
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006622
6623 akl->kw[0].match_pfx = 0;
6624 akl->kw[0].private = fcn;
6625
6626 /* End of array. */
6627 memset(&akl->kw[1], 0, sizeof(*akl->kw));
6628
6629 /* Register this new converter */
6630 service_keywords_register(akl);
6631
Thierry FOURNIER8255a752015-09-23 21:03:35 +02006632 return 0;
6633}
6634
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006635/* This function initialises Lua cli handler. It copies the
6636 * arguments in the Lua stack and create channel IO objects.
6637 */
6638static int hlua_cli_parse_fct(char **args, struct appctx *appctx, void *private)
6639{
6640 struct hlua *hlua;
6641 struct hlua_function *fcn;
6642 int i;
6643 const char *error;
6644
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006645 fcn = private;
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006646 appctx->ctx.hlua_cli.fcn = private;
6647
6648 hlua = pool_alloc2(pool2_hlua);
6649 if (!hlua) {
6650 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
6651 return 0;
6652 }
6653 HLUA_INIT(hlua);
6654 appctx->ctx.hlua_cli.hlua = hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006655
6656 /* Create task used by signal to wakeup applets.
6657 * We use the same wakeup fonction than the Lua applet_tcp and
6658 * applet_http. It is absolutely compatible.
6659 */
6660 appctx->ctx.hlua_cli.task = task_new();
6661 if (!appctx->ctx.hlua_cli.task) {
Thierry FOURNIERffbf5692016-12-16 11:14:06 +01006662 SEND_ERR(NULL, "Lua cli '%s': out of memory.\n", fcn->name);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006663 return 0;
6664 }
6665 appctx->ctx.hlua_cli.task->nice = 0;
6666 appctx->ctx.hlua_cli.task->context = appctx;
6667 appctx->ctx.hlua_cli.task->process = hlua_applet_wakeup;
6668
6669 /* Initialises the Lua context */
6670 if (!hlua_ctx_init(hlua, appctx->ctx.hlua_cli.task)) {
6671 SEND_ERR(NULL, "Lua cli '%s': can't initialize Lua context.\n", fcn->name);
6672 return 1;
6673 }
6674
6675 /* The following Lua calls can fail. */
6676 if (!SET_SAFE_LJMP(hlua->T)) {
6677 if (lua_type(hlua->T, -1) == LUA_TSTRING)
6678 error = lua_tostring(hlua->T, -1);
6679 else
6680 error = "critical error";
6681 SEND_ERR(NULL, "Lua cli '%s': %s.\n", fcn->name, error);
6682 goto error;
6683 }
6684
6685 /* Check stack available size. */
6686 if (!lua_checkstack(hlua->T, 2)) {
6687 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6688 goto error;
6689 }
6690
6691 /* Restore the function in the stack. */
6692 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, fcn->function_ref);
6693
6694 /* Once the arguments parsed, the CLI is like an AppletTCP,
6695 * so push AppletTCP in the stack.
6696 * TODO: get_priv() and set_priv() are useless. Maybe we will
6697 * create a new object without these two functions.
6698 */
6699 if (!hlua_applet_tcp_new(hlua->T, appctx)) {
6700 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6701 goto error;
6702 }
6703 hlua->nargs = 1;
6704
6705 /* push keywords in the stack. */
6706 for (i = 0; *args[i]; i++) {
6707 /* Check stack available size. */
6708 if (!lua_checkstack(hlua->T, 1)) {
6709 SEND_ERR(NULL, "Lua cli '%s': full stack.\n", fcn->name);
6710 goto error;
6711 }
6712 lua_pushstring(hlua->T, args[i]);
6713 hlua->nargs++;
6714 }
6715
6716 /* We must initialize the execution timeouts. */
6717 hlua->max_time = hlua_timeout_session;
6718
6719 /* At this point the execution is safe. */
6720 RESET_SAFE_LJMP(hlua->T);
6721
6722 /* It's ok */
6723 return 0;
6724
6725 /* It's not ok. */
6726error:
6727 RESET_SAFE_LJMP(hlua->T);
6728 hlua_ctx_destroy(hlua);
6729 return 1;
6730}
6731
6732static int hlua_cli_io_handler_fct(struct appctx *appctx)
6733{
6734 struct hlua *hlua;
6735 struct stream_interface *si;
6736 struct hlua_function *fcn;
6737
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006738 hlua = appctx->ctx.hlua_cli.hlua;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006739 si = appctx->owner;
Willy Tarreau8ae4f752016-12-14 15:41:45 +01006740 fcn = appctx->ctx.hlua_cli.fcn;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006741
6742 /* If the stream is disconnect or closed, ldo nothing. */
6743 if (unlikely(si->state == SI_ST_DIS || si->state == SI_ST_CLO))
6744 return 1;
6745
6746 /* Execute the function. */
6747 switch (hlua_ctx_resume(hlua, 1)) {
6748
6749 /* finished. */
6750 case HLUA_E_OK:
6751 return 1;
6752
6753 /* yield. */
6754 case HLUA_E_AGAIN:
6755 /* We want write. */
6756 if (HLUA_IS_WAKERESWR(hlua))
6757 si_applet_cant_put(si);
6758 /* Set the timeout. */
6759 if (hlua->wake_time != TICK_ETERNITY)
6760 task_schedule(hlua->task, hlua->wake_time);
6761 return 0;
6762
6763 /* finished with error. */
6764 case HLUA_E_ERRMSG:
6765 /* Display log. */
6766 SEND_ERR(NULL, "Lua cli '%s': %s.\n",
6767 fcn->name, lua_tostring(hlua->T, -1));
6768 lua_pop(hlua->T, 1);
6769 return 1;
6770
6771 case HLUA_E_ERR:
6772 /* Display log. */
6773 SEND_ERR(NULL, "Lua cli '%s' return an unknown error.\n",
6774 fcn->name);
6775 return 1;
6776
6777 default:
6778 return 1;
6779 }
6780
6781 return 1;
6782}
6783
6784static void hlua_cli_io_release_fct(struct appctx *appctx)
6785{
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01006786 hlua_ctx_destroy(appctx->ctx.hlua_cli.hlua);
6787 pool_free2(pool2_hlua, appctx->ctx.hlua_cli.hlua);
6788 appctx->ctx.hlua_cli.hlua = NULL;
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01006789}
6790
6791/* This function is an LUA binding used for registering
6792 * new keywords in the cli. It expects a list of keywords
6793 * which are the "path". It is limited to 5 keywords. A
6794 * description of the command, a function to be executed
6795 * for the parsing and a function for io handlers.
6796 */
6797__LJMP static int hlua_register_cli(lua_State *L)
6798{
6799 struct cli_kw_list *cli_kws;
6800 const char *message;
6801 int ref_io;
6802 int len;
6803 struct hlua_function *fcn;
6804 int index;
6805 int i;
6806
6807 MAY_LJMP(check_args(L, 3, "register_cli"));
6808
6809 /* First argument : an array of maximum 5 keywords. */
6810 if (!lua_istable(L, 1))
6811 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table"));
6812
6813 /* Second argument : string with contextual message. */
6814 message = MAY_LJMP(luaL_checkstring(L, 2));
6815
6816 /* Third and fourth argument : lua function. */
6817 ref_io = MAY_LJMP(hlua_checkfunction(L, 3));
6818
6819 /* Allocate and fill the sample fetch keyword struct. */
6820 cli_kws = calloc(1, sizeof(*cli_kws) + sizeof(struct cli_kw) * 2);
6821 if (!cli_kws)
6822 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6823 fcn = calloc(1, sizeof(*fcn));
6824 if (!fcn)
6825 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6826
6827 /* Fill path. */
6828 index = 0;
6829 lua_pushnil(L);
6830 while(lua_next(L, 1) != 0) {
6831 if (index >= 5)
6832 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table with a maximum of 5 entries"));
6833 if (lua_type(L, -1) != LUA_TSTRING)
6834 WILL_LJMP(luaL_argerror(L, 1, "1st argument must be a table filled with strings"));
6835 cli_kws->kw[0].str_kw[index] = strdup(lua_tostring(L, -1));
6836 if (!cli_kws->kw[0].str_kw[index])
6837 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6838 index++;
6839 lua_pop(L, 1);
6840 }
6841
6842 /* Copy help message. */
6843 cli_kws->kw[0].usage = strdup(message);
6844 if (!cli_kws->kw[0].usage)
6845 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6846
6847 /* Fill fcn io handler. */
6848 len = strlen("<lua.cli>") + 1;
6849 for (i = 0; i < index; i++)
6850 len += strlen(cli_kws->kw[0].str_kw[i]) + 1;
6851 fcn->name = calloc(1, len);
6852 if (!fcn->name)
6853 WILL_LJMP(luaL_error(L, "lua out of memory error."));
6854 strncat((char *)fcn->name, "<lua.cli", len);
6855 for (i = 0; i < index; i++) {
6856 strncat((char *)fcn->name, ".", len);
6857 strncat((char *)fcn->name, cli_kws->kw[0].str_kw[i], len);
6858 }
6859 strncat((char *)fcn->name, ">", len);
6860 fcn->function_ref = ref_io;
6861
6862 /* Fill last entries. */
6863 cli_kws->kw[0].private = fcn;
6864 cli_kws->kw[0].parse = hlua_cli_parse_fct;
6865 cli_kws->kw[0].io_handler = hlua_cli_io_handler_fct;
6866 cli_kws->kw[0].io_release = hlua_cli_io_release_fct;
6867
6868 /* Register this new converter */
6869 cli_register_kw(cli_kws);
6870
6871 return 0;
6872}
6873
Thierry FOURNIERbd413492015-03-03 16:52:26 +01006874static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
6875 struct proxy *defpx, const char *file, int line,
6876 char **err, unsigned int *timeout)
6877{
6878 const char *error;
6879
6880 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
6881 if (error && *error != '\0') {
6882 memprintf(err, "%s: invalid timeout", args[0]);
6883 return -1;
6884 }
6885 return 0;
6886}
6887
6888static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
6889 struct proxy *defpx, const char *file, int line,
6890 char **err)
6891{
6892 return hlua_read_timeout(args, section_type, curpx, defpx,
6893 file, line, err, &hlua_timeout_session);
6894}
6895
6896static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
6897 struct proxy *defpx, const char *file, int line,
6898 char **err)
6899{
6900 return hlua_read_timeout(args, section_type, curpx, defpx,
6901 file, line, err, &hlua_timeout_task);
6902}
6903
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02006904static int hlua_applet_timeout(char **args, int section_type, struct proxy *curpx,
6905 struct proxy *defpx, const char *file, int line,
6906 char **err)
6907{
6908 return hlua_read_timeout(args, section_type, curpx, defpx,
6909 file, line, err, &hlua_timeout_applet);
6910}
6911
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01006912static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
6913 struct proxy *defpx, const char *file, int line,
6914 char **err)
6915{
6916 char *error;
6917
6918 hlua_nb_instruction = strtoll(args[1], &error, 10);
6919 if (*error != '\0') {
6920 memprintf(err, "%s: invalid number", args[0]);
6921 return -1;
6922 }
6923 return 0;
6924}
6925
Willy Tarreau32f61e22015-03-18 17:54:59 +01006926static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
6927 struct proxy *defpx, const char *file, int line,
6928 char **err)
6929{
6930 char *error;
6931
6932 if (*(args[1]) == 0) {
6933 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
6934 return -1;
6935 }
6936 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
6937 if (*error != '\0') {
6938 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
6939 return -1;
6940 }
6941 return 0;
6942}
6943
6944
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006945/* This function is called by the main configuration key "lua-load". It loads and
6946 * execute an lua file during the parsing of the HAProxy configuration file. It is
6947 * the main lua entry point.
6948 *
6949 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
6950 * occured, otherwise it returns 0.
6951 *
6952 * In some error case, LUA set an error message in top of the stack. This function
6953 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02006954 *
6955 * This function can fail with an abort() due to an Lua critical error.
6956 * We are in the configuration parsing process of HAProxy, this abort() is
6957 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01006958 */
6959static int hlua_load(char **args, int section_type, struct proxy *curpx,
6960 struct proxy *defpx, const char *file, int line,
6961 char **err)
6962{
6963 int error;
6964
6965 /* Just load and compile the file. */
6966 error = luaL_loadfile(gL.T, args[1]);
6967 if (error) {
6968 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
6969 lua_pop(gL.T, 1);
6970 return -1;
6971 }
6972
6973 /* If no syntax error where detected, execute the code. */
6974 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
6975 switch (error) {
6976 case LUA_OK:
6977 break;
6978 case LUA_ERRRUN:
6979 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
6980 lua_pop(gL.T, 1);
6981 return -1;
6982 case LUA_ERRMEM:
6983 memprintf(err, "lua out of memory error\n");
6984 return -1;
6985 case LUA_ERRERR:
6986 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
6987 lua_pop(gL.T, 1);
6988 return -1;
6989 case LUA_ERRGCMM:
6990 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
6991 lua_pop(gL.T, 1);
6992 return -1;
6993 default:
6994 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
6995 lua_pop(gL.T, 1);
6996 return -1;
6997 }
6998
6999 return 0;
7000}
7001
7002/* configuration keywords declaration */
7003static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01007004 { CFG_GLOBAL, "lua-load", hlua_load },
7005 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
7006 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIER56da1012015-10-01 08:42:31 +02007007 { CFG_GLOBAL, "tune.lua.service-timeout", hlua_applet_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01007008 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01007009 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007010 { 0, NULL, NULL },
7011}};
7012
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007013/* This function can fail with an abort() due to an Lua critical error.
7014 * We are in the initialisation process of HAProxy, this abort() is
7015 * tolerated.
7016 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007017int hlua_post_init()
7018{
7019 struct hlua_init_function *init;
7020 const char *msg;
7021 enum hlua_exec ret;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007022 const char *error;
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007023
Thierry Fournier3d4a6752016-02-19 20:53:30 +01007024 /* Call post initialisation function in safe environement. */
7025 if (!SET_SAFE_LJMP(gL.T)) {
7026 if (lua_type(gL.T, -1) == LUA_TSTRING)
7027 error = lua_tostring(gL.T, -1);
7028 else
7029 error = "critical error";
7030 fprintf(stderr, "Lua post-init: %s.\n", error);
7031 exit(1);
7032 }
7033 hlua_fcn_post_init(gL.T);
7034 RESET_SAFE_LJMP(gL.T);
7035
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007036 list_for_each_entry(init, &hlua_init_functions, l) {
7037 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
7038 ret = hlua_ctx_resume(&gL, 0);
7039 switch (ret) {
7040 case HLUA_E_OK:
7041 lua_pop(gL.T, -1);
7042 return 1;
7043 case HLUA_E_AGAIN:
7044 Alert("lua init: yield not allowed.\n");
7045 return 0;
7046 case HLUA_E_ERRMSG:
7047 msg = lua_tostring(gL.T, -1);
7048 Alert("lua init: %s.\n", msg);
7049 return 0;
7050 case HLUA_E_ERR:
7051 default:
7052 Alert("lua init: unknown runtime error.\n");
7053 return 0;
7054 }
7055 }
7056 return 1;
7057}
7058
Willy Tarreau32f61e22015-03-18 17:54:59 +01007059/* The memory allocator used by the Lua stack. <ud> is a pointer to the
7060 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
7061 * is the previously allocated size or the kind of object in case of a new
7062 * allocation. <nsize> is the requested new size.
7063 */
7064static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
7065{
7066 struct hlua_mem_allocator *zone = ud;
7067
7068 if (nsize == 0) {
7069 /* it's a free */
7070 if (ptr)
7071 zone->allocated -= osize;
7072 free(ptr);
7073 return NULL;
7074 }
7075
7076 if (!ptr) {
7077 /* it's a new allocation */
7078 if (zone->limit && zone->allocated + nsize > zone->limit)
7079 return NULL;
7080
7081 ptr = malloc(nsize);
7082 if (ptr)
7083 zone->allocated += nsize;
7084 return ptr;
7085 }
7086
7087 /* it's a realloc */
7088 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
7089 return NULL;
7090
7091 ptr = realloc(ptr, nsize);
7092 if (ptr)
7093 zone->allocated += nsize - osize;
7094 return ptr;
7095}
7096
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007097/* Ithis function can fail with an abort() due to an Lua critical error.
7098 * We are in the initialisation process of HAProxy, this abort() is
7099 * tolerated.
7100 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007101void hlua_init(void)
7102{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007103 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007104 int idx;
7105 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007106 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007107 char *p;
Thierry Fournierfd107a22016-02-19 19:57:23 +01007108 const char *error_msg;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007109#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007110 struct srv_kw *kw;
7111 int tmp_error;
7112 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007113 char *args[] = { /* SSL client configuration. */
7114 "ssl",
7115 "verify",
7116 "none",
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007117 NULL
7118 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007119#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007120
Thierry FOURNIERebed6e92016-12-16 11:54:07 +01007121 /* Initialise struct hlua and com signals pool */
7122 pool2_hlua = create_pool("hlua", sizeof(struct hlua), MEM_F_SHARED);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007123 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
7124
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01007125 /* Register configuration keywords. */
7126 cfg_register_keywords(&cfg_kws);
7127
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007128 /* Init main lua stack. */
7129 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01007130 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01007131 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007132 gL.T = luaL_newstate();
7133 hlua_sethlua(&gL);
7134 gL.Tref = LUA_REFNIL;
7135 gL.task = NULL;
7136
Thierry FOURNIERbabae282015-09-17 11:36:37 +02007137 /* From this point, until the end of the initialisation fucntion,
7138 * the Lua function can fail with an abort. We are in the initialisation
7139 * process of HAProxy, this abort() is tolerated.
7140 */
7141
Willy Tarreau32f61e22015-03-18 17:54:59 +01007142 /* change the memory allocators to track memory usage */
7143 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
7144
Thierry FOURNIER380d0932015-01-23 14:27:52 +01007145 /* Initialise lua. */
7146 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007147
Thierry Fournier75933d42016-01-21 09:30:18 +01007148 /* Set safe environment for the initialisation. */
7149 if (!SET_SAFE_LJMP(gL.T)) {
Thierry Fournierfd107a22016-02-19 19:57:23 +01007150 if (lua_type(gL.T, -1) == LUA_TSTRING)
7151 error_msg = lua_tostring(gL.T, -1);
7152 else
7153 error_msg = "critical error";
7154 fprintf(stderr, "Lua init: %s.\n", error_msg);
Thierry Fournier75933d42016-01-21 09:30:18 +01007155 exit(1);
7156 }
7157
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007158 /*
7159 *
7160 * Create "core" object.
7161 *
7162 */
7163
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01007164 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007165 lua_newtable(gL.T);
7166
7167 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01007168 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007169 hlua_class_const_int(gL.T, log_levels[i], i);
7170
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007171 /* Register special functions. */
7172 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01007173 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01007174 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01007175 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02007176 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007177 hlua_class_function(gL.T, "register_service", hlua_register_service);
Thierry FOURNIER / OZON.IOa44fdd92016-11-13 13:19:20 +01007178 hlua_class_function(gL.T, "register_cli", hlua_register_cli);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01007179 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01007180 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01007181 hlua_class_function(gL.T, "sleep", hlua_sleep);
7182 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01007183 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
7184 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
7185 hlua_class_function(gL.T, "set_map", hlua_set_map);
7186 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007187 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007188 hlua_class_function(gL.T, "log", hlua_log);
7189 hlua_class_function(gL.T, "Debug", hlua_log_debug);
7190 hlua_class_function(gL.T, "Info", hlua_log_info);
7191 hlua_class_function(gL.T, "Warning", hlua_log_warning);
7192 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02007193 hlua_class_function(gL.T, "done", hlua_done);
Thierry Fournierfb0b5462016-01-21 09:28:58 +01007194 hlua_fcn_reg_core_fcn(gL.T);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01007195
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01007196 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007197
7198 /*
7199 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007200 * Register class Map
7201 *
7202 */
7203
7204 /* This table entry is the object "Map" base. */
7205 lua_newtable(gL.T);
7206
7207 /* register pattern types. */
7208 for (i=0; i<PAT_MATCH_NUM; i++)
7209 hlua_class_const_int(gL.T, pat_match_names[i], i);
7210
7211 /* register constructor. */
7212 hlua_class_function(gL.T, "new", hlua_map_new);
7213
7214 /* Create and fill the metatable. */
7215 lua_newtable(gL.T);
7216
7217 /* Create and fille the __index entry. */
7218 lua_pushstring(gL.T, "__index");
7219 lua_newtable(gL.T);
7220
7221 /* Register . */
7222 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
7223 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
7224
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007225 lua_rawset(gL.T, -3);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007226
Thierry Fournier45e78d72016-02-19 18:34:46 +01007227 /* Register previous table in the registry with reference and named entry.
7228 * The function hlua_register_metatable() pops the stack, so we
7229 * previously create a copy of the table.
7230 */
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007231 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007232 class_map_ref = hlua_register_metatable(gL.T, CLASS_MAP);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02007233
7234 /* Assign the metatable to the mai Map object. */
7235 lua_setmetatable(gL.T, -2);
7236
7237 /* Set a name to the table. */
7238 lua_setglobal(gL.T, "Map");
7239
7240 /*
7241 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007242 * Register class Channel
7243 *
7244 */
7245
7246 /* Create and fill the metatable. */
7247 lua_newtable(gL.T);
7248
7249 /* Create and fille the __index entry. */
7250 lua_pushstring(gL.T, "__index");
7251 lua_newtable(gL.T);
7252
7253 /* Register . */
7254 hlua_class_function(gL.T, "get", hlua_channel_get);
7255 hlua_class_function(gL.T, "dup", hlua_channel_dup);
7256 hlua_class_function(gL.T, "getline", hlua_channel_getline);
7257 hlua_class_function(gL.T, "set", hlua_channel_set);
7258 hlua_class_function(gL.T, "append", hlua_channel_append);
7259 hlua_class_function(gL.T, "send", hlua_channel_send);
7260 hlua_class_function(gL.T, "forward", hlua_channel_forward);
7261 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
7262 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
Thierry FOURNIER / OZON.IO65192f32016-11-07 15:28:40 +01007263 hlua_class_function(gL.T, "is_full", hlua_channel_is_full);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007264
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007265 lua_rawset(gL.T, -3);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007266
7267 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007268 class_channel_ref = hlua_register_metatable(gL.T, CLASS_CHANNEL);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01007269
7270 /*
7271 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007272 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007273 *
7274 */
7275
7276 /* Create and fill the metatable. */
7277 lua_newtable(gL.T);
7278
7279 /* Create and fille the __index entry. */
7280 lua_pushstring(gL.T, "__index");
7281 lua_newtable(gL.T);
7282
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007283 /* Browse existing fetches and create the associated
7284 * object method.
7285 */
7286 sf = NULL;
7287 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
7288
7289 /* Dont register the keywork if the arguments check function are
7290 * not safe during the runtime.
7291 */
7292 if ((sf->val_args != NULL) &&
7293 (sf->val_args != val_payload_lv) &&
7294 (sf->val_args != val_hdr))
7295 continue;
7296
7297 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7298 * by an underscore.
7299 */
7300 strncpy(trash.str, sf->kw, trash.size);
7301 trash.str[trash.size - 1] = '\0';
7302 for (p = trash.str; *p; p++)
7303 if (*p == '.' || *p == '-' || *p == '+')
7304 *p = '_';
7305
7306 /* Register the function. */
7307 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01007308 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007309 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007310 lua_rawset(gL.T, -3);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01007311 }
7312
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007313 lua_rawset(gL.T, -3);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007314
7315 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007316 class_fetches_ref = hlua_register_metatable(gL.T, CLASS_FETCHES);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007317
7318 /*
7319 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007320 * Register class Converters
7321 *
7322 */
7323
7324 /* Create and fill the metatable. */
7325 lua_newtable(gL.T);
7326
7327 /* Create and fill the __index entry. */
7328 lua_pushstring(gL.T, "__index");
7329 lua_newtable(gL.T);
7330
7331 /* Browse existing converters and create the associated
7332 * object method.
7333 */
7334 sc = NULL;
7335 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
7336 /* Dont register the keywork if the arguments check function are
7337 * not safe during the runtime.
7338 */
7339 if (sc->val_args != NULL)
7340 continue;
7341
7342 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
7343 * by an underscore.
7344 */
7345 strncpy(trash.str, sc->kw, trash.size);
7346 trash.str[trash.size - 1] = '\0';
7347 for (p = trash.str; *p; p++)
7348 if (*p == '.' || *p == '-' || *p == '+')
7349 *p = '_';
7350
7351 /* Register the function. */
7352 lua_pushstring(gL.T, trash.str);
7353 lua_pushlightuserdata(gL.T, sc);
7354 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007355 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007356 }
7357
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007358 lua_rawset(gL.T, -3);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007359
7360 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007361 class_converters_ref = hlua_register_metatable(gL.T, CLASS_CONVERTERS);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01007362
7363 /*
7364 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007365 * Register class HTTP
7366 *
7367 */
7368
7369 /* Create and fill the metatable. */
7370 lua_newtable(gL.T);
7371
7372 /* Create and fille the __index entry. */
7373 lua_pushstring(gL.T, "__index");
7374 lua_newtable(gL.T);
7375
7376 /* Register Lua functions. */
7377 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
7378 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
7379 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
7380 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
7381 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
7382 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
7383 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
7384 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
7385 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
7386 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
7387
7388 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
7389 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
7390 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
7391 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
7392 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
7393 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02007394 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007395
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007396 lua_rawset(gL.T, -3);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007397
7398 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007399 class_http_ref = hlua_register_metatable(gL.T, CLASS_HTTP);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01007400
7401 /*
7402 *
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007403 * Register class AppletTCP
7404 *
7405 */
7406
7407 /* Create and fill the metatable. */
7408 lua_newtable(gL.T);
7409
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007410 /* Create and fille the __index entry. */
7411 lua_pushstring(gL.T, "__index");
7412 lua_newtable(gL.T);
7413
7414 /* Register Lua functions. */
Thierry FOURNIER / OZON.IO3e1d7912016-12-12 12:29:34 +01007415 hlua_class_function(gL.T, "getline", hlua_applet_tcp_getline);
7416 hlua_class_function(gL.T, "receive", hlua_applet_tcp_recv);
7417 hlua_class_function(gL.T, "send", hlua_applet_tcp_send);
7418 hlua_class_function(gL.T, "set_priv", hlua_applet_tcp_set_priv);
7419 hlua_class_function(gL.T, "get_priv", hlua_applet_tcp_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007420 hlua_class_function(gL.T, "set_var", hlua_applet_tcp_set_var);
7421 hlua_class_function(gL.T, "unset_var", hlua_applet_tcp_unset_var);
7422 hlua_class_function(gL.T, "get_var", hlua_applet_tcp_get_var);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007423
7424 lua_settable(gL.T, -3);
7425
7426 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007427 class_applet_tcp_ref = hlua_register_metatable(gL.T, CLASS_APPLET_TCP);
Thierry FOURNIERf0a64b62015-09-19 12:36:17 +02007428
7429 /*
7430 *
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007431 * Register class AppletHTTP
7432 *
7433 */
7434
7435 /* Create and fill the metatable. */
7436 lua_newtable(gL.T);
7437
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007438 /* Create and fille the __index entry. */
7439 lua_pushstring(gL.T, "__index");
7440 lua_newtable(gL.T);
7441
7442 /* Register Lua functions. */
Thierry FOURNIER8db004c2015-12-25 01:33:18 +01007443 hlua_class_function(gL.T, "set_priv", hlua_applet_http_set_priv);
7444 hlua_class_function(gL.T, "get_priv", hlua_applet_http_get_priv);
Thierry FOURNIER / OZON.IO4394a2c2016-12-12 12:31:54 +01007445 hlua_class_function(gL.T, "set_var", hlua_applet_http_set_var);
7446 hlua_class_function(gL.T, "unset_var", hlua_applet_http_unset_var);
7447 hlua_class_function(gL.T, "get_var", hlua_applet_http_get_var);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007448 hlua_class_function(gL.T, "getline", hlua_applet_http_getline);
7449 hlua_class_function(gL.T, "receive", hlua_applet_http_recv);
7450 hlua_class_function(gL.T, "send", hlua_applet_http_send);
7451 hlua_class_function(gL.T, "add_header", hlua_applet_http_addheader);
7452 hlua_class_function(gL.T, "set_status", hlua_applet_http_status);
7453 hlua_class_function(gL.T, "start_response", hlua_applet_http_start_response);
7454
7455 lua_settable(gL.T, -3);
7456
7457 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007458 class_applet_http_ref = hlua_register_metatable(gL.T, CLASS_APPLET_HTTP);
Thierry FOURNIERa30b5db2015-09-18 09:04:27 +02007459
7460 /*
7461 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01007462 * Register class TXN
7463 *
7464 */
7465
7466 /* Create and fill the metatable. */
7467 lua_newtable(gL.T);
7468
7469 /* Create and fille the __index entry. */
7470 lua_pushstring(gL.T, "__index");
7471 lua_newtable(gL.T);
7472
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007473 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01007474 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
7475 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007476 hlua_class_function(gL.T, "set_var", hlua_set_var);
Christopher Faulet85d79c92016-11-09 16:54:56 +01007477 hlua_class_function(gL.T, "unset_var", hlua_unset_var);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02007478 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02007479 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01007480 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
7481 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
7482 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01007483 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
7484 hlua_class_function(gL.T, "log", hlua_txn_log);
7485 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
7486 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
7487 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
7488 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01007489
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007490 lua_rawset(gL.T, -3);
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01007491
7492 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007493 class_txn_ref = hlua_register_metatable(gL.T, CLASS_TXN);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007494
7495 /*
7496 *
7497 * Register class Socket
7498 *
7499 */
7500
7501 /* Create and fill the metatable. */
7502 lua_newtable(gL.T);
7503
7504 /* Create and fille the __index entry. */
7505 lua_pushstring(gL.T, "__index");
7506 lua_newtable(gL.T);
7507
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007508#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007509 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01007510#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007511 hlua_class_function(gL.T, "connect", hlua_socket_connect);
7512 hlua_class_function(gL.T, "send", hlua_socket_send);
7513 hlua_class_function(gL.T, "receive", hlua_socket_receive);
7514 hlua_class_function(gL.T, "close", hlua_socket_close);
7515 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
7516 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
7517 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
7518 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
7519
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007520 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007521
7522 /* Register the garbage collector entry. */
7523 lua_pushstring(gL.T, "__gc");
7524 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
Thierry FOURNIER84e73c82015-09-25 22:13:32 +02007525 lua_rawset(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007526
7527 /* Register previous table in the registry with reference and named entry. */
Thierry Fournier45e78d72016-02-19 18:34:46 +01007528 class_socket_ref = hlua_register_metatable(gL.T, CLASS_SOCKET);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007529
7530 /* Proxy and server configuration initialisation. */
7531 memset(&socket_proxy, 0, sizeof(socket_proxy));
7532 init_new_proxy(&socket_proxy);
7533 socket_proxy.parent = NULL;
7534 socket_proxy.last_change = now.tv_sec;
7535 socket_proxy.id = "LUA-SOCKET";
7536 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
7537 socket_proxy.maxconn = 0;
7538 socket_proxy.accept = NULL;
7539 socket_proxy.options2 |= PR_O2_INDEPSTR;
7540 socket_proxy.srv = NULL;
7541 socket_proxy.conn_retries = 0;
7542 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
7543
7544 /* Init TCP server: unchanged parameters */
7545 memset(&socket_tcp, 0, sizeof(socket_tcp));
7546 socket_tcp.next = NULL;
7547 socket_tcp.proxy = &socket_proxy;
7548 socket_tcp.obj_type = OBJ_TYPE_SERVER;
7549 LIST_INIT(&socket_tcp.actconns);
7550 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007551 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007552 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007553 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007554 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
7555 socket_tcp.last_change = 0;
7556 socket_tcp.id = "LUA-TCP-CONN";
7557 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7558 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7559 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
7560
7561 /* XXX: Copy default parameter from default server,
7562 * but the default server is not initialized.
7563 */
7564 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
7565 socket_tcp.minconn = socket_proxy.defsrv.minconn;
7566 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
7567 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
7568 socket_tcp.onerror = socket_proxy.defsrv.onerror;
7569 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7570 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
7571 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7572 socket_tcp.uweight = socket_proxy.defsrv.iweight;
7573 socket_tcp.iweight = socket_proxy.defsrv.iweight;
7574
7575 socket_tcp.check.status = HCHK_STATUS_INI;
7576 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
7577 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
7578 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
7579 socket_tcp.check.server = &socket_tcp;
7580
7581 socket_tcp.agent.status = HCHK_STATUS_INI;
7582 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
7583 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
7584 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
7585 socket_tcp.agent.server = &socket_tcp;
7586
7587 socket_tcp.xprt = &raw_sock;
7588
7589#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007590 /* Init TCP server: unchanged parameters */
7591 memset(&socket_ssl, 0, sizeof(socket_ssl));
7592 socket_ssl.next = NULL;
7593 socket_ssl.proxy = &socket_proxy;
7594 socket_ssl.obj_type = OBJ_TYPE_SERVER;
7595 LIST_INIT(&socket_ssl.actconns);
7596 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02007597 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02007598 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02007599 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007600 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
7601 socket_ssl.last_change = 0;
7602 socket_ssl.id = "LUA-SSL-CONN";
7603 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7604 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
7605 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
7606
7607 /* XXX: Copy default parameter from default server,
7608 * but the default server is not initialized.
7609 */
7610 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
7611 socket_ssl.minconn = socket_proxy.defsrv.minconn;
7612 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
7613 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
7614 socket_ssl.onerror = socket_proxy.defsrv.onerror;
7615 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
7616 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
7617 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
7618 socket_ssl.uweight = socket_proxy.defsrv.iweight;
7619 socket_ssl.iweight = socket_proxy.defsrv.iweight;
7620
7621 socket_ssl.check.status = HCHK_STATUS_INI;
7622 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
7623 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
7624 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
7625 socket_ssl.check.server = &socket_ssl;
7626
7627 socket_ssl.agent.status = HCHK_STATUS_INI;
7628 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
7629 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
7630 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
7631 socket_ssl.agent.server = &socket_ssl;
7632
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007633 socket_ssl.use_ssl = 1;
7634 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007635
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007636 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007637 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
7638 /*
7639 *
7640 * If the keyword is not known, we can search in the registered
7641 * server keywords. This is usefull to configure special SSL
7642 * features like client certificates and ssl_verify.
7643 *
7644 */
7645 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
7646 if (tmp_error != 0) {
7647 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
7648 abort(); /* This must be never arrives because the command line
7649 not editable by the user. */
7650 }
7651 idx += kw->skip;
7652 }
7653 }
7654
7655 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01007656 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01007657#endif
Thierry Fournier75933d42016-01-21 09:30:18 +01007658
7659 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01007660}