blob: 7e75a31c6497bada6bb862b5395e436dea49f949 [file] [log] [blame]
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001#include <sys/socket.h>
2
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003#include <ctype.h>
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004#include <setjmp.h>
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01006#include <lauxlib.h>
7#include <lua.h>
8#include <lualib.h>
9
Thierry FOURNIER463119c2015-03-10 00:35:36 +010010#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
11#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010012#endif
13
Thierry FOURNIER380d0932015-01-23 14:27:52 +010014#include <ebpttree.h>
15
16#include <common/cfgparse.h>
17
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010018#include <types/connection.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010019#include <types/hlua.h>
20#include <types/proxy.h>
21
Thierry FOURNIER55da1652015-01-23 11:36:30 +010022#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020023#include <proto/applet.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010024#include <proto/channel.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010025#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010026#include <proto/hlua.h>
Thierry FOURNIER3def3932015-04-07 11:27:54 +020027#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010028#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010029#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010030#include <proto/payload.h>
31#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010032#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010033#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010034#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010035#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020036#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020037#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010038#include <proto/ssl_sock.h>
39#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010040#include <proto/task.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020041#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010042
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010043/* Lua uses longjmp to perform yield or throwing errors. This
44 * macro is used only for identifying the function that can
45 * not return because a longjmp is executed.
46 * __LJMP marks a prototype of hlua file that can use longjmp.
47 * WILL_LJMP() marks an lua function that will use longjmp.
48 * MAY_LJMP() marks an lua function that may use longjmp.
49 */
50#define __LJMP
51#define WILL_LJMP(func) func
52#define MAY_LJMP(func) func
53
Thierry FOURNIERbabae282015-09-17 11:36:37 +020054/* This couple of function executes securely some Lua calls outside of
55 * the lua runtime environment. Each Lua call can return a longjmp
56 * if it encounter a memory error.
57 *
58 * Lua documentation extract:
59 *
60 * If an error happens outside any protected environment, Lua calls
61 * a panic function (see lua_atpanic) and then calls abort, thus
62 * exiting the host application. Your panic function can avoid this
63 * exit by never returning (e.g., doing a long jump to your own
64 * recovery point outside Lua).
65 *
66 * The panic function runs as if it were a message handler (see
67 * §2.3); in particular, the error message is at the top of the
68 * stack. However, there is no guarantee about stack space. To push
69 * anything on the stack, the panic function must first check the
70 * available space (see §4.2).
71 *
72 * We must check all the Lua entry point. This includes:
73 * - The include/proto/hlua.h exported functions
74 * - the task wrapper function
75 * - The action wrapper function
76 * - The converters wrapper function
77 * - The sample-fetch wrapper functions
78 *
79 * It is tolerated that the initilisation function returns an abort.
80 * Before each Lua abort, an error message is writed on stderr.
81 *
82 * The macro SET_SAFE_LJMP initialise the longjmp. The Macro
83 * RESET_SAFE_LJMP reset the longjmp. These function must be macro
84 * because they must be exists in the program stack when the longjmp
85 * is called.
86 */
87jmp_buf safe_ljmp_env;
88static int hlua_panic_safe(lua_State *L) { return 0; }
89static int hlua_panic_ljmp(lua_State *L) { longjmp(safe_ljmp_env, 1); }
90
91#define SET_SAFE_LJMP(__L) \
92 ({ \
93 int ret; \
94 if (setjmp(safe_ljmp_env) != 0) { \
95 lua_atpanic(__L, hlua_panic_safe); \
96 ret = 0; \
97 } else { \
98 lua_atpanic(__L, hlua_panic_ljmp); \
99 ret = 1; \
100 } \
101 ret; \
102 })
103
104/* If we are the last function catching Lua errors, we
105 * must reset the panic function.
106 */
107#define RESET_SAFE_LJMP(__L) \
108 do { \
109 lua_atpanic(__L, hlua_panic_safe); \
110 } while(0)
111
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100112/* The main Lua execution context. */
113struct hlua gL;
114
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100115/* This is the memory pool containing all the signal structs. These
116 * struct are used to store each requiered signal between two tasks.
117 */
118struct pool_head *pool2_hlua_com;
119
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100120/* Used for Socket connection. */
121static struct proxy socket_proxy;
122static struct server socket_tcp;
123#ifdef USE_OPENSSL
124static struct server socket_ssl;
125#endif
126
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +0100127/* List head of the function called at the initialisation time. */
128struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
129
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100130/* The following variables contains the reference of the different
131 * Lua classes. These references are useful for identify metadata
132 * associated with an object.
133 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +0100134static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +0100135static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +0100136static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +0100137static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +0100138static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +0100139static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +0200140static int class_map_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +0100141
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100142/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +0200143 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +0100144 * short timeout. Lua linked with tasks doesn't have a timeout
145 * because a task may remain alive during all the haproxy execution.
146 */
147static unsigned int hlua_timeout_session = 4000; /* session timeout. */
148static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
149
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100150/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
151 * it is used for preventing infinite loops.
152 *
153 * I test the scheer with an infinite loop containing one incrementation
154 * and one test. I run this loop between 10 seconds, I raise a ceil of
155 * 710M loops from one interrupt each 9000 instructions, so I fix the value
156 * to one interrupt each 10 000 instructions.
157 *
158 * configured | Number of
159 * instructions | loops executed
160 * between two | in milions
161 * forced yields |
162 * ---------------+---------------
163 * 10 | 160
164 * 500 | 670
165 * 1000 | 680
166 * 5000 | 700
167 * 7000 | 700
168 * 8000 | 700
169 * 9000 | 710 <- ceil
170 * 10000 | 710
171 * 100000 | 710
172 * 1000000 | 710
173 *
174 */
175static unsigned int hlua_nb_instruction = 10000;
176
Willy Tarreau32f61e22015-03-18 17:54:59 +0100177/* Descriptor for the memory allocation state. If limit is not null, it will
178 * be enforced on any memory allocation.
179 */
180struct hlua_mem_allocator {
181 size_t allocated;
182 size_t limit;
183};
184
185static struct hlua_mem_allocator hlua_global_allocator;
186
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100187/* These functions converts types between HAProxy internal args or
188 * sample and LUA types. Another function permits to check if the
189 * LUA stack contains arguments according with an required ARG_T
190 * format.
191 */
192static int hlua_arg2lua(lua_State *L, const struct arg *arg);
193static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100194__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
195 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100196static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100197static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100198static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
199
Thierry FOURNIER23bc3752015-09-11 19:15:43 +0200200#define SEND_ERR(__be, __fmt, __args...) \
201 do { \
202 send_log(__be, LOG_ERR, __fmt, ## __args); \
203 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) \
204 Alert(__fmt, ## __args); \
205 } while (0)
206
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100207/* Used to check an Lua function type in the stack. It creates and
208 * returns a reference of the function. This function throws an
209 * error if the rgument is not a "function".
210 */
211__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
212{
213 if (!lua_isfunction(L, argno)) {
214 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
215 WILL_LJMP(luaL_argerror(L, argno, msg));
216 }
217 lua_pushvalue(L, argno);
218 return luaL_ref(L, LUA_REGISTRYINDEX);
219}
220
221/* The three following functions are useful for adding entries
222 * in a table. These functions takes a string and respectively an
223 * integer, a string or a function and add it to the table in the
224 * top of the stack.
225 *
226 * These functions throws an error if no more stack size is
227 * available.
228 */
229__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100230 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100231{
232 if (!lua_checkstack(L, 2))
233 WILL_LJMP(luaL_error(L, "full stack"));
234 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100235 lua_pushinteger(L, value);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100236 lua_settable(L, -3);
237}
238__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
239 const char *value)
240{
241 if (!lua_checkstack(L, 2))
242 WILL_LJMP(luaL_error(L, "full stack"));
243 lua_pushstring(L, name);
244 lua_pushstring(L, value);
245 lua_settable(L, -3);
246}
247__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
248 int (*function)(lua_State *L))
249{
250 if (!lua_checkstack(L, 2))
251 WILL_LJMP(luaL_error(L, "full stack"));
252 lua_pushstring(L, name);
253 lua_pushcclosure(L, function, 0);
254 lua_settable(L, -3);
255}
256
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +0200257__LJMP static int hlua_dump_object(struct lua_State *L)
258{
259 const char *name = (const char *)lua_tostring(L, lua_upvalueindex(1));
260 lua_pushfstring(L, "HAProxy class %s", name);
261 return 1;
262}
263
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100264/* This function check the number of arguments available in the
265 * stack. If the number of arguments available is not the same
266 * then <nb> an error is throwed.
267 */
268__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
269{
270 if (lua_gettop(L) == nb)
271 return;
272 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
273}
274
275/* Return true if the data in stack[<ud>] is an object of
276 * type <class_ref>.
277 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100278static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100279{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100280 if (!lua_getmetatable(L, ud))
281 return 0;
282
283 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
284 if (!lua_rawequal(L, -1, -2)) {
285 lua_pop(L, 2);
286 return 0;
287 }
288
289 lua_pop(L, 2);
290 return 1;
291}
292
293/* Return an object of the expected type, or throws an error. */
294__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
295{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100296 void *p;
297
298 /* Check if the stack entry is an array. */
299 if (!lua_istable(L, ud))
300 WILL_LJMP(luaL_argerror(L, ud, NULL));
301 /* Check if the metadata have the expected type. */
302 if (!hlua_metaistype(L, ud, class_ref))
303 WILL_LJMP(luaL_argerror(L, ud, NULL));
304 /* Push on the stack at the entry [0] of the table. */
305 lua_rawgeti(L, ud, 0);
306 /* Check if this entry is userdata. */
307 p = lua_touserdata(L, -1);
308 if (!p)
309 WILL_LJMP(luaL_argerror(L, ud, NULL));
310 /* Remove the entry returned by lua_rawgeti(). */
311 lua_pop(L, 1);
312 /* Return the associated struct. */
313 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100314}
315
316/* This fucntion push an error string prefixed by the file name
317 * and the line number where the error is encountered.
318 */
319static int hlua_pusherror(lua_State *L, const char *fmt, ...)
320{
321 va_list argp;
322 va_start(argp, fmt);
323 luaL_where(L, 1);
324 lua_pushvfstring(L, fmt, argp);
325 va_end(argp);
326 lua_concat(L, 2);
327 return 1;
328}
329
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100330/* This function register a new signal. "lua" is the current lua
331 * execution context. It contains a pointer to the associated task.
332 * "link" is a list head attached to an other task that must be wake
333 * the lua task if an event occurs. This is useful with external
334 * events like TCP I/O or sleep functions. This funcion allocate
335 * memory for the signal.
336 */
337static int hlua_com_new(struct hlua *lua, struct list *link)
338{
339 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
340 if (!com)
341 return 0;
342 LIST_ADDQ(&lua->com, &com->purge_me);
343 LIST_ADDQ(link, &com->wake_me);
344 com->task = lua->task;
345 return 1;
346}
347
348/* This function purge all the pending signals when the LUA execution
349 * is finished. This prevent than a coprocess try to wake a deleted
350 * task. This function remove the memory associated to the signal.
351 */
352static void hlua_com_purge(struct hlua *lua)
353{
354 struct hlua_com *com, *back;
355
356 /* Delete all pending communication signals. */
357 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
358 LIST_DEL(&com->purge_me);
359 LIST_DEL(&com->wake_me);
360 pool_free2(pool2_hlua_com, com);
361 }
362}
363
364/* This function sends signals. It wakes all the tasks attached
365 * to a list head, and remove the signal, and free the used
366 * memory.
367 */
368static void hlua_com_wake(struct list *wake)
369{
370 struct hlua_com *com, *back;
371
372 /* Wake task and delete all pending communication signals. */
373 list_for_each_entry_safe(com, back, wake, wake_me) {
374 LIST_DEL(&com->purge_me);
375 LIST_DEL(&com->wake_me);
376 task_wakeup(com->task, TASK_WOKEN_MSG);
377 pool_free2(pool2_hlua_com, com);
378 }
379}
380
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100381/* This functions is used with sample fetch and converters. It
382 * converts the HAProxy configuration argument in a lua stack
383 * values.
384 *
385 * It takes an array of "arg", and each entry of the array is
386 * converted and pushed in the LUA stack.
387 */
388static int hlua_arg2lua(lua_State *L, const struct arg *arg)
389{
390 switch (arg->type) {
391 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100392 case ARGT_TIME:
393 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100394 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100395 break;
396
397 case ARGT_STR:
398 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
399 break;
400
401 case ARGT_IPV4:
402 case ARGT_IPV6:
403 case ARGT_MSK4:
404 case ARGT_MSK6:
405 case ARGT_FE:
406 case ARGT_BE:
407 case ARGT_TAB:
408 case ARGT_SRV:
409 case ARGT_USR:
410 case ARGT_MAP:
411 default:
412 lua_pushnil(L);
413 break;
414 }
415 return 1;
416}
417
418/* This function take one entrie in an LUA stack at the index "ud",
419 * and try to convert it in an HAProxy argument entry. This is useful
420 * with sample fetch wrappers. The input arguments are gived to the
421 * lua wrapper and converted as arg list by thi function.
422 */
423static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
424{
425 switch (lua_type(L, ud)) {
426
427 case LUA_TNUMBER:
428 case LUA_TBOOLEAN:
429 arg->type = ARGT_SINT;
430 arg->data.sint = lua_tointeger(L, ud);
431 break;
432
433 case LUA_TSTRING:
434 arg->type = ARGT_STR;
435 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
436 break;
437
438 case LUA_TUSERDATA:
439 case LUA_TNIL:
440 case LUA_TTABLE:
441 case LUA_TFUNCTION:
442 case LUA_TTHREAD:
443 case LUA_TLIGHTUSERDATA:
444 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200445 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100446 break;
447 }
448 return 1;
449}
450
451/* the following functions are used to convert a struct sample
452 * in Lua type. This useful to convert the return of the
453 * fetchs or converters.
454 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100455static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100456{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200457 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100458 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100459 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200460 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100461 break;
462
463 case SMP_T_BIN:
464 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200465 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100466 break;
467
468 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200469 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100470 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
471 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
472 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
473 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
474 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
475 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
476 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
477 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
478 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200479 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100480 break;
481 default:
482 lua_pushnil(L);
483 break;
484 }
485 break;
486
487 case SMP_T_IPV4:
488 case SMP_T_IPV6:
489 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200490 if (sample_casts[smp->data.type][SMP_T_STR] &&
491 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200492 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100493 else
494 lua_pushnil(L);
495 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100496 default:
497 lua_pushnil(L);
498 break;
499 }
500 return 1;
501}
502
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100503/* the following functions are used to convert a struct sample
504 * in Lua strings. This is useful to convert the return of the
505 * fetchs or converters.
506 */
507static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
508{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200509 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100510
511 case SMP_T_BIN:
512 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200513 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100514 break;
515
516 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200517 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100518 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
519 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
520 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
521 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
522 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
523 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
524 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
525 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
526 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200527 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100528 break;
529 default:
530 lua_pushstring(L, "");
531 break;
532 }
533 break;
534
535 case SMP_T_SINT:
536 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100537 case SMP_T_IPV4:
538 case SMP_T_IPV6:
539 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200540 if (sample_casts[smp->data.type][SMP_T_STR] &&
541 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200542 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100543 else
544 lua_pushstring(L, "");
545 break;
546 default:
547 lua_pushstring(L, "");
548 break;
549 }
550 return 1;
551}
552
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100553/* the following functions are used to convert an Lua type in a
554 * struct sample. This is useful to provide data from a converter
555 * to the LUA code.
556 */
557static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
558{
559 switch (lua_type(L, ud)) {
560
561 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200562 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200563 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100564 break;
565
566
567 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200568 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200569 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100570 break;
571
572 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200573 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100574 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200575 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100576 break;
577
578 case LUA_TUSERDATA:
579 case LUA_TNIL:
580 case LUA_TTABLE:
581 case LUA_TFUNCTION:
582 case LUA_TTHREAD:
583 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200584 case LUA_TNONE:
585 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200586 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200587 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100588 break;
589 }
590 return 1;
591}
592
593/* This function check the "argp" builded by another conversion function
594 * is in accord with the expected argp defined by the "mask". The fucntion
595 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100596 *
597 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
598 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100599 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100600__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
601 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602{
603 int min_arg;
604 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100605 struct proxy *px;
606 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100607
608 idx = 0;
609 min_arg = ARGM(mask);
610 mask >>= ARGM_BITS;
611
612 while (1) {
613
614 /* Check oversize. */
615 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100616 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100617 }
618
619 /* Check for mandatory arguments. */
620 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100621 if (idx < min_arg) {
622
623 /* If miss other argument than the first one, we return an error. */
624 if (idx > 0)
625 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
626
627 /* If first argument have a certain type, some default values
628 * may be used. See the function smp_resolve_args().
629 */
630 switch (mask & ARGT_MASK) {
631
632 case ARGT_FE:
633 if (!(p->cap & PR_CAP_FE))
634 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
635 argp[idx].data.prx = p;
636 argp[idx].type = ARGT_FE;
637 argp[idx+1].type = ARGT_STOP;
638 break;
639
640 case ARGT_BE:
641 if (!(p->cap & PR_CAP_BE))
642 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
643 argp[idx].data.prx = p;
644 argp[idx].type = ARGT_BE;
645 argp[idx+1].type = ARGT_STOP;
646 break;
647
648 case ARGT_TAB:
649 argp[idx].data.prx = p;
650 argp[idx].type = ARGT_TAB;
651 argp[idx+1].type = ARGT_STOP;
652 break;
653
654 default:
655 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
656 break;
657 }
658 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100659 return 0;
660 }
661
662 /* Check for exceed the number of requiered argument. */
663 if ((mask & ARGT_MASK) == ARGT_STOP &&
664 argp[idx].type != ARGT_STOP) {
665 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
666 }
667
668 if ((mask & ARGT_MASK) == ARGT_STOP &&
669 argp[idx].type == ARGT_STOP) {
670 return 0;
671 }
672
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100673 /* Convert some argument types. */
674 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100675 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100676 if (argp[idx].type != ARGT_SINT)
677 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
678 argp[idx].type = ARGT_SINT;
679 break;
680
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100681 case ARGT_TIME:
682 if (argp[idx].type != ARGT_SINT)
683 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200684 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100685 break;
686
687 case ARGT_SIZE:
688 if (argp[idx].type != ARGT_SINT)
689 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200690 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100691 break;
692
693 case ARGT_FE:
694 if (argp[idx].type != ARGT_STR)
695 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
696 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
697 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200698 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100699 if (!argp[idx].data.prx)
700 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
701 argp[idx].type = ARGT_FE;
702 break;
703
704 case ARGT_BE:
705 if (argp[idx].type != ARGT_STR)
706 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
707 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
708 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200709 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100710 if (!argp[idx].data.prx)
711 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
712 argp[idx].type = ARGT_BE;
713 break;
714
715 case ARGT_TAB:
716 if (argp[idx].type != ARGT_STR)
717 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
718 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
719 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200720 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100721 if (!argp[idx].data.prx)
722 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
723 argp[idx].type = ARGT_TAB;
724 break;
725
726 case ARGT_SRV:
727 if (argp[idx].type != ARGT_STR)
728 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
729 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
730 trash.str[argp[idx].data.str.len] = 0;
731 sname = strrchr(trash.str, '/');
732 if (sname) {
733 *sname++ = '\0';
734 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200735 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100736 if (!px)
737 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
738 }
739 else {
740 sname = trash.str;
741 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100742 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100743 argp[idx].data.srv = findserver(px, sname);
744 if (!argp[idx].data.srv)
745 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
746 argp[idx].type = ARGT_SRV;
747 break;
748
749 case ARGT_IPV4:
750 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
751 trash.str[argp[idx].data.str.len] = 0;
752 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
753 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
754 argp[idx].type = ARGT_IPV4;
755 break;
756
757 case ARGT_MSK4:
758 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
759 trash.str[argp[idx].data.str.len] = 0;
760 if (!str2mask(trash.str, &argp[idx].data.ipv4))
761 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
762 argp[idx].type = ARGT_MSK4;
763 break;
764
765 case ARGT_IPV6:
766 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
767 trash.str[argp[idx].data.str.len] = 0;
768 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
769 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
770 argp[idx].type = ARGT_IPV6;
771 break;
772
773 case ARGT_MSK6:
774 case ARGT_MAP:
775 case ARGT_REG:
776 case ARGT_USR:
777 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100778 break;
779 }
780
781 /* Check for type of argument. */
782 if ((mask & ARGT_MASK) != argp[idx].type) {
783 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
784 arg_type_names[(mask & ARGT_MASK)],
785 arg_type_names[argp[idx].type & ARGT_MASK]);
786 WILL_LJMP(luaL_argerror(L, first + idx, msg));
787 }
788
789 /* Next argument. */
790 mask >>= ARGT_BITS;
791 idx++;
792 }
793}
794
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100795/*
796 * The following functions are used to make correspondance between the the
797 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100798 *
799 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100800 * - hlua_sethlua : create the association between hlua context and lua_state.
801 */
802static inline struct hlua *hlua_gethlua(lua_State *L)
803{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100804 struct hlua **hlua = lua_getextraspace(L);
805 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100806}
807static inline void hlua_sethlua(struct hlua *hlua)
808{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100809 struct hlua **hlua_store = lua_getextraspace(hlua->T);
810 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100811}
812
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100813/* This function is used to send logs. It try to send on screen (stderr)
814 * and on the default syslog server.
815 */
816static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
817{
818 struct tm tm;
819 char *p;
820
821 /* Cleanup the log message. */
822 p = trash.str;
823 for (; *msg != '\0'; msg++, p++) {
Thierry FOURNIERccf00632015-09-16 12:47:03 +0200824 if (p >= trash.str + trash.size - 1) {
825 /* Break the message if exceed the buffer size. */
826 *(p-4) = ' ';
827 *(p-3) = '.';
828 *(p-2) = '.';
829 *(p-1) = '.';
830 break;
831 }
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100832 if (isprint(*msg))
833 *p = *msg;
834 else
835 *p = '.';
836 }
837 *p = '\0';
838
Thierry FOURNIER5554e292015-09-09 11:21:37 +0200839 send_log(px, level, "%s\n", trash.str);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100840 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200841 get_localtime(date.tv_sec, &tm);
842 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100843 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
844 (int)getpid(), trash.str);
845 fflush(stderr);
846 }
847}
848
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100849/* This function just ensure that the yield will be always
850 * returned with a timeout and permit to set some flags
851 */
852__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100853 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100854{
855 struct hlua *hlua = hlua_gethlua(L);
856
857 /* Set the wake timeout. If timeout is required, we set
858 * the expiration time.
859 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100860 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100861
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100862 hlua->flags |= flags;
863
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100864 /* Process the yield. */
865 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
866}
867
Willy Tarreau87b09662015-04-03 00:22:06 +0200868/* This function initialises the Lua environment stored in the stream.
869 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100870 * an LUA coroutine. It can not be use to crete the main LUA context.
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200871 *
872 * This function is particular. it initialises a new Lua thread. If the
873 * initialisation fails (example: out of memory error), the lua function
874 * throws an error (longjmp).
875 *
876 * This function manipulates two Lua stack: the main and the thread. Only
877 * the main stack can fail. The thread is not manipulated. This function
878 * MUST NOT manipulate the created thread stack state, because is not
879 * proctected agains error throwed by the thread stack.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100880 */
881int hlua_ctx_init(struct hlua *lua, struct task *task)
882{
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200883 if (!SET_SAFE_LJMP(gL.T)) {
884 lua->Tref = LUA_REFNIL;
885 return 0;
886 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100887 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100888 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100889 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100890 lua->T = lua_newthread(gL.T);
891 if (!lua->T) {
892 lua->Tref = LUA_REFNIL;
893 return 0;
894 }
895 hlua_sethlua(lua);
896 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
897 lua->task = task;
Thierry FOURNIERbabae282015-09-17 11:36:37 +0200898 RESET_SAFE_LJMP(gL.T);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100899 return 1;
900}
901
Willy Tarreau87b09662015-04-03 00:22:06 +0200902/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100903 * is destroyed. The destroy also the memory context. The struct "lua"
904 * is not freed.
905 */
906void hlua_ctx_destroy(struct hlua *lua)
907{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100908 if (!lua->T)
909 return;
910
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100911 /* Purge all the pending signals. */
912 hlua_com_purge(lua);
913
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100914 /* The thread is garbage collected by Lua. */
915 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
916 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
Thierry FOURNIERa7b536b2015-09-21 22:50:24 +0200917 lua->T = NULL;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100918}
919
920/* This function is used to restore the Lua context when a coroutine
921 * fails. This function copy the common memory between old coroutine
922 * and the new coroutine. The old coroutine is destroyed, and its
923 * replaced by the new coroutine.
924 * If the flag "keep_msg" is set, the last entry of the old is assumed
925 * as string error message and it is copied in the new stack.
926 */
927static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
928{
929 lua_State *T;
930 int new_ref;
931
932 /* Renew the main LUA stack doesn't have sense. */
933 if (lua == &gL)
934 return 0;
935
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100936 /* New Lua coroutine. */
937 T = lua_newthread(gL.T);
938 if (!T)
939 return 0;
940
941 /* Copy last error message. */
942 if (keep_msg)
943 lua_xmove(lua->T, T, 1);
944
945 /* Copy data between the coroutines. */
946 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
947 lua_xmove(lua->T, T, 1);
948 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
949
950 /* Destroy old data. */
951 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
952
953 /* The thread is garbage collected by Lua. */
954 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
955
956 /* Fill the struct with the new coroutine values. */
957 lua->Mref = new_ref;
958 lua->T = T;
959 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
960
961 /* Set context. */
962 hlua_sethlua(lua);
963
964 return 1;
965}
966
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100967void hlua_hook(lua_State *L, lua_Debug *ar)
968{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100969 struct hlua *hlua = hlua_gethlua(L);
970
971 /* Lua cannot yield when its returning from a function,
972 * so, we can fix the interrupt hook to 1 instruction,
973 * expecting that the function is finnished.
974 */
975 if (lua_gethookmask(L) & LUA_MASKRET) {
976 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
977 return;
978 }
979
980 /* restore the interrupt condition. */
981 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
982
983 /* If we interrupt the Lua processing in yieldable state, we yield.
984 * If the state is not yieldable, trying yield causes an error.
985 */
986 if (lua_isyieldable(L))
987 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
988
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100989 /* If we cannot yield, update the clock and check the timeout. */
990 tv_update_date(0, 1);
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100991 if (tick_is_expired(hlua->expire, now_ms)) {
992 lua_pushfstring(L, "execution timeout");
993 WILL_LJMP(lua_error(L));
994 }
995
996 /* Try to interrupt the process at the end of the current
997 * unyieldable function.
998 */
999 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001000}
1001
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001002/* This function start or resumes the Lua stack execution. If the flag
1003 * "yield_allowed" if no set and the LUA stack execution returns a yield
1004 * The function return an error.
1005 *
1006 * The function can returns 4 values:
1007 * - HLUA_E_OK : The execution is terminated without any errors.
1008 * - HLUA_E_AGAIN : The execution must continue at the next associated
1009 * task wakeup.
1010 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
1011 * the top of the stack.
1012 * - HLUA_E_ERR : An error has occured without error message.
1013 *
1014 * If an error occured, the stack is renewed and it is ready to run new
1015 * LUA code.
1016 */
1017static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
1018{
1019 int ret;
1020 const char *msg;
1021
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001022 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001023
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001024 /* If we want to resume the task, then check first the execution timeout.
1025 * if it is reached, we can interrupt the Lua processing.
1026 */
1027 if (tick_is_expired(lua->expire, now_ms))
1028 goto timeout_reached;
1029
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001030resume_execution:
1031
1032 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
1033 * instructions. it is used for preventing infinite loops.
1034 */
1035 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
1036
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +01001037 /* Remove all flags except the running flags. */
1038 lua->flags = HLUA_RUN;
1039
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001040 /* Call the function. */
1041 ret = lua_resume(lua->T, gL.T, lua->nargs);
1042 switch (ret) {
1043
1044 case LUA_OK:
1045 ret = HLUA_E_OK;
1046 break;
1047
1048 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001049 /* Check if the execution timeout is expired. It it is the case, we
1050 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001051 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001052 if (tick_is_expired(lua->expire, now_ms)) {
1053
1054timeout_reached:
1055
1056 lua_settop(lua->T, 0); /* Empty the stack. */
1057 if (!lua_checkstack(lua->T, 1)) {
1058 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001059 break;
1060 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +01001061 lua_pushfstring(lua->T, "execution timeout");
1062 ret = HLUA_E_ERRMSG;
1063 break;
1064 }
1065 /* Process the forced yield. if the general yield is not allowed or
1066 * if no task were associated this the current Lua execution
1067 * coroutine, we resume the execution. Else we want to return in the
1068 * scheduler and we want to be waked up again, to continue the
1069 * current Lua execution. So we schedule our own task.
1070 */
1071 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001072 if (!yield_allowed || !lua->task)
1073 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001074 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01001075 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001076 if (!yield_allowed) {
1077 lua_settop(lua->T, 0); /* Empty the stack. */
1078 if (!lua_checkstack(lua->T, 1)) {
1079 ret = HLUA_E_ERR;
1080 break;
1081 }
1082 lua_pushfstring(lua->T, "yield not allowed");
1083 ret = HLUA_E_ERRMSG;
1084 break;
1085 }
1086 ret = HLUA_E_AGAIN;
1087 break;
1088
1089 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001090
1091 /* Special exit case. The traditionnal exit is returned as an error
1092 * because the errors ares the only one mean to return immediately
1093 * from and lua execution.
1094 */
1095 if (lua->flags & HLUA_EXIT) {
1096 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001097 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001098 break;
1099 }
1100
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001101 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001102 if (!lua_checkstack(lua->T, 1)) {
1103 ret = HLUA_E_ERR;
1104 break;
1105 }
1106 msg = lua_tostring(lua->T, -1);
1107 lua_settop(lua->T, 0); /* Empty the stack. */
1108 lua_pop(lua->T, 1);
1109 if (msg)
1110 lua_pushfstring(lua->T, "runtime error: %s", msg);
1111 else
1112 lua_pushfstring(lua->T, "unknown runtime error");
1113 ret = HLUA_E_ERRMSG;
1114 break;
1115
1116 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001117 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001118 lua_settop(lua->T, 0); /* Empty the stack. */
1119 if (!lua_checkstack(lua->T, 1)) {
1120 ret = HLUA_E_ERR;
1121 break;
1122 }
1123 lua_pushfstring(lua->T, "out of memory error");
1124 ret = HLUA_E_ERRMSG;
1125 break;
1126
1127 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001128 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001129 if (!lua_checkstack(lua->T, 1)) {
1130 ret = HLUA_E_ERR;
1131 break;
1132 }
1133 msg = lua_tostring(lua->T, -1);
1134 lua_settop(lua->T, 0); /* Empty the stack. */
1135 lua_pop(lua->T, 1);
1136 if (msg)
1137 lua_pushfstring(lua->T, "message handler error: %s", msg);
1138 else
1139 lua_pushfstring(lua->T, "message handler error");
1140 ret = HLUA_E_ERRMSG;
1141 break;
1142
1143 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001144 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001145 lua_settop(lua->T, 0); /* Empty the stack. */
1146 if (!lua_checkstack(lua->T, 1)) {
1147 ret = HLUA_E_ERR;
1148 break;
1149 }
1150 lua_pushfstring(lua->T, "unknonwn error");
1151 ret = HLUA_E_ERRMSG;
1152 break;
1153 }
1154
1155 switch (ret) {
1156 case HLUA_E_AGAIN:
1157 break;
1158
1159 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001160 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001161 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001162 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001163 break;
1164
1165 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001166 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001167 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001168 hlua_ctx_renew(lua, 0);
1169 break;
1170
1171 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001172 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001173 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001174 break;
1175 }
1176
1177 return ret;
1178}
1179
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001180/* This function exit the current code. */
1181__LJMP static int hlua_done(lua_State *L)
1182{
1183 struct hlua *hlua = hlua_gethlua(L);
1184
1185 hlua->flags |= HLUA_EXIT;
1186 WILL_LJMP(lua_error(L));
1187
1188 return 0;
1189}
1190
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001191/* This function is an LUA binding. It provides a function
1192 * for deleting ACL from a referenced ACL file.
1193 */
1194__LJMP static int hlua_del_acl(lua_State *L)
1195{
1196 const char *name;
1197 const char *key;
1198 struct pat_ref *ref;
1199
1200 MAY_LJMP(check_args(L, 2, "del_acl"));
1201
1202 name = MAY_LJMP(luaL_checkstring(L, 1));
1203 key = MAY_LJMP(luaL_checkstring(L, 2));
1204
1205 ref = pat_ref_lookup(name);
1206 if (!ref)
1207 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1208
1209 pat_ref_delete(ref, key);
1210 return 0;
1211}
1212
1213/* This function is an LUA binding. It provides a function
1214 * for deleting map entry from a referenced map file.
1215 */
1216static int hlua_del_map(lua_State *L)
1217{
1218 const char *name;
1219 const char *key;
1220 struct pat_ref *ref;
1221
1222 MAY_LJMP(check_args(L, 2, "del_map"));
1223
1224 name = MAY_LJMP(luaL_checkstring(L, 1));
1225 key = MAY_LJMP(luaL_checkstring(L, 2));
1226
1227 ref = pat_ref_lookup(name);
1228 if (!ref)
1229 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1230
1231 pat_ref_delete(ref, key);
1232 return 0;
1233}
1234
1235/* This function is an LUA binding. It provides a function
1236 * for adding ACL pattern from a referenced ACL file.
1237 */
1238static int hlua_add_acl(lua_State *L)
1239{
1240 const char *name;
1241 const char *key;
1242 struct pat_ref *ref;
1243
1244 MAY_LJMP(check_args(L, 2, "add_acl"));
1245
1246 name = MAY_LJMP(luaL_checkstring(L, 1));
1247 key = MAY_LJMP(luaL_checkstring(L, 2));
1248
1249 ref = pat_ref_lookup(name);
1250 if (!ref)
1251 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1252
1253 if (pat_ref_find_elt(ref, key) == NULL)
1254 pat_ref_add(ref, key, NULL, NULL);
1255 return 0;
1256}
1257
1258/* This function is an LUA binding. It provides a function
1259 * for setting map pattern and sample from a referenced map
1260 * file.
1261 */
1262static int hlua_set_map(lua_State *L)
1263{
1264 const char *name;
1265 const char *key;
1266 const char *value;
1267 struct pat_ref *ref;
1268
1269 MAY_LJMP(check_args(L, 3, "set_map"));
1270
1271 name = MAY_LJMP(luaL_checkstring(L, 1));
1272 key = MAY_LJMP(luaL_checkstring(L, 2));
1273 value = MAY_LJMP(luaL_checkstring(L, 3));
1274
1275 ref = pat_ref_lookup(name);
1276 if (!ref)
1277 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1278
1279 if (pat_ref_find_elt(ref, key) != NULL)
1280 pat_ref_set(ref, key, value, NULL);
1281 else
1282 pat_ref_add(ref, key, value, NULL);
1283 return 0;
1284}
1285
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001286/* A class is a lot of memory that contain data. This data can be a table,
1287 * an integer or user data. This data is associated with a metatable. This
1288 * metatable have an original version registred in the global context with
1289 * the name of the object (_G[<name>] = <metable> ).
1290 *
1291 * A metable is a table that modify the standard behavior of a standard
1292 * access to the associated data. The entries of this new metatable are
1293 * defined as is:
1294 *
1295 * http://lua-users.org/wiki/MetatableEvents
1296 *
1297 * __index
1298 *
1299 * we access an absent field in a table, the result is nil. This is
1300 * true, but it is not the whole truth. Actually, such access triggers
1301 * the interpreter to look for an __index metamethod: If there is no
1302 * such method, as usually happens, then the access results in nil;
1303 * otherwise, the metamethod will provide the result.
1304 *
1305 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1306 * the key does not appear in the table, but the metatable has an __index
1307 * property:
1308 *
1309 * - if the value is a function, the function is called, passing in the
1310 * table and the key; the return value of that function is returned as
1311 * the result.
1312 *
1313 * - if the value is another table, the value of the key in that table is
1314 * asked for and returned (and if it doesn't exist in that table, but that
1315 * table's metatable has an __index property, then it continues on up)
1316 *
1317 * - Use "rawget(myTable,key)" to skip this metamethod.
1318 *
1319 * http://www.lua.org/pil/13.4.1.html
1320 *
1321 * __newindex
1322 *
1323 * Like __index, but control property assignment.
1324 *
1325 * __mode - Control weak references. A string value with one or both
1326 * of the characters 'k' and 'v' which specifies that the the
1327 * keys and/or values in the table are weak references.
1328 *
1329 * __call - Treat a table like a function. When a table is followed by
1330 * parenthesis such as "myTable( 'foo' )" and the metatable has
1331 * a __call key pointing to a function, that function is invoked
1332 * (passing any specified arguments) and the return value is
1333 * returned.
1334 *
1335 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1336 * called, if the metatable for myTable has a __metatable
1337 * key, the value of that key is returned instead of the
1338 * actual metatable.
1339 *
1340 * __tostring - Control string representation. When the builtin
1341 * "tostring( myTable )" function is called, if the metatable
1342 * for myTable has a __tostring property set to a function,
1343 * that function is invoked (passing myTable to it) and the
1344 * return value is used as the string representation.
1345 *
1346 * __len - Control table length. When the table length is requested using
1347 * the length operator ( '#' ), if the metatable for myTable has
1348 * a __len key pointing to a function, that function is invoked
1349 * (passing myTable to it) and the return value used as the value
1350 * of "#myTable".
1351 *
1352 * __gc - Userdata finalizer code. When userdata is set to be garbage
1353 * collected, if the metatable has a __gc field pointing to a
1354 * function, that function is first invoked, passing the userdata
1355 * to it. The __gc metamethod is not called for tables.
1356 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1357 *
1358 * Special metamethods for redefining standard operators:
1359 * http://www.lua.org/pil/13.1.html
1360 *
1361 * __add "+"
1362 * __sub "-"
1363 * __mul "*"
1364 * __div "/"
1365 * __unm "!"
1366 * __pow "^"
1367 * __concat ".."
1368 *
1369 * Special methods for redfining standar relations
1370 * http://www.lua.org/pil/13.2.html
1371 *
1372 * __eq "=="
1373 * __lt "<"
1374 * __le "<="
1375 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001376
1377/*
1378 *
1379 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001380 * Class Map
1381 *
1382 *
1383 */
1384
1385/* Returns a struct hlua_map if the stack entry "ud" is
1386 * a class session, otherwise it throws an error.
1387 */
1388__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1389{
1390 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1391}
1392
1393/* This function is the map constructor. It don't need
1394 * the class Map object. It creates and return a new Map
1395 * object. It must be called only during "body" or "init"
1396 * context because it process some filesystem accesses.
1397 */
1398__LJMP static int hlua_map_new(struct lua_State *L)
1399{
1400 const char *fn;
1401 int match = PAT_MATCH_STR;
1402 struct sample_conv conv;
1403 const char *file = "";
1404 int line = 0;
1405 lua_Debug ar;
1406 char *err = NULL;
1407 struct arg args[2];
1408
1409 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1410 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1411
1412 fn = MAY_LJMP(luaL_checkstring(L, 1));
1413
1414 if (lua_gettop(L) >= 2) {
1415 match = MAY_LJMP(luaL_checkinteger(L, 2));
1416 if (match < 0 || match >= PAT_MATCH_NUM)
1417 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1418 }
1419
1420 /* Get Lua filename and line number. */
1421 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1422 lua_getinfo(L, "Sl", &ar); /* get info about it */
1423 if (ar.currentline > 0) { /* is there info? */
1424 file = ar.short_src;
1425 line = ar.currentline;
1426 }
1427 }
1428
1429 /* fill fake sample_conv struct. */
1430 conv.kw = ""; /* unused. */
1431 conv.process = NULL; /* unused. */
1432 conv.arg_mask = 0; /* unused. */
1433 conv.val_args = NULL; /* unused. */
1434 conv.out_type = SMP_T_STR;
1435 conv.private = (void *)(long)match;
1436 switch (match) {
1437 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1438 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1439 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1440 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1441 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1442 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1443 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001444 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001445 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1446 default:
1447 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1448 }
1449
1450 /* fill fake args. */
1451 args[0].type = ARGT_STR;
1452 args[0].data.str.str = (char *)fn;
1453 args[1].type = ARGT_STOP;
1454
1455 /* load the map. */
1456 if (!sample_load_map(args, &conv, file, line, &err)) {
1457 /* error case: we cant use luaL_error because we must
1458 * free the err variable.
1459 */
1460 luaL_where(L, 1);
1461 lua_pushfstring(L, "'new': %s.", err);
1462 lua_concat(L, 2);
1463 free(err);
1464 WILL_LJMP(lua_error(L));
1465 }
1466
1467 /* create the lua object. */
1468 lua_newtable(L);
1469 lua_pushlightuserdata(L, args[0].data.map);
1470 lua_rawseti(L, -2, 0);
1471
1472 /* Pop a class Map metatable and affect it to the userdata. */
1473 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1474 lua_setmetatable(L, -2);
1475
1476
1477 return 1;
1478}
1479
1480__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1481{
1482 struct map_descriptor *desc;
1483 struct pattern *pat;
1484 struct sample smp;
1485
1486 MAY_LJMP(check_args(L, 2, "lookup"));
1487 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001488 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001489 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001490 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001491 }
1492 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001493 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001494 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001495 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 +02001496 }
1497
1498 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001499 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001500 if (str)
1501 lua_pushstring(L, "");
1502 else
1503 lua_pushnil(L);
1504 return 1;
1505 }
1506
1507 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001508 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001509 return 1;
1510}
1511
1512__LJMP static int hlua_map_lookup(struct lua_State *L)
1513{
1514 return _hlua_map_lookup(L, 0);
1515}
1516
1517__LJMP static int hlua_map_slookup(struct lua_State *L)
1518{
1519 return _hlua_map_lookup(L, 1);
1520}
1521
1522/*
1523 *
1524 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001525 * Class Socket
1526 *
1527 *
1528 */
1529
1530__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1531{
1532 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1533}
1534
1535/* This function is the handler called for each I/O on the established
1536 * connection. It is used for notify space avalaible to send or data
1537 * received.
1538 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001539static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001540{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001541 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001542 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001543
Willy Tarreau87b09662015-04-03 00:22:06 +02001544 /* Wakeup the main stream if the client connection is closed. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001545 if (!c || channel_output_closed(si_ic(si)) || channel_input_closed(si_oc(si))) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001546 if (appctx->ctx.hlua.socket) {
1547 appctx->ctx.hlua.socket->s = NULL;
1548 appctx->ctx.hlua.socket = NULL;
1549 }
1550 si_shutw(si);
1551 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001552 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001553 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1554 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001555 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001556 }
1557
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. */
1568 appctx->ctx.hlua.connected = 1;
1569
1570 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001571 if (channel_may_recv(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001572 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1573
1574 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001575 if (channel_is_empty(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001576 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1577}
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. */
1586 if (appctx->ctx.hlua.socket)
1587 appctx->ctx.hlua.socket->s = NULL;
1588
1589 /* Wake all the task waiting for me. */
1590 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1591 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1592}
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;
1615 appctx->ctx.hlua.socket = NULL;
1616
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);
1637 appctx->ctx.hlua.socket = NULL;
1638 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 Tarreauaa977ba2015-09-25 11:45:06 +02001746 si_applet_wake_cb(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001747
1748 /* If the pattern reclaim to read all the data
1749 * in the connection, got out.
1750 */
1751 if (wanted == HLSR_READ_ALL)
1752 goto connection_empty;
1753 else if (wanted >= 0 && len < wanted)
1754 goto connection_empty;
1755
1756 /* Return result. */
1757 luaL_pushresult(&socket->b);
1758 return 1;
1759
1760connection_closed:
1761
1762 /* If the buffer containds data. */
1763 if (socket->b.n > 0) {
1764 luaL_pushresult(&socket->b);
1765 return 1;
1766 }
1767 lua_pushnil(L);
1768 lua_pushstring(L, "connection closed.");
1769 return 2;
1770
1771connection_empty:
1772
1773 appctx = objt_appctx(socket->s->si[0].end);
1774 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1775 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001776 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001777 return 0;
1778}
1779
1780/* This Lus function gets two parameters. The first one can be string
1781 * or a number. If the string is "*l", the user require one line. If
1782 * the string is "*a", the user require all the content of the stream.
1783 * If the value is a number, the user require a number of bytes equal
1784 * to the value. The default value is "*l" (a line).
1785 *
1786 * This paraeter with a variable type is converted in integer. This
1787 * integer takes this values:
1788 * -1 : read a line
1789 * -2 : read all the stream
1790 * >0 : amount if bytes.
1791 *
1792 * The second parameter is optinal. It contains a string that must be
1793 * concatenated with the read data.
1794 */
1795__LJMP static int hlua_socket_receive(struct lua_State *L)
1796{
1797 int wanted = HLSR_READ_LINE;
1798 const char *pattern;
1799 int type;
1800 char *error;
1801 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001802 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001803
1804 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1805 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1806
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001807 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001808
1809 /* check for pattern. */
1810 if (lua_gettop(L) >= 2) {
1811 type = lua_type(L, 2);
1812 if (type == LUA_TSTRING) {
1813 pattern = lua_tostring(L, 2);
1814 if (strcmp(pattern, "*a") == 0)
1815 wanted = HLSR_READ_ALL;
1816 else if (strcmp(pattern, "*l") == 0)
1817 wanted = HLSR_READ_LINE;
1818 else {
1819 wanted = strtoll(pattern, &error, 10);
1820 if (*error != '\0')
1821 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1822 }
1823 }
1824 else if (type == LUA_TNUMBER) {
1825 wanted = lua_tointeger(L, 2);
1826 if (wanted < 0)
1827 WILL_LJMP(luaL_error(L, "Unsupported size."));
1828 }
1829 }
1830
1831 /* Set pattern. */
1832 lua_pushinteger(L, wanted);
1833 lua_replace(L, 2);
1834
1835 /* init bufffer, and fiil it wih prefix. */
1836 luaL_buffinit(L, &socket->b);
1837
1838 /* Check prefix. */
1839 if (lua_gettop(L) >= 3) {
1840 if (lua_type(L, 3) != LUA_TSTRING)
1841 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1842 pattern = lua_tolstring(L, 3, &len);
1843 luaL_addlstring(&socket->b, pattern, len);
1844 }
1845
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001846 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001847}
1848
1849/* Write the Lua input string in the output buffer.
1850 * This fucntion returns a yield if no space are available.
1851 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001852static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001853{
1854 struct hlua_socket *socket;
1855 struct hlua *hlua = hlua_gethlua(L);
1856 struct appctx *appctx;
1857 size_t buf_len;
1858 const char *buf;
1859 int len;
1860 int send_len;
1861 int sent;
1862
1863 /* Check if this lua stack is schedulable. */
1864 if (!hlua || !hlua->task)
1865 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1866 "'frontend', 'backend' or 'task'"));
1867
1868 /* Get object */
1869 socket = MAY_LJMP(hlua_checksocket(L, 1));
1870 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001871 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001872
1873 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001874 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001875 lua_pushinteger(L, -1);
1876 return 1;
1877 }
1878
1879 /* Update the input buffer data. */
1880 buf += sent;
1881 send_len = buf_len - sent;
1882
1883 /* All the data are sent. */
1884 if (sent >= buf_len)
1885 return 1; /* Implicitly return the length sent. */
1886
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001887 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1888 * the request buffer if its not required.
1889 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001890 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001891 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001892 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001893 goto hlua_socket_write_yield_return;
1894 }
1895 }
1896
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001897 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001898 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001899 if (len <= 0)
1900 goto hlua_socket_write_yield_return;
1901
1902 /* send data */
1903 if (len < send_len)
1904 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001905 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001906
1907 /* "Not enough space" (-1), "Buffer too little to contain
1908 * the data" (-2) are not expected because the available length
1909 * is tested.
1910 * Other unknown error are also not expected.
1911 */
1912 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001913 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001914 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001915
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001916 MAY_LJMP(hlua_socket_close(L));
1917 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001918 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001919 return 1;
1920 }
1921
1922 /* update buffers. */
Willy Tarreauaa977ba2015-09-25 11:45:06 +02001923 si_applet_wake_cb(&socket->s->si[0]);
Willy Tarreau94aa6172015-03-13 14:19:06 +01001924 socket->s->req.rex = TICK_ETERNITY;
1925 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001926
1927 /* Update length sent. */
1928 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001929 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001930
1931 /* All the data buffer is sent ? */
1932 if (sent + len >= buf_len)
1933 return 1;
1934
1935hlua_socket_write_yield_return:
1936 appctx = objt_appctx(socket->s->si[0].end);
1937 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1938 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001939 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001940 return 0;
1941}
1942
1943/* This function initiate the send of data. It just check the input
1944 * parameters and push an integer in the Lua stack that contain the
1945 * amount of data writed in the buffer. This is used by the function
1946 * "hlua_socket_write_yield" that can yield.
1947 *
1948 * The Lua function gets between 3 and 4 parameters. The first one is
1949 * the associated object. The second is a string buffer. The third is
1950 * a facultative integer that represents where is the buffer position
1951 * of the start of the data that can send. The first byte is the
1952 * position "1". The default value is "1". The fourth argument is a
1953 * facultative integer that represents where is the buffer position
1954 * of the end of the data that can send. The default is the last byte.
1955 */
1956static int hlua_socket_send(struct lua_State *L)
1957{
1958 int i;
1959 int j;
1960 const char *buf;
1961 size_t buf_len;
1962
1963 /* Check number of arguments. */
1964 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1965 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1966
1967 /* Get the string. */
1968 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1969
1970 /* Get and check j. */
1971 if (lua_gettop(L) == 4) {
1972 j = MAY_LJMP(luaL_checkinteger(L, 4));
1973 if (j < 0)
1974 j = buf_len + j + 1;
1975 if (j > buf_len)
1976 j = buf_len + 1;
1977 lua_pop(L, 1);
1978 }
1979 else
1980 j = buf_len;
1981
1982 /* Get and check i. */
1983 if (lua_gettop(L) == 3) {
1984 i = MAY_LJMP(luaL_checkinteger(L, 3));
1985 if (i < 0)
1986 i = buf_len + i + 1;
1987 if (i > buf_len)
1988 i = buf_len + 1;
1989 lua_pop(L, 1);
1990 } else
1991 i = 1;
1992
1993 /* Check bth i and j. */
1994 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001995 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001996 return 1;
1997 }
1998 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001999 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002000 return 1;
2001 }
2002 if (i == 0)
2003 i = 1;
2004 if (j == 0)
2005 j = 1;
2006
2007 /* Pop the string. */
2008 lua_pop(L, 1);
2009
2010 /* Update the buffer length. */
2011 buf += i - 1;
2012 buf_len = j - i + 1;
2013 lua_pushlstring(L, buf, buf_len);
2014
2015 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002016 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002017
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002018 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002019}
2020
Willy Tarreau22b0a682015-06-17 19:43:49 +02002021#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002022__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
2023{
2024 static char buffer[SOCKET_INFO_MAX_LEN];
2025 int ret;
2026 int len;
2027 char *p;
2028
2029 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
2030 if (ret <= 0) {
2031 lua_pushnil(L);
2032 return 1;
2033 }
2034
2035 if (ret == AF_UNIX) {
2036 lua_pushstring(L, buffer+1);
2037 return 1;
2038 }
2039 else if (ret == AF_INET6) {
2040 buffer[0] = '[';
2041 len = strlen(buffer);
2042 buffer[len] = ']';
2043 len++;
2044 buffer[len] = ':';
2045 len++;
2046 p = buffer;
2047 }
2048 else if (ret == AF_INET) {
2049 p = buffer + 1;
2050 len = strlen(p);
2051 p[len] = ':';
2052 len++;
2053 }
2054 else {
2055 lua_pushnil(L);
2056 return 1;
2057 }
2058
2059 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
2060 lua_pushnil(L);
2061 return 1;
2062 }
2063
2064 lua_pushstring(L, p);
2065 return 1;
2066}
2067
2068/* Returns information about the peer of the connection. */
2069__LJMP static int hlua_socket_getpeername(struct lua_State *L)
2070{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002071 struct hlua_socket *socket;
2072 struct connection *conn;
2073
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002074 MAY_LJMP(check_args(L, 1, "getpeername"));
2075
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002076 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002077
2078 /* Check if the tcp object is avalaible. */
2079 if (!socket->s) {
2080 lua_pushnil(L);
2081 return 1;
2082 }
2083
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002084 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002085 if (!conn) {
2086 lua_pushnil(L);
2087 return 1;
2088 }
2089
2090 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
2091 unsigned int salen = sizeof(conn->addr.to);
2092 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
2093 lua_pushnil(L);
2094 return 1;
2095 }
2096 conn->flags |= CO_FL_ADDR_TO_SET;
2097 }
2098
2099 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2100}
2101
2102/* Returns information about my connection side. */
2103static int hlua_socket_getsockname(struct lua_State *L)
2104{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002105 struct hlua_socket *socket;
2106 struct connection *conn;
2107
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002108 MAY_LJMP(check_args(L, 1, "getsockname"));
2109
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002110 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002111
2112 /* Check if the tcp object is avalaible. */
2113 if (!socket->s) {
2114 lua_pushnil(L);
2115 return 1;
2116 }
2117
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002118 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002119 if (!conn) {
2120 lua_pushnil(L);
2121 return 1;
2122 }
2123
2124 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2125 unsigned int salen = sizeof(conn->addr.from);
2126 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2127 lua_pushnil(L);
2128 return 1;
2129 }
2130 conn->flags |= CO_FL_ADDR_FROM_SET;
2131 }
2132
2133 return hlua_socket_info(L, &conn->addr.from);
2134}
2135
2136/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002137static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002138 .obj_type = OBJ_TYPE_APPLET,
2139 .name = "<LUA_TCP>",
2140 .fct = hlua_socket_handler,
2141 .release = hlua_socket_release,
2142};
2143
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002144__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002145{
2146 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2147 struct hlua *hlua = hlua_gethlua(L);
2148 struct appctx *appctx;
2149
2150 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002151 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002152 lua_pushnil(L);
2153 lua_pushstring(L, "Can't connect");
2154 return 2;
2155 }
2156
2157 appctx = objt_appctx(socket->s->si[0].end);
2158
2159 /* Check for connection established. */
2160 if (appctx->ctx.hlua.connected) {
2161 lua_pushinteger(L, 1);
2162 return 1;
2163 }
2164
2165 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2166 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002167 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002168 return 0;
2169}
2170
2171/* This function fail or initite the connection. */
2172__LJMP static int hlua_socket_connect(struct lua_State *L)
2173{
2174 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002175 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002176 const char *ip;
2177 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002178 struct hlua *hlua;
2179 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180
2181 MAY_LJMP(check_args(L, 3, "connect"));
2182
2183 /* Get args. */
2184 socket = MAY_LJMP(hlua_checksocket(L, 1));
2185 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002186 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002187
Willy Tarreau973a5422015-08-05 21:47:23 +02002188 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002189 if (!conn)
2190 WILL_LJMP(luaL_error(L, "connect: internal error"));
2191
2192 /* Parse ip address. */
2193 conn->addr.to.ss_family = AF_UNSPEC;
2194 if (!str2ip2(ip, &conn->addr.to, 0))
2195 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
2196
2197 /* Set port. */
2198 if (conn->addr.to.ss_family == AF_INET)
2199 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2200 else if (conn->addr.to.ss_family == AF_INET6)
2201 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2202
2203 /* it is important not to call the wakeup function directly but to
2204 * pass through task_wakeup(), because this one knows how to apply
2205 * priorities to tasks.
2206 */
2207 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
2208
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002209 hlua = hlua_gethlua(L);
2210 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002211
2212 /* inform the stream that we want to be notified whenever the
2213 * connection completes.
2214 */
2215 si_applet_cant_get(&socket->s->si[0]);
2216 si_applet_cant_put(&socket->s->si[0]);
2217
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002218 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2219 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002220 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002221
2222 return 0;
2223}
2224
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002225#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2227{
2228 struct hlua_socket *socket;
2229
2230 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2231 socket = MAY_LJMP(hlua_checksocket(L, 1));
2232 socket->s->target = &socket_ssl.obj_type;
2233 return MAY_LJMP(hlua_socket_connect(L));
2234}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002235#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236
2237__LJMP static int hlua_socket_setoption(struct lua_State *L)
2238{
2239 return 0;
2240}
2241
2242__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2243{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002244 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002245 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002246
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002247 MAY_LJMP(check_args(L, 2, "settimeout"));
2248
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002249 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002250 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002251
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002252 socket->s->req.rto = tmout;
2253 socket->s->req.wto = tmout;
2254 socket->s->res.rto = tmout;
2255 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002256
2257 return 0;
2258}
2259
2260__LJMP static int hlua_socket_new(lua_State *L)
2261{
2262 struct hlua_socket *socket;
2263 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002264 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002265 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002266 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002267
2268 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002269 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002270 hlua_pusherror(L, "socket: full stack");
2271 goto out_fail_conf;
2272 }
2273
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002274 /* Create the object: obj[0] = userdata. */
2275 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002276 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002277 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002278 memset(socket, 0, sizeof(*socket));
2279
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002280 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002281 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002282 hlua_pusherror(L, "socket: uninitialized pools.");
2283 goto out_fail_conf;
2284 }
2285
Willy Tarreau87b09662015-04-03 00:22:06 +02002286 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002287 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2288 lua_setmetatable(L, -2);
2289
Willy Tarreaud420a972015-04-06 00:39:18 +02002290 /* Create the applet context */
2291 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002292 if (!appctx) {
2293 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002294 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002295 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002296
Willy Tarreaud420a972015-04-06 00:39:18 +02002297 appctx->ctx.hlua.socket = socket;
2298 appctx->ctx.hlua.connected = 0;
2299 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2300 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002301
Willy Tarreaud420a972015-04-06 00:39:18 +02002302 /* Now create a session, task and stream for this applet */
2303 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2304 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002305 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002306 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002307 }
2308
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002309 task = task_new();
2310 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002311 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002312 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002313 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002314 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002315
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002316 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002317 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002318 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002319 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002320 }
2321
Willy Tarreaud420a972015-04-06 00:39:18 +02002322 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002323 socket->s = strm;
2324 strm->hlua.T = NULL;
2325 strm->hlua.Tref = LUA_REFNIL;
2326 strm->hlua.Mref = LUA_REFNIL;
2327 strm->hlua.nargs = 0;
2328 strm->hlua.flags = 0;
2329 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002330
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002331 /* Configure "right" stream interface. this "si" is used to connect
2332 * and retrieve data from the server. The connection is initialized
2333 * with the "struct server".
2334 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002335 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002336
2337 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002338 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2339 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002340
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002341 /* Update statistics counters. */
2342 socket_proxy.feconn++; /* beconn will be increased later */
2343 jobs++;
2344 totalconn++;
2345
2346 /* Return yield waiting for connection. */
2347 return 1;
2348
Willy Tarreaud420a972015-04-06 00:39:18 +02002349 out_fail_stream:
2350 task_free(task);
2351 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002352 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002353 out_fail_sess:
2354 appctx_free(appctx);
2355 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002356 WILL_LJMP(lua_error(L));
2357 return 0;
2358}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002359
2360/*
2361 *
2362 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002363 * Class Channel
2364 *
2365 *
2366 */
2367
2368/* Returns the struct hlua_channel join to the class channel in the
2369 * stack entry "ud" or throws an argument error.
2370 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002371__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002372{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002373 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002374}
2375
Willy Tarreau47860ed2015-03-10 14:07:50 +01002376/* Pushes the channel onto the top of the stack. If the stask does not have a
2377 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002378 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002379static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002380{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002381 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002382 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002383 return 0;
2384
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002385 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002386 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002387 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002388
2389 /* Pop a class sesison metatable and affect it to the userdata. */
2390 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2391 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002392 return 1;
2393}
2394
2395/* Duplicate all the data present in the input channel and put it
2396 * in a string LUA variables. Returns -1 and push a nil value in
2397 * the stack if the channel is closed and all the data are consumed,
2398 * returns 0 if no data are available, otherwise it returns the length
2399 * of the builded string.
2400 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002401static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002402{
2403 char *blk1;
2404 char *blk2;
2405 int len1;
2406 int len2;
2407 int ret;
2408 luaL_Buffer b;
2409
Willy Tarreau47860ed2015-03-10 14:07:50 +01002410 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002411 if (unlikely(ret == 0))
2412 return 0;
2413
2414 if (unlikely(ret < 0)) {
2415 lua_pushnil(L);
2416 return -1;
2417 }
2418
2419 luaL_buffinit(L, &b);
2420 luaL_addlstring(&b, blk1, len1);
2421 if (unlikely(ret == 2))
2422 luaL_addlstring(&b, blk2, len2);
2423 luaL_pushresult(&b);
2424
2425 if (unlikely(ret == 2))
2426 return len1 + len2;
2427 return len1;
2428}
2429
2430/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2431 * a yield. This function keep the data in the buffer.
2432 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002433__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002434{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002435 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002436
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002437 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2438
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002439 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002440 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002441 return 1;
2442}
2443
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002444/* Check arguments for the function "hlua_channel_dup_yield". */
2445__LJMP static int hlua_channel_dup(lua_State *L)
2446{
2447 MAY_LJMP(check_args(L, 1, "dup"));
2448 MAY_LJMP(hlua_checkchannel(L, 1));
2449 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2450}
2451
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002452/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2453 * a yield. This function consumes the data in the buffer. It returns
2454 * a string containing the data or a nil pointer if no data are available
2455 * and the channel is closed.
2456 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002457__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002458{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002459 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002460 int ret;
2461
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002462 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002463
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002464 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002465 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002466 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002467
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002468 if (unlikely(ret == -1))
2469 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002470
Willy Tarreau47860ed2015-03-10 14:07:50 +01002471 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002472 return 1;
2473}
2474
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002475/* Check arguments for the fucntion "hlua_channel_get_yield". */
2476__LJMP static int hlua_channel_get(lua_State *L)
2477{
2478 MAY_LJMP(check_args(L, 1, "get"));
2479 MAY_LJMP(hlua_checkchannel(L, 1));
2480 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2481}
2482
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002483/* This functions consumes and returns one line. If the channel is closed,
2484 * and the last data does not contains a final '\n', the data are returned
2485 * without the final '\n'. When no more data are avalaible, it returns nil
2486 * value.
2487 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002488__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002489{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002490 char *blk1;
2491 char *blk2;
2492 int len1;
2493 int len2;
2494 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002495 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002496 int ret;
2497 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002498
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002499 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2500
Willy Tarreau47860ed2015-03-10 14:07:50 +01002501 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002502 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002503 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002504
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002505 if (ret == -1) {
2506 lua_pushnil(L);
2507 return 1;
2508 }
2509
2510 luaL_buffinit(L, &b);
2511 luaL_addlstring(&b, blk1, len1);
2512 len = len1;
2513 if (unlikely(ret == 2)) {
2514 luaL_addlstring(&b, blk2, len2);
2515 len += len2;
2516 }
2517 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002518 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002519 return 1;
2520}
2521
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002522/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2523__LJMP static int hlua_channel_getline(lua_State *L)
2524{
2525 MAY_LJMP(check_args(L, 1, "getline"));
2526 MAY_LJMP(hlua_checkchannel(L, 1));
2527 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2528}
2529
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002530/* This function takes a string as input, and append it at the
2531 * input side of channel. If the data is too big, but a space
2532 * is probably available after sending some data, the function
2533 * yield. If the data is bigger than the buffer, or if the
2534 * channel is closed, it returns -1. otherwise, it returns the
2535 * amount of data writed.
2536 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002537__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002538{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002539 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002540 size_t len;
2541 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2542 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2543 int ret;
2544 int max;
2545
Willy Tarreau47860ed2015-03-10 14:07:50 +01002546 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002547 if (max > len - l)
2548 max = len - l;
2549
Willy Tarreau47860ed2015-03-10 14:07:50 +01002550 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002551 if (ret == -2 || ret == -3) {
2552 lua_pushinteger(L, -1);
2553 return 1;
2554 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002555 if (ret == -1) {
2556 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002557 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002558 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002559 l += ret;
2560 lua_pop(L, 1);
2561 lua_pushinteger(L, l);
2562
Willy Tarreau47860ed2015-03-10 14:07:50 +01002563 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2564 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002565 /* There are no space avalaible, and the output buffer is empty.
2566 * in this case, we cannot add more data, so we cannot yield,
2567 * we return the amount of copyied data.
2568 */
2569 return 1;
2570 }
2571 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002572 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002573 return 1;
2574}
2575
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002576/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002577 * of the writed string, or -1 if the channel is closed or if the
2578 * buffer size is too little for the data.
2579 */
2580__LJMP static int hlua_channel_append(lua_State *L)
2581{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002582 size_t len;
2583
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002584 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002585 MAY_LJMP(hlua_checkchannel(L, 1));
2586 MAY_LJMP(luaL_checklstring(L, 2, &len));
2587 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002588 lua_pushinteger(L, 0);
2589
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002590 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002591}
2592
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002593/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002594 * his process by cleaning the buffer. The result is a replacement
2595 * of the current data. It returns the length of the writed string,
2596 * or -1 if the channel is closed or if the buffer size is too
2597 * little for the data.
2598 */
2599__LJMP static int hlua_channel_set(lua_State *L)
2600{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002601 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002602
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002603 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002604 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002605 lua_pushinteger(L, 0);
2606
Willy Tarreau47860ed2015-03-10 14:07:50 +01002607 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002608
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002609 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002610}
2611
2612/* Append data in the output side of the buffer. This data is immediatly
2613 * sent. The fcuntion returns the ammount of data writed. If the buffer
2614 * cannot contains the data, the function yield. The function returns -1
2615 * if the channel is closed.
2616 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002617__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002618{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002619 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002620 size_t len;
2621 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2622 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2623 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002624 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002625
Willy Tarreau47860ed2015-03-10 14:07:50 +01002626 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002627 lua_pushinteger(L, -1);
2628 return 1;
2629 }
2630
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002631 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2632 * the request buffer if its not required.
2633 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002634 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002635 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002636 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002637 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002638 }
2639 }
2640
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002641 /* the writed data will be immediatly sent, so we can check
2642 * the avalaible space without taking in account the reserve.
2643 * The reserve is guaranted for the processing of incoming
2644 * data, because the buffer will be flushed.
2645 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002646 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002647
2648 /* If there are no space avalaible, and the output buffer is empty.
2649 * in this case, we cannot add more data, so we cannot yield,
2650 * we return the amount of copyied data.
2651 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002652 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002653 return 1;
2654
2655 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002656 if (max > len - l)
2657 max = len - l;
2658
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002659 /* The buffer avalaible size may be not contiguous. This test
2660 * detects a non contiguous buffer and realign it.
2661 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002662 if (bi_space_for_replace(chn->buf) < max)
2663 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002664
2665 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002666 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002667
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002668 /* buffer replace considers that the input part is filled.
2669 * so, I must forward these new data in the output part.
2670 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002671 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002672
2673 l += max;
2674 lua_pop(L, 1);
2675 lua_pushinteger(L, l);
2676
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002677 /* If there are no space avalaible, and the output buffer is empty.
2678 * in this case, we cannot add more data, so we cannot yield,
2679 * we return the amount of copyied data.
2680 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002681 max = chn->buf->size - buffer_len(chn->buf);
2682 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002683 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002684
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002685 if (l < len) {
2686 /* If we are waiting for space in the response buffer, we
2687 * must set the flag WAKERESWR. This flag required the task
2688 * wake up if any activity is detected on the response buffer.
2689 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002690 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002691 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002692 else
2693 HLUA_SET_WAKEREQWR(hlua);
2694 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002695 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002696
2697 return 1;
2698}
2699
2700/* Just a wraper of "_hlua_channel_send". This wrapper permits
2701 * yield the LUA process, and resume it without checking the
2702 * input arguments.
2703 */
2704__LJMP static int hlua_channel_send(lua_State *L)
2705{
2706 MAY_LJMP(check_args(L, 2, "send"));
2707 lua_pushinteger(L, 0);
2708
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002709 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002710}
2711
2712/* This function forward and amount of butes. The data pass from
2713 * the input side of the buffer to the output side, and can be
2714 * forwarded. This function never fails.
2715 *
2716 * The Lua function takes an amount of bytes to be forwarded in
2717 * imput. It returns the number of bytes forwarded.
2718 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002719__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002720{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002721 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002722 int len;
2723 int l;
2724 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002725 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002726
2727 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2728 len = MAY_LJMP(luaL_checkinteger(L, 2));
2729 l = MAY_LJMP(luaL_checkinteger(L, -1));
2730
2731 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002732 if (max > chn->buf->i)
2733 max = chn->buf->i;
2734 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002735 l += max;
2736
2737 lua_pop(L, 1);
2738 lua_pushinteger(L, l);
2739
2740 /* Check if it miss bytes to forward. */
2741 if (l < len) {
2742 /* The the input channel or the output channel are closed, we
2743 * must return the amount of data forwarded.
2744 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002745 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002746 return 1;
2747
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002748 /* If we are waiting for space data in the response buffer, we
2749 * must set the flag WAKERESWR. This flag required the task
2750 * wake up if any activity is detected on the response buffer.
2751 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002752 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002753 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002754 else
2755 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002756
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002757 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002758 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002759 }
2760
2761 return 1;
2762}
2763
2764/* Just check the input and prepare the stack for the previous
2765 * function "hlua_channel_forward_yield"
2766 */
2767__LJMP static int hlua_channel_forward(lua_State *L)
2768{
2769 MAY_LJMP(check_args(L, 2, "forward"));
2770 MAY_LJMP(hlua_checkchannel(L, 1));
2771 MAY_LJMP(luaL_checkinteger(L, 2));
2772
2773 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002774 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002775}
2776
2777/* Just returns the number of bytes available in the input
2778 * side of the buffer. This function never fails.
2779 */
2780__LJMP static int hlua_channel_get_in_len(lua_State *L)
2781{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002782 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002783
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002784 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002785 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002786 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002787 return 1;
2788}
2789
2790/* Just returns the number of bytes available in the output
2791 * side of the buffer. This function never fails.
2792 */
2793__LJMP static int hlua_channel_get_out_len(lua_State *L)
2794{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002795 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002796
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002797 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002798 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002799 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002800 return 1;
2801}
2802
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002803/*
2804 *
2805 *
2806 * Class Fetches
2807 *
2808 *
2809 */
2810
2811/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002812 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002813 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002814__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002815{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002816 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002817}
2818
2819/* This function creates and push in the stack a fetch object according
2820 * with a current TXN.
2821 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002822static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002823{
Willy Tarreau7073c472015-04-06 11:15:40 +02002824 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002825
2826 /* Check stack size. */
2827 if (!lua_checkstack(L, 3))
2828 return 0;
2829
2830 /* Create the object: obj[0] = userdata.
2831 * Note that the base of the Fetches object is the
2832 * transaction object.
2833 */
2834 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002835 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002836 lua_rawseti(L, -2, 0);
2837
Willy Tarreau7073c472015-04-06 11:15:40 +02002838 hsmp->s = txn->s;
2839 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002840 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002841
2842 /* Pop a class sesison metatable and affect it to the userdata. */
2843 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2844 lua_setmetatable(L, -2);
2845
2846 return 1;
2847}
2848
2849/* This function is an LUA binding. It is called with each sample-fetch.
2850 * It uses closure argument to store the associated sample-fetch. It
2851 * returns only one argument or throws an error. An error is thrown
2852 * only if an error is encountered during the argument parsing. If
2853 * the "sample-fetch" function fails, nil is returned.
2854 */
2855__LJMP static int hlua_run_sample_fetch(lua_State *L)
2856{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002857 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002858 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002859 struct arg args[ARGM_NBARGS + 1];
2860 int i;
2861 struct sample smp;
2862
2863 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002864 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002865
2866 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002867 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002868
2869 /* Get extra arguments. */
2870 for (i = 0; i < lua_gettop(L) - 1; i++) {
2871 if (i >= ARGM_NBARGS)
2872 break;
2873 hlua_lua2arg(L, i + 2, &args[i]);
2874 }
2875 args[i].type = ARGT_STOP;
2876
2877 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002878 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002879
2880 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002881 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002882 lua_pushfstring(L, "error in arguments");
2883 WILL_LJMP(lua_error(L));
2884 }
2885
2886 /* Initialise the sample. */
2887 memset(&smp, 0, sizeof(smp));
2888
2889 /* Run the sample fetch process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02002890 smp.px = hsmp->p;
2891 smp.sess = hsmp->s->sess;
2892 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002893 smp.opt = 0;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02002894 if (!f->process(args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002895 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002896 lua_pushstring(L, "");
2897 else
2898 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002899 return 1;
2900 }
2901
2902 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002903 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002904 hlua_smp2lua_str(L, &smp);
2905 else
2906 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002907 return 1;
2908}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002909
2910/*
2911 *
2912 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002913 * Class Converters
2914 *
2915 *
2916 */
2917
2918/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002919 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002920 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002921__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002922{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002923 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002924}
2925
2926/* This function creates and push in the stack a Converters object
2927 * according with a current TXN.
2928 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002929static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002930{
Willy Tarreau7073c472015-04-06 11:15:40 +02002931 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002932
2933 /* Check stack size. */
2934 if (!lua_checkstack(L, 3))
2935 return 0;
2936
2937 /* Create the object: obj[0] = userdata.
2938 * Note that the base of the Converters object is the
2939 * same than the TXN object.
2940 */
2941 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002942 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002943 lua_rawseti(L, -2, 0);
2944
Willy Tarreau7073c472015-04-06 11:15:40 +02002945 hsmp->s = txn->s;
2946 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002947 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002948
Willy Tarreau87b09662015-04-03 00:22:06 +02002949 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002950 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2951 lua_setmetatable(L, -2);
2952
2953 return 1;
2954}
2955
2956/* This function is an LUA binding. It is called with each converter.
2957 * It uses closure argument to store the associated converter. It
2958 * returns only one argument or throws an error. An error is thrown
2959 * only if an error is encountered during the argument parsing. If
2960 * the converter function function fails, nil is returned.
2961 */
2962__LJMP static int hlua_run_sample_conv(lua_State *L)
2963{
Willy Tarreauda5f1082015-04-06 11:17:13 +02002964 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002965 struct sample_conv *conv;
2966 struct arg args[ARGM_NBARGS + 1];
2967 int i;
2968 struct sample smp;
2969
2970 /* Get closure arguments. */
2971 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2972
2973 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002974 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002975
2976 /* Get extra arguments. */
2977 for (i = 0; i < lua_gettop(L) - 2; i++) {
2978 if (i >= ARGM_NBARGS)
2979 break;
2980 hlua_lua2arg(L, i + 3, &args[i]);
2981 }
2982 args[i].type = ARGT_STOP;
2983
2984 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002985 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002986
2987 /* Run the special args checker. */
2988 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2989 hlua_pusherror(L, "error in arguments");
2990 WILL_LJMP(lua_error(L));
2991 }
2992
2993 /* Initialise the sample. */
2994 if (!hlua_lua2smp(L, 2, &smp)) {
2995 hlua_pusherror(L, "error in the input argument");
2996 WILL_LJMP(lua_error(L));
2997 }
2998
2999 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003000 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003001 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003002 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003003 WILL_LJMP(lua_error(L));
3004 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02003005 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
3006 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003007 hlua_pusherror(L, "error during the input argument casting");
3008 WILL_LJMP(lua_error(L));
3009 }
3010
3011 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02003012 smp.px = hsmp->p;
3013 smp.sess = hsmp->s->sess;
3014 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02003015 smp.opt = 0;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003016 if (!conv->process(args, &smp, conv->private)) {
Willy Tarreauda5f1082015-04-06 11:17:13 +02003017 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003018 lua_pushstring(L, "");
3019 else
Willy Tarreaua678b432015-08-28 10:14:59 +02003020 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003021 return 1;
3022 }
3023
3024 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02003025 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003026 hlua_smp2lua_str(L, &smp);
3027 else
3028 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02003029 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003030}
3031
3032/*
3033 *
3034 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003035 * Class HTTP
3036 *
3037 *
3038 */
3039
3040/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003041 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003042 */
3043__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
3044{
3045 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
3046}
3047
3048/* This function creates and push in the stack a HTTP object
3049 * according with a current TXN.
3050 */
3051static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
3052{
Willy Tarreau9a8ad862015-04-06 11:14:06 +02003053 struct hlua_txn *htxn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003054
3055 /* Check stack size. */
3056 if (!lua_checkstack(L, 3))
3057 return 0;
3058
3059 /* Create the object: obj[0] = userdata.
3060 * Note that the base of the Converters object is the
3061 * same than the TXN object.
3062 */
3063 lua_newtable(L);
Willy Tarreau9a8ad862015-04-06 11:14:06 +02003064 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003065 lua_rawseti(L, -2, 0);
3066
Willy Tarreau9a8ad862015-04-06 11:14:06 +02003067 htxn->s = txn->s;
3068 htxn->p = txn->p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003069
Willy Tarreau87b09662015-04-03 00:22:06 +02003070 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003071 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
3072 lua_setmetatable(L, -2);
3073
3074 return 1;
3075}
3076
3077/* This function creates ans returns an array of HTTP headers.
3078 * This function does not fails. It is used as wrapper with the
3079 * 2 following functions.
3080 */
3081__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3082{
3083 const char *cur_ptr, *cur_next, *p;
3084 int old_idx, cur_idx;
3085 struct hdr_idx_elem *cur_hdr;
3086 const char *hn, *hv;
3087 int hnl, hvl;
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003088 int type;
3089 const char *in;
3090 char *out;
3091 int len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003092
3093 /* Create the table. */
3094 lua_newtable(L);
3095
Willy Tarreaueee5b512015-04-03 23:46:31 +02003096 if (!htxn->s->txn)
3097 return 1;
3098
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003099 /* Build array of headers. */
3100 old_idx = 0;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003101 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003102
3103 while (1) {
Willy Tarreaueee5b512015-04-03 23:46:31 +02003104 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003105 if (!cur_idx)
3106 break;
3107 old_idx = cur_idx;
3108
Willy Tarreaueee5b512015-04-03 23:46:31 +02003109 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003110 cur_ptr = cur_next;
3111 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
3112
3113 /* Now we have one full header at cur_ptr of len cur_hdr->len,
3114 * and the next header starts at cur_next. We'll check
3115 * this header in the list as well as against the default
3116 * rule.
3117 */
3118
3119 /* look for ': *'. */
3120 hn = cur_ptr;
3121 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
3122 if (p >= cur_ptr+cur_hdr->len)
3123 continue;
3124 hnl = p - hn;
3125 p++;
3126 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3127 p++;
3128 if (p >= cur_ptr+cur_hdr->len)
3129 continue;
3130 hv = p;
3131 hvl = cur_ptr+cur_hdr->len-p;
3132
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003133 /* Lowercase the key. Don't check the size of trash, it have
3134 * the size of one buffer and the input data contains in one
3135 * buffer.
3136 */
3137 out = trash.str;
3138 for (in=hn; in<hn+hnl; in++, out++)
3139 *out = tolower(*in);
3140 *out = '\0';
3141
3142 /* Check for existing entry:
3143 * assume that the table is on the top of the stack, and
3144 * push the key in the stack, the function lua_gettable()
3145 * perform the lookup.
3146 */
3147 lua_pushlstring(L, trash.str, hnl);
3148 lua_gettable(L, -2);
3149 type = lua_type(L, -1);
3150
3151 switch (type) {
3152 case LUA_TNIL:
3153 /* Table not found, create it. */
3154 lua_pop(L, 1); /* remove the nil value. */
3155 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
3156 lua_newtable(L); /* create and push empty table. */
3157 lua_pushlstring(L, hv, hvl); /* push header value. */
3158 lua_rawseti(L, -2, 0); /* index header value (pop it). */
3159 lua_rawset(L, -3); /* index new table with header name (pop the values). */
3160 break;
3161
3162 case LUA_TTABLE:
3163 /* Entry found: push the value in the table. */
3164 len = lua_rawlen(L, -1);
3165 lua_pushlstring(L, hv, hvl); /* push header value. */
3166 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
3167 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
3168 break;
3169
3170 default:
3171 /* Other cases are errors. */
3172 hlua_pusherror(L, "internal error during the parsing of headers.");
3173 WILL_LJMP(lua_error(L));
3174 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003175 }
3176
3177 return 1;
3178}
3179
3180__LJMP static int hlua_http_req_get_headers(lua_State *L)
3181{
3182 struct hlua_txn *htxn;
3183
3184 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3185 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3186
Willy Tarreaueee5b512015-04-03 23:46:31 +02003187 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003188}
3189
3190__LJMP static int hlua_http_res_get_headers(lua_State *L)
3191{
3192 struct hlua_txn *htxn;
3193
3194 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3195 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3196
Willy Tarreaueee5b512015-04-03 23:46:31 +02003197 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003198}
3199
3200/* This function replace full header, or just a value in
3201 * the request or in the response. It is a wrapper fir the
3202 * 4 following functions.
3203 */
3204__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3205 struct http_msg *msg, int action)
3206{
3207 size_t name_len;
3208 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3209 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3210 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3211 struct my_regex re;
3212
3213 if (!regex_comp(reg, &re, 1, 1, NULL))
3214 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3215
3216 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3217 regex_free(&re);
3218 return 0;
3219}
3220
3221__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3222{
3223 struct hlua_txn *htxn;
3224
3225 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3226 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3227
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003228 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003229}
3230
3231__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3232{
3233 struct hlua_txn *htxn;
3234
3235 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3236 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3237
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003238 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003239}
3240
3241__LJMP static int hlua_http_req_rep_val(lua_State *L)
3242{
3243 struct hlua_txn *htxn;
3244
3245 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3246 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3247
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003248 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003249}
3250
3251__LJMP static int hlua_http_res_rep_val(lua_State *L)
3252{
3253 struct hlua_txn *htxn;
3254
3255 MAY_LJMP(check_args(L, 4, "res_rep_val"));
3256 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3257
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003258 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003259}
3260
3261/* This function deletes all the occurences of an header.
3262 * It is a wrapper for the 2 following functions.
3263 */
3264__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3265{
3266 size_t len;
3267 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3268 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003269 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003270
3271 ctx.idx = 0;
3272 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3273 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3274 return 0;
3275}
3276
3277__LJMP static int hlua_http_req_del_hdr(lua_State *L)
3278{
3279 struct hlua_txn *htxn;
3280
3281 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3282 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3283
Willy Tarreaueee5b512015-04-03 23:46:31 +02003284 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003285}
3286
3287__LJMP static int hlua_http_res_del_hdr(lua_State *L)
3288{
3289 struct hlua_txn *htxn;
3290
3291 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3292 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3293
Willy Tarreaueee5b512015-04-03 23:46:31 +02003294 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003295}
3296
3297/* This function adds an header. It is a wrapper used by
3298 * the 2 following functions.
3299 */
3300__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3301{
3302 size_t name_len;
3303 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3304 size_t value_len;
3305 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3306 char *p;
3307
3308 /* Check length. */
3309 trash.len = value_len + name_len + 2;
3310 if (trash.len > trash.size)
3311 return 0;
3312
3313 /* Creates the header string. */
3314 p = trash.str;
3315 memcpy(p, name, name_len);
3316 p += name_len;
3317 *p = ':';
3318 p++;
3319 *p = ' ';
3320 p++;
3321 memcpy(p, value, value_len);
3322
Willy Tarreaueee5b512015-04-03 23:46:31 +02003323 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003324 trash.str, trash.len) != 0);
3325
3326 return 0;
3327}
3328
3329__LJMP static int hlua_http_req_add_hdr(lua_State *L)
3330{
3331 struct hlua_txn *htxn;
3332
3333 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3334 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3335
Willy Tarreaueee5b512015-04-03 23:46:31 +02003336 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003337}
3338
3339__LJMP static int hlua_http_res_add_hdr(lua_State *L)
3340{
3341 struct hlua_txn *htxn;
3342
3343 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3344 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3345
Willy Tarreaueee5b512015-04-03 23:46:31 +02003346 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003347}
3348
3349static int hlua_http_req_set_hdr(lua_State *L)
3350{
3351 struct hlua_txn *htxn;
3352
3353 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3354 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3355
Willy Tarreaueee5b512015-04-03 23:46:31 +02003356 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3357 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003358}
3359
3360static int hlua_http_res_set_hdr(lua_State *L)
3361{
3362 struct hlua_txn *htxn;
3363
3364 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3365 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3366
Willy Tarreaueee5b512015-04-03 23:46:31 +02003367 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3368 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003369}
3370
3371/* This function set the method. */
3372static int hlua_http_req_set_meth(lua_State *L)
3373{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003374 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003375 size_t name_len;
3376 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003377
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003378 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003379 return 1;
3380}
3381
3382/* This function set the method. */
3383static int hlua_http_req_set_path(lua_State *L)
3384{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003385 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003386 size_t name_len;
3387 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003388 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003389 return 1;
3390}
3391
3392/* This function set the query-string. */
3393static int hlua_http_req_set_query(lua_State *L)
3394{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003395 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003396 size_t name_len;
3397 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003398
3399 /* Check length. */
3400 if (name_len > trash.size - 1) {
3401 lua_pushboolean(L, 0);
3402 return 1;
3403 }
3404
3405 /* Add the mark question as prefix. */
3406 chunk_reset(&trash);
3407 trash.str[trash.len++] = '?';
3408 memcpy(trash.str + trash.len, name, name_len);
3409 trash.len += name_len;
3410
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003411 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003412 return 1;
3413}
3414
3415/* This function set the uri. */
3416static int hlua_http_req_set_uri(lua_State *L)
3417{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003418 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003419 size_t name_len;
3420 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003421
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003422 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003423 return 1;
3424}
3425
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02003426/* This function set the response code. */
3427static int hlua_http_res_set_status(lua_State *L)
3428{
3429 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3430 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
3431
3432 http_set_status(code, htxn->s);
3433 return 0;
3434}
3435
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003436/*
3437 *
3438 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003439 * Class TXN
3440 *
3441 *
3442 */
3443
3444/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003445 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003446 */
3447__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3448{
3449 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3450}
3451
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02003452__LJMP static int hlua_set_var(lua_State *L)
3453{
3454 struct hlua_txn *htxn;
3455 const char *name;
3456 size_t len;
3457 struct sample smp;
3458
3459 MAY_LJMP(check_args(L, 3, "set_var"));
3460
3461 /* It is useles to retrieve the stream, but this function
3462 * runs only in a stream context.
3463 */
3464 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3465 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3466
3467 /* Converts the third argument in a sample. */
3468 hlua_lua2smp(L, 3, &smp);
3469
3470 /* Store the sample in a variable. */
3471 vars_set_by_name(name, len, htxn->s, &smp);
3472 return 0;
3473}
3474
3475__LJMP static int hlua_get_var(lua_State *L)
3476{
3477 struct hlua_txn *htxn;
3478 const char *name;
3479 size_t len;
3480 struct sample smp;
3481
3482 MAY_LJMP(check_args(L, 2, "get_var"));
3483
3484 /* It is useles to retrieve the stream, but this function
3485 * runs only in a stream context.
3486 */
3487 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3488 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3489
3490 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
3491 lua_pushnil(L);
3492 return 1;
3493 }
3494
3495 return hlua_smp2lua(L, &smp);
3496}
3497
Willy Tarreau59551662015-03-10 14:23:13 +01003498__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003499{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003500 struct hlua *hlua;
3501
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003502 MAY_LJMP(check_args(L, 2, "set_priv"));
3503
Willy Tarreau87b09662015-04-03 00:22:06 +02003504 /* It is useles to retrieve the stream, but this function
3505 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003506 */
3507 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003508 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003509
3510 /* Remove previous value. */
3511 if (hlua->Mref != -1)
3512 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3513
3514 /* Get and store new value. */
3515 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3516 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3517
3518 return 0;
3519}
3520
Willy Tarreau59551662015-03-10 14:23:13 +01003521__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003522{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003523 struct hlua *hlua;
3524
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003525 MAY_LJMP(check_args(L, 1, "get_priv"));
3526
Willy Tarreau87b09662015-04-03 00:22:06 +02003527 /* It is useles to retrieve the stream, but this function
3528 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003529 */
3530 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003531 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003532
3533 /* Push configuration index in the stack. */
3534 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3535
3536 return 1;
3537}
3538
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003539/* Create stack entry containing a class TXN. This function
3540 * return 0 if the stack does not contains free slots,
3541 * otherwise it returns 1.
3542 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003543static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003544{
Willy Tarreaude491382015-04-06 11:04:28 +02003545 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003546
3547 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003548 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003549 return 0;
3550
3551 /* NOTE: The allocation never fails. The failure
3552 * throw an error, and the function never returns.
3553 * if the throw is not avalaible, the process is aborted.
3554 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003555 /* Create the object: obj[0] = userdata. */
3556 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02003557 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003558 lua_rawseti(L, -2, 0);
3559
Willy Tarreaude491382015-04-06 11:04:28 +02003560 htxn->s = s;
3561 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003562
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003563 /* Create the "f" field that contains a list of fetches. */
3564 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02003565 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003566 return 0;
3567 lua_settable(L, -3);
3568
3569 /* Create the "sf" field that contains a list of stringsafe fetches. */
3570 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02003571 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003572 return 0;
3573 lua_settable(L, -3);
3574
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003575 /* Create the "c" field that contains a list of converters. */
3576 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02003577 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003578 return 0;
3579 lua_settable(L, -3);
3580
3581 /* Create the "sc" field that contains a list of stringsafe converters. */
3582 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02003583 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003584 return 0;
3585 lua_settable(L, -3);
3586
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003587 /* Create the "req" field that contains the request channel object. */
3588 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003589 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003590 return 0;
3591 lua_settable(L, -3);
3592
3593 /* Create the "res" field that contains the response channel object. */
3594 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003595 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003596 return 0;
3597 lua_settable(L, -3);
3598
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003599 /* Creates the HTTP object is the current proxy allows http. */
3600 lua_pushstring(L, "http");
3601 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02003602 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003603 return 0;
3604 }
3605 else
3606 lua_pushnil(L);
3607 lua_settable(L, -3);
3608
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003609 /* Pop a class sesison metatable and affect it to the userdata. */
3610 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3611 lua_setmetatable(L, -2);
3612
3613 return 1;
3614}
3615
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003616__LJMP static int hlua_txn_deflog(lua_State *L)
3617{
3618 const char *msg;
3619 struct hlua_txn *htxn;
3620
3621 MAY_LJMP(check_args(L, 2, "deflog"));
3622 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3623 msg = MAY_LJMP(luaL_checkstring(L, 2));
3624
3625 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3626 return 0;
3627}
3628
3629__LJMP static int hlua_txn_log(lua_State *L)
3630{
3631 int level;
3632 const char *msg;
3633 struct hlua_txn *htxn;
3634
3635 MAY_LJMP(check_args(L, 3, "log"));
3636 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3637 level = MAY_LJMP(luaL_checkinteger(L, 2));
3638 msg = MAY_LJMP(luaL_checkstring(L, 3));
3639
3640 if (level < 0 || level >= NB_LOG_LEVELS)
3641 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3642
3643 hlua_sendlog(htxn->s->be, level, msg);
3644 return 0;
3645}
3646
3647__LJMP static int hlua_txn_log_debug(lua_State *L)
3648{
3649 const char *msg;
3650 struct hlua_txn *htxn;
3651
3652 MAY_LJMP(check_args(L, 2, "Debug"));
3653 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3654 msg = MAY_LJMP(luaL_checkstring(L, 2));
3655 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3656 return 0;
3657}
3658
3659__LJMP static int hlua_txn_log_info(lua_State *L)
3660{
3661 const char *msg;
3662 struct hlua_txn *htxn;
3663
3664 MAY_LJMP(check_args(L, 2, "Info"));
3665 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3666 msg = MAY_LJMP(luaL_checkstring(L, 2));
3667 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3668 return 0;
3669}
3670
3671__LJMP static int hlua_txn_log_warning(lua_State *L)
3672{
3673 const char *msg;
3674 struct hlua_txn *htxn;
3675
3676 MAY_LJMP(check_args(L, 2, "Warning"));
3677 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3678 msg = MAY_LJMP(luaL_checkstring(L, 2));
3679 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3680 return 0;
3681}
3682
3683__LJMP static int hlua_txn_log_alert(lua_State *L)
3684{
3685 const char *msg;
3686 struct hlua_txn *htxn;
3687
3688 MAY_LJMP(check_args(L, 2, "Alert"));
3689 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3690 msg = MAY_LJMP(luaL_checkstring(L, 2));
3691 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3692 return 0;
3693}
3694
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003695__LJMP static int hlua_txn_set_loglevel(lua_State *L)
3696{
3697 struct hlua_txn *htxn;
3698 int ll;
3699
3700 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3701 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3702 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3703
3704 if (ll < 0 || ll > 7)
3705 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3706
3707 htxn->s->logs.level = ll;
3708 return 0;
3709}
3710
3711__LJMP static int hlua_txn_set_tos(lua_State *L)
3712{
3713 struct hlua_txn *htxn;
3714 struct connection *cli_conn;
3715 int tos;
3716
3717 MAY_LJMP(check_args(L, 2, "set_tos"));
3718 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3719 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3720
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003721 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003722 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3723
3724 return 0;
3725}
3726
3727__LJMP static int hlua_txn_set_mark(lua_State *L)
3728{
3729#ifdef SO_MARK
3730 struct hlua_txn *htxn;
3731 struct connection *cli_conn;
3732 int mark;
3733
3734 MAY_LJMP(check_args(L, 2, "set_mark"));
3735 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3736 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3737
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003738 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02003739 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003740#endif
3741 return 0;
3742}
3743
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003744/* This function is an Lua binding that send pending data
3745 * to the client, and close the stream interface.
3746 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02003747__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003748{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003749 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01003750 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003751
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003752 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003753 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003754
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003755 ic = &htxn->s->req;
3756 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01003757
Willy Tarreau630ef452015-08-28 10:06:15 +02003758 if (htxn->s->txn) {
3759 /* HTTP mode, let's stay in sync with the stream */
3760 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
3761 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
3762 htxn->s->txn->req.sov = 0;
3763 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
3764 oc->analysers = AN_RES_HTTP_XFER_BODY;
3765 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
3766 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
3767
3768 /* Trim any possible response */
3769 oc->buf->i = 0;
3770 htxn->s->txn->rsp.next = htxn->s->txn->rsp.sov = 0;
3771
3772 /* Note that if we want to support keep-alive, we need
3773 * to bypass the close/shutr_now calls below, but that
3774 * may only be done if the HTTP request was already
3775 * processed and the connection header is known (ie
3776 * not during TCP rules).
3777 */
3778 }
3779
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003780 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01003781 channel_abort(ic);
3782 channel_auto_close(ic);
3783 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003784
3785 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01003786 channel_auto_read(oc);
3787 channel_auto_close(oc);
3788 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003789
Willy Tarreau0458b082015-08-28 09:40:04 +02003790 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02003791
3792 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003793 return 0;
3794}
3795
3796__LJMP static int hlua_log(lua_State *L)
3797{
3798 int level;
3799 const char *msg;
3800
3801 MAY_LJMP(check_args(L, 2, "log"));
3802 level = MAY_LJMP(luaL_checkinteger(L, 1));
3803 msg = MAY_LJMP(luaL_checkstring(L, 2));
3804
3805 if (level < 0 || level >= NB_LOG_LEVELS)
3806 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3807
3808 hlua_sendlog(NULL, level, msg);
3809 return 0;
3810}
3811
3812__LJMP static int hlua_log_debug(lua_State *L)
3813{
3814 const char *msg;
3815
3816 MAY_LJMP(check_args(L, 1, "debug"));
3817 msg = MAY_LJMP(luaL_checkstring(L, 1));
3818 hlua_sendlog(NULL, LOG_DEBUG, msg);
3819 return 0;
3820}
3821
3822__LJMP static int hlua_log_info(lua_State *L)
3823{
3824 const char *msg;
3825
3826 MAY_LJMP(check_args(L, 1, "info"));
3827 msg = MAY_LJMP(luaL_checkstring(L, 1));
3828 hlua_sendlog(NULL, LOG_INFO, msg);
3829 return 0;
3830}
3831
3832__LJMP static int hlua_log_warning(lua_State *L)
3833{
3834 const char *msg;
3835
3836 MAY_LJMP(check_args(L, 1, "warning"));
3837 msg = MAY_LJMP(luaL_checkstring(L, 1));
3838 hlua_sendlog(NULL, LOG_WARNING, msg);
3839 return 0;
3840}
3841
3842__LJMP static int hlua_log_alert(lua_State *L)
3843{
3844 const char *msg;
3845
3846 MAY_LJMP(check_args(L, 1, "alert"));
3847 msg = MAY_LJMP(luaL_checkstring(L, 1));
3848 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003849 return 0;
3850}
3851
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003852__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003853{
3854 int wakeup_ms = lua_tointeger(L, -1);
3855 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003856 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003857 return 0;
3858}
3859
3860__LJMP static int hlua_sleep(lua_State *L)
3861{
3862 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003863 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003864
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003865 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003866
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003867 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003868 wakeup_ms = tick_add(now_ms, delay);
3869 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003870
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003871 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3872 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003873}
3874
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003875__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003876{
3877 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003878 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003879
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003880 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003881
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003882 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003883 wakeup_ms = tick_add(now_ms, delay);
3884 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003885
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003886 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3887 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003888}
3889
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003890/* This functionis an LUA binding. it permits to give back
3891 * the hand at the HAProxy scheduler. It is used when the
3892 * LUA processing consumes a lot of time.
3893 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003894__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003895{
3896 return 0;
3897}
3898
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003899__LJMP static int hlua_yield(lua_State *L)
3900{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003901 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3902 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003903}
3904
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003905/* This function change the nice of the currently executed
3906 * task. It is used set low or high priority at the current
3907 * task.
3908 */
Willy Tarreau59551662015-03-10 14:23:13 +01003909__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003910{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003911 struct hlua *hlua;
3912 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003913
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003914 MAY_LJMP(check_args(L, 1, "set_nice"));
3915 hlua = hlua_gethlua(L);
3916 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003917
3918 /* If he task is not set, I'm in a start mode. */
3919 if (!hlua || !hlua->task)
3920 return 0;
3921
3922 if (nice < -1024)
3923 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003924 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003925 nice = 1024;
3926
3927 hlua->task->nice = nice;
3928 return 0;
3929}
3930
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003931/* This function is used as a calback of a task. It is called by the
3932 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3933 * return an E_AGAIN signal, the emmiter of this signal must set a
3934 * signal to wake the task.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02003935 *
3936 * Task wrapper are longjmp safe because the only one Lua code
3937 * executed is the safe hlua_ctx_resume();
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003938 */
3939static struct task *hlua_process_task(struct task *task)
3940{
3941 struct hlua *hlua = task->context;
3942 enum hlua_exec status;
3943
3944 /* We need to remove the task from the wait queue before executing
3945 * the Lua code because we don't know if it needs to wait for
3946 * another timer or not in the case of E_AGAIN.
3947 */
3948 task_delete(task);
3949
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003950 /* If it is the first call to the task, we must initialize the
3951 * execution timeouts.
3952 */
3953 if (!HLUA_IS_RUNNING(hlua))
Camilo Lopez685c0142015-08-02 19:07:28 -04003954 hlua->expire = tick_add_ifset(now_ms, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003955
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003956 /* Execute the Lua code. */
3957 status = hlua_ctx_resume(hlua, 1);
3958
3959 switch (status) {
3960 /* finished or yield */
3961 case HLUA_E_OK:
3962 hlua_ctx_destroy(hlua);
3963 task_delete(task);
3964 task_free(task);
3965 break;
3966
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003967 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3968 if (hlua->wake_time != TICK_ETERNITY)
3969 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003970 break;
3971
3972 /* finished with error. */
3973 case HLUA_E_ERRMSG:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02003974 SEND_ERR(NULL, "Lua task: %s.\n", lua_tostring(hlua->T, -1));
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003975 hlua_ctx_destroy(hlua);
3976 task_delete(task);
3977 task_free(task);
3978 break;
3979
3980 case HLUA_E_ERR:
3981 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02003982 SEND_ERR(NULL, "Lua task: unknown error.\n");
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003983 hlua_ctx_destroy(hlua);
3984 task_delete(task);
3985 task_free(task);
3986 break;
3987 }
3988 return NULL;
3989}
3990
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003991/* This function is an LUA binding that register LUA function to be
3992 * executed after the HAProxy configuration parsing and before the
3993 * HAProxy scheduler starts. This function expect only one LUA
3994 * argument that is a function. This function returns nothing, but
3995 * throws if an error is encountered.
3996 */
3997__LJMP static int hlua_register_init(lua_State *L)
3998{
3999 struct hlua_init_function *init;
4000 int ref;
4001
4002 MAY_LJMP(check_args(L, 1, "register_init"));
4003
4004 ref = MAY_LJMP(hlua_checkfunction(L, 1));
4005
4006 init = malloc(sizeof(*init));
4007 if (!init)
4008 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4009
4010 init->function_ref = ref;
4011 LIST_ADDQ(&hlua_init_functions, &init->l);
4012 return 0;
4013}
4014
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004015/* This functio is an LUA binding. It permits to register a task
4016 * executed in parallel of the main HAroxy activity. The task is
4017 * created and it is set in the HAProxy scheduler. It can be called
4018 * from the "init" section, "post init" or during the runtime.
4019 *
4020 * Lua prototype:
4021 *
4022 * <none> core.register_task(<function>)
4023 */
4024static int hlua_register_task(lua_State *L)
4025{
4026 struct hlua *hlua;
4027 struct task *task;
4028 int ref;
4029
4030 MAY_LJMP(check_args(L, 1, "register_task"));
4031
4032 ref = MAY_LJMP(hlua_checkfunction(L, 1));
4033
4034 hlua = malloc(sizeof(*hlua));
4035 if (!hlua)
4036 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4037
4038 task = task_new();
4039 task->context = hlua;
4040 task->process = hlua_process_task;
4041
4042 if (!hlua_ctx_init(hlua, task))
4043 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4044
4045 /* Restore the function in the stack. */
4046 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
4047 hlua->nargs = 0;
4048
4049 /* Schedule task. */
4050 task_schedule(task, now_ms);
4051
4052 return 0;
4053}
4054
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004055/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
4056 * doesn't allow "yield" functions because the HAProxy engine cannot
4057 * resume converters.
4058 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004059static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004060{
4061 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004062 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004063
Willy Tarreau87b09662015-04-03 00:22:06 +02004064 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004065 * Lua context can be not initialized. This behavior
4066 * permits to save performances because a systematic
4067 * Lua initialization cause 5% performances loss.
4068 */
Willy Tarreau87b09662015-04-03 00:22:06 +02004069 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004070 SEND_ERR(stream->be, "Lua converter '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004071 return 0;
4072 }
4073
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004074 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004075 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004076
4077 /* The following Lua calls can fail. */
4078 if (!SET_SAFE_LJMP(stream->hlua.T)) {
4079 SEND_ERR(stream->be, "Lua converter '%s': critical error.\n", fcn->name);
4080 return 0;
4081 }
4082
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004083 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004084 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004085 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004086 return 0;
4087 }
4088
4089 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004090 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004091
4092 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004093 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004094 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004095 return 0;
4096 }
Willy Tarreau87b09662015-04-03 00:22:06 +02004097 hlua_smp2lua(stream->hlua.T, smp);
4098 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004099
4100 /* push keywords in the stack. */
4101 if (arg_p) {
4102 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02004103 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004104 SEND_ERR(stream->be, "Lua converter '%s': full stack.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004105 return 0;
4106 }
Willy Tarreau87b09662015-04-03 00:22:06 +02004107 hlua_arg2lua(stream->hlua.T, arg_p);
4108 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004109 }
4110 }
4111
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004112 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004113 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004114
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004115 /* At this point the execution is safe. */
4116 RESET_SAFE_LJMP(stream->hlua.T);
4117
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004118 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004119 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004120 }
4121
4122 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004123 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004124 /* finished. */
4125 case HLUA_E_OK:
4126 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004127 hlua_lua2smp(stream->hlua.T, -1, smp);
4128 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004129 return 1;
4130
4131 /* yield. */
4132 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004133 SEND_ERR(stream->be, "Lua converter '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004134 return 0;
4135
4136 /* finished with error. */
4137 case HLUA_E_ERRMSG:
4138 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004139 SEND_ERR(stream->be, "Lua converter '%s': %s.\n",
4140 fcn->name, lua_tostring(stream->hlua.T, -1));
Willy Tarreau87b09662015-04-03 00:22:06 +02004141 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004142 return 0;
4143
4144 case HLUA_E_ERR:
4145 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004146 SEND_ERR(stream->be, "Lua converter '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004147
4148 default:
4149 return 0;
4150 }
4151}
4152
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004153/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
4154 * doesn't allow "yield" functions because the HAProxy engine cannot
4155 * resume sample-fetches.
4156 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004157static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
4158 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004159{
4160 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004161 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004162
Willy Tarreau87b09662015-04-03 00:22:06 +02004163 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004164 * Lua context can be not initialized. This behavior
4165 * permits to save performances because a systematic
4166 * Lua initialization cause 5% performances loss.
4167 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004168 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004169 SEND_ERR(stream->be, "Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004170 return 0;
4171 }
4172
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004173 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004174 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004175
4176 /* The following Lua calls can fail. */
4177 if (!SET_SAFE_LJMP(stream->hlua.T)) {
4178 SEND_ERR(smp->px, "Lua sample-fetch '%s': critical error.\n", fcn->name);
4179 return 0;
4180 }
4181
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004182 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004183 if (!lua_checkstack(stream->hlua.T, 2)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004184 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004185 return 0;
4186 }
4187
4188 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004189 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004190
4191 /* push arguments in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004192 if (!hlua_txn_new(stream->hlua.T, stream, smp->px)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004193 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004194 return 0;
4195 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004196 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004197
4198 /* push keywords in the stack. */
4199 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
4200 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004201 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004202 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004203 return 0;
4204 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004205 if (!lua_checkstack(stream->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004206 SEND_ERR(smp->px, "Lua sample-fetch '%s': full stack.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004207 return 0;
4208 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004209 hlua_arg2lua(stream->hlua.T, arg_p);
4210 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004211 }
4212
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004213 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004214 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004215
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004216 /* At this point the execution is safe. */
4217 RESET_SAFE_LJMP(stream->hlua.T);
4218
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004219 /* Set the currently running flag. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004220 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004221 }
4222
4223 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004224 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004225 /* finished. */
4226 case HLUA_E_OK:
4227 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004228 hlua_lua2smp(stream->hlua.T, -1, smp);
4229 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004230
4231 /* Set the end of execution flag. */
4232 smp->flags &= ~SMP_F_MAY_CHANGE;
4233 return 1;
4234
4235 /* yield. */
4236 case HLUA_E_AGAIN:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004237 SEND_ERR(smp->px, "Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004238 return 0;
4239
4240 /* finished with error. */
4241 case HLUA_E_ERRMSG:
4242 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004243 SEND_ERR(smp->px, "Lua sample-fetch '%s': %s.\n",
4244 fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004245 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004246 return 0;
4247
4248 case HLUA_E_ERR:
4249 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004250 SEND_ERR(smp->px, "Lua sample-fetch '%s' returns an unknown error.\n", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004251
4252 default:
4253 return 0;
4254 }
4255}
4256
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004257/* This function is an LUA binding used for registering
4258 * "sample-conv" functions. It expects a converter name used
4259 * in the haproxy configuration file, and an LUA function.
4260 */
4261__LJMP static int hlua_register_converters(lua_State *L)
4262{
4263 struct sample_conv_kw_list *sck;
4264 const char *name;
4265 int ref;
4266 int len;
4267 struct hlua_function *fcn;
4268
4269 MAY_LJMP(check_args(L, 2, "register_converters"));
4270
4271 /* First argument : converter name. */
4272 name = MAY_LJMP(luaL_checkstring(L, 1));
4273
4274 /* Second argument : lua function. */
4275 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4276
4277 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004278 sck = malloc(sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004279 if (!sck)
4280 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4281 fcn = malloc(sizeof(*fcn));
4282 if (!fcn)
4283 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4284
4285 /* Fill fcn. */
4286 fcn->name = strdup(name);
4287 if (!fcn->name)
4288 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4289 fcn->function_ref = ref;
4290
4291 /* List head */
4292 sck->list.n = sck->list.p = NULL;
4293
4294 /* converter keyword. */
4295 len = strlen("lua.") + strlen(name) + 1;
4296 sck->kw[0].kw = malloc(len);
4297 if (!sck->kw[0].kw)
4298 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4299
4300 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4301 sck->kw[0].process = hlua_sample_conv_wrapper;
4302 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4303 sck->kw[0].val_args = NULL;
4304 sck->kw[0].in_type = SMP_T_STR;
4305 sck->kw[0].out_type = SMP_T_STR;
4306 sck->kw[0].private = fcn;
4307
4308 /* End of array. */
4309 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
4310
4311 /* Register this new converter */
4312 sample_register_convs(sck);
4313
4314 return 0;
4315}
4316
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004317/* This fucntion is an LUA binding used for registering
4318 * "sample-fetch" functions. It expects a converter name used
4319 * in the haproxy configuration file, and an LUA function.
4320 */
4321__LJMP static int hlua_register_fetches(lua_State *L)
4322{
4323 const char *name;
4324 int ref;
4325 int len;
4326 struct sample_fetch_kw_list *sfk;
4327 struct hlua_function *fcn;
4328
4329 MAY_LJMP(check_args(L, 2, "register_fetches"));
4330
4331 /* First argument : sample-fetch name. */
4332 name = MAY_LJMP(luaL_checkstring(L, 1));
4333
4334 /* Second argument : lua function. */
4335 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4336
4337 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004338 sfk = malloc(sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004339 if (!sfk)
4340 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4341 fcn = malloc(sizeof(*fcn));
4342 if (!fcn)
4343 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4344
4345 /* Fill fcn. */
4346 fcn->name = strdup(name);
4347 if (!fcn->name)
4348 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4349 fcn->function_ref = ref;
4350
4351 /* List head */
4352 sfk->list.n = sfk->list.p = NULL;
4353
4354 /* sample-fetch keyword. */
4355 len = strlen("lua.") + strlen(name) + 1;
4356 sfk->kw[0].kw = malloc(len);
4357 if (!sfk->kw[0].kw)
4358 return luaL_error(L, "lua out of memory error.");
4359
4360 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4361 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4362 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4363 sfk->kw[0].val_args = NULL;
4364 sfk->kw[0].out_type = SMP_T_STR;
4365 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4366 sfk->kw[0].val = 0;
4367 sfk->kw[0].private = fcn;
4368
4369 /* End of array. */
4370 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
4371
4372 /* Register this new fetch. */
4373 sample_register_fetches(sfk);
4374
4375 return 0;
4376}
4377
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004378/* This function is a wrapper to execute each LUA function declared
4379 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004380 * return ACT_RET_CONT if the processing is finished (with or without
4381 * error) and return ACT_RET_YIELD if the function must be called again
4382 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004383 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004384static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
4385 struct session *sess, struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004386{
4387 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004388 unsigned int analyzer;
4389
4390 switch (rule->from) {
4391 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; break;
4392 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; break;
4393 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; break;
4394 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; break;
4395 default:
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004396 SEND_ERR(px, "Lua: internal error while execute action.\n");
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004397 return ACT_RET_CONT;
4398 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004399
Willy Tarreau87b09662015-04-03 00:22:06 +02004400 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004401 * Lua context can be not initialized. This behavior
4402 * permits to save performances because a systematic
4403 * Lua initialization cause 5% performances loss.
4404 */
4405 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004406 SEND_ERR(px, "Lua action '%s': can't initialize Lua context.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004407 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004408 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004409 }
4410
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004411 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004412 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004413
4414 /* The following Lua calls can fail. */
4415 if (!SET_SAFE_LJMP(s->hlua.T)) {
4416 SEND_ERR(px, "Lua function '%s': critical error.\n",
4417 rule->arg.hlua_rule->fcn.name);
4418 return ACT_RET_CONT;
4419 }
4420
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004421 /* Check stack available size. */
4422 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004423 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004424 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004425 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004426 }
4427
4428 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004429 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004430
Willy Tarreau87b09662015-04-03 00:22:06 +02004431 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004432 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004433 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004434 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004435 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004436 }
4437 s->hlua.nargs = 1;
4438
4439 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004440 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004441 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004442 SEND_ERR(px, "Lua function '%s': full stack.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004443 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004444 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004445 }
4446 lua_pushstring(s->hlua.T, *arg);
4447 s->hlua.nargs++;
4448 }
4449
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004450 /* Now the execution is safe. */
4451 RESET_SAFE_LJMP(s->hlua.T);
4452
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004453 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004454 s->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004455
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004456 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004457 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004458 }
4459
4460 /* Execute the function. */
4461 switch (hlua_ctx_resume(&s->hlua, 1)) {
4462 /* finished. */
4463 case HLUA_E_OK:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004464 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004465
4466 /* yield. */
4467 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004468 /* Set timeout in the required channel. */
4469 if (s->hlua.wake_time != TICK_ETERNITY) {
4470 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004471 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004472 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004473 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004474 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004475 /* Some actions can be wake up when a "write" event
4476 * is detected on a response channel. This is useful
4477 * only for actions targetted on the requests.
4478 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004479 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004480 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01004481 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004482 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004483 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004484 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004485 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004486 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004487
4488 /* finished with error. */
4489 case HLUA_E_ERRMSG:
4490 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004491 SEND_ERR(px, "Lua function '%s': %s.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004492 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004493 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004494 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004495
4496 case HLUA_E_ERR:
4497 /* Display log. */
Thierry FOURNIER23bc3752015-09-11 19:15:43 +02004498 SEND_ERR(px, "Lua function '%s' return an unknown error.\n",
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004499 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004500
4501 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004502 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004503 }
4504}
4505
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004506/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
4507 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004508 *
4509 * This function can fail with an abort() due to an Lua critical error.
4510 * We are in the configuration parsing process of HAProxy, this abort() is
4511 * tolerated.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004512 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004513static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4514 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004515{
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004516 struct hlua_function *fcn = (struct hlua_function *)rule->kw->private;
4517
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004518 /* Memory for the rule. */
4519 rule->arg.hlua_rule = malloc(sizeof(*rule->arg.hlua_rule));
4520 if (!rule->arg.hlua_rule) {
4521 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004522 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004523 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004524
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004525 /* Reference the Lua function and store the reference. */
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004526 rule->arg.hlua_rule->fcn = *fcn;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004527
4528 /* TODO: later accept arguments. */
4529 rule->arg.hlua_rule->args = NULL;
4530
Thierry FOURNIER42148732015-09-02 17:17:33 +02004531 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004532 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004533 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004534}
4535
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004536/* This function is an LUA binding used for registering
4537 * "sample-conv" functions. It expects a converter name used
4538 * in the haproxy configuration file, and an LUA function.
4539 */
4540__LJMP static int hlua_register_action(lua_State *L)
4541{
4542 struct action_kw_list *akl;
4543 const char *name;
4544 int ref;
4545 int len;
4546 struct hlua_function *fcn;
4547
4548 MAY_LJMP(check_args(L, 3, "register_service"));
4549
4550 /* First argument : converter name. */
4551 name = MAY_LJMP(luaL_checkstring(L, 1));
4552
4553 /* Second argument : environment. */
4554 if (lua_type(L, 2) != LUA_TTABLE)
4555 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
4556
4557 /* Third argument : lua function. */
4558 ref = MAY_LJMP(hlua_checkfunction(L, 3));
4559
4560 /* browse the second argulent as an array. */
4561 lua_pushnil(L);
4562 while (lua_next(L, 2) != 0) {
4563 if (lua_type(L, -1) != LUA_TSTRING)
4564 WILL_LJMP(luaL_error(L, "register_action: second argument must be a table of strings"));
4565
4566 /* Check required environment. Only accepted "http" or "tcp". */
4567 /* Allocate and fill the sample fetch keyword struct. */
4568 akl = malloc(sizeof(*akl) + sizeof(struct action_kw) * 2);
4569 if (!akl)
4570 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4571 fcn = malloc(sizeof(*fcn));
4572 if (!fcn)
4573 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4574
4575 /* Fill fcn. */
4576 fcn->name = strdup(name);
4577 if (!fcn->name)
4578 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4579 fcn->function_ref = ref;
4580
4581 /* List head */
4582 akl->list.n = akl->list.p = NULL;
4583
4584 /* End of array. */
4585 memset(&akl->kw[1], 0, sizeof(*akl->kw));
4586
4587 /* action keyword. */
4588 len = strlen("lua.") + strlen(name) + 1;
4589 akl->kw[0].kw = malloc(len);
4590 if (!akl->kw[0].kw)
4591 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4592
4593 snprintf((char *)akl->kw[0].kw, len, "lua.%s", name);
4594
4595 akl->kw[0].match_pfx = 0;
4596 akl->kw[0].private = fcn;
4597 akl->kw[0].parse = action_register_lua;
4598
4599 /* select the action registering point. */
4600 if (strcmp(lua_tostring(L, -1), "tcp-req") == 0)
4601 tcp_req_cont_keywords_register(akl);
4602 else if (strcmp(lua_tostring(L, -1), "tcp-res") == 0)
4603 tcp_res_cont_keywords_register(akl);
4604 else if (strcmp(lua_tostring(L, -1), "http-req") == 0)
4605 http_req_keywords_register(akl);
4606 else if (strcmp(lua_tostring(L, -1), "http-res") == 0)
4607 http_res_keywords_register(akl);
4608 else
4609 WILL_LJMP(luaL_error(L, "lua action environment '%s' is unknown. "
4610 "'tcp-req', 'tcp-res', 'http-req' or 'http-res' "
4611 "are expected.", lua_tostring(L, -1)));
4612
4613 /* pop the environment string. */
4614 lua_pop(L, 1);
4615 }
4616
4617 return 0;
4618}
4619
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004620static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4621 struct proxy *defpx, const char *file, int line,
4622 char **err, unsigned int *timeout)
4623{
4624 const char *error;
4625
4626 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4627 if (error && *error != '\0') {
4628 memprintf(err, "%s: invalid timeout", args[0]);
4629 return -1;
4630 }
4631 return 0;
4632}
4633
4634static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4635 struct proxy *defpx, const char *file, int line,
4636 char **err)
4637{
4638 return hlua_read_timeout(args, section_type, curpx, defpx,
4639 file, line, err, &hlua_timeout_session);
4640}
4641
4642static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4643 struct proxy *defpx, const char *file, int line,
4644 char **err)
4645{
4646 return hlua_read_timeout(args, section_type, curpx, defpx,
4647 file, line, err, &hlua_timeout_task);
4648}
4649
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004650static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4651 struct proxy *defpx, const char *file, int line,
4652 char **err)
4653{
4654 char *error;
4655
4656 hlua_nb_instruction = strtoll(args[1], &error, 10);
4657 if (*error != '\0') {
4658 memprintf(err, "%s: invalid number", args[0]);
4659 return -1;
4660 }
4661 return 0;
4662}
4663
Willy Tarreau32f61e22015-03-18 17:54:59 +01004664static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4665 struct proxy *defpx, const char *file, int line,
4666 char **err)
4667{
4668 char *error;
4669
4670 if (*(args[1]) == 0) {
4671 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4672 return -1;
4673 }
4674 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4675 if (*error != '\0') {
4676 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4677 return -1;
4678 }
4679 return 0;
4680}
4681
4682
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004683/* This function is called by the main configuration key "lua-load". It loads and
4684 * execute an lua file during the parsing of the HAProxy configuration file. It is
4685 * the main lua entry point.
4686 *
4687 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4688 * occured, otherwise it returns 0.
4689 *
4690 * In some error case, LUA set an error message in top of the stack. This function
4691 * returns this error message in the HAProxy logs and pop it from the stack.
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004692 *
4693 * This function can fail with an abort() due to an Lua critical error.
4694 * We are in the configuration parsing process of HAProxy, this abort() is
4695 * tolerated.
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004696 */
4697static int hlua_load(char **args, int section_type, struct proxy *curpx,
4698 struct proxy *defpx, const char *file, int line,
4699 char **err)
4700{
4701 int error;
4702
4703 /* Just load and compile the file. */
4704 error = luaL_loadfile(gL.T, args[1]);
4705 if (error) {
4706 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4707 lua_pop(gL.T, 1);
4708 return -1;
4709 }
4710
4711 /* If no syntax error where detected, execute the code. */
4712 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4713 switch (error) {
4714 case LUA_OK:
4715 break;
4716 case LUA_ERRRUN:
4717 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4718 lua_pop(gL.T, 1);
4719 return -1;
4720 case LUA_ERRMEM:
4721 memprintf(err, "lua out of memory error\n");
4722 return -1;
4723 case LUA_ERRERR:
4724 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4725 lua_pop(gL.T, 1);
4726 return -1;
4727 case LUA_ERRGCMM:
4728 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4729 lua_pop(gL.T, 1);
4730 return -1;
4731 default:
4732 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4733 lua_pop(gL.T, 1);
4734 return -1;
4735 }
4736
4737 return 0;
4738}
4739
4740/* configuration keywords declaration */
4741static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004742 { CFG_GLOBAL, "lua-load", hlua_load },
4743 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4744 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004745 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01004746 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004747 { 0, NULL, NULL },
4748}};
4749
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004750/* This function can fail with an abort() due to an Lua critical error.
4751 * We are in the initialisation process of HAProxy, this abort() is
4752 * tolerated.
4753 */
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004754int hlua_post_init()
4755{
4756 struct hlua_init_function *init;
4757 const char *msg;
4758 enum hlua_exec ret;
4759
4760 list_for_each_entry(init, &hlua_init_functions, l) {
4761 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4762 ret = hlua_ctx_resume(&gL, 0);
4763 switch (ret) {
4764 case HLUA_E_OK:
4765 lua_pop(gL.T, -1);
4766 return 1;
4767 case HLUA_E_AGAIN:
4768 Alert("lua init: yield not allowed.\n");
4769 return 0;
4770 case HLUA_E_ERRMSG:
4771 msg = lua_tostring(gL.T, -1);
4772 Alert("lua init: %s.\n", msg);
4773 return 0;
4774 case HLUA_E_ERR:
4775 default:
4776 Alert("lua init: unknown runtime error.\n");
4777 return 0;
4778 }
4779 }
4780 return 1;
4781}
4782
Willy Tarreau32f61e22015-03-18 17:54:59 +01004783/* The memory allocator used by the Lua stack. <ud> is a pointer to the
4784 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4785 * is the previously allocated size or the kind of object in case of a new
4786 * allocation. <nsize> is the requested new size.
4787 */
4788static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4789{
4790 struct hlua_mem_allocator *zone = ud;
4791
4792 if (nsize == 0) {
4793 /* it's a free */
4794 if (ptr)
4795 zone->allocated -= osize;
4796 free(ptr);
4797 return NULL;
4798 }
4799
4800 if (!ptr) {
4801 /* it's a new allocation */
4802 if (zone->limit && zone->allocated + nsize > zone->limit)
4803 return NULL;
4804
4805 ptr = malloc(nsize);
4806 if (ptr)
4807 zone->allocated += nsize;
4808 return ptr;
4809 }
4810
4811 /* it's a realloc */
4812 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4813 return NULL;
4814
4815 ptr = realloc(ptr, nsize);
4816 if (ptr)
4817 zone->allocated += nsize - osize;
4818 return ptr;
4819}
4820
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004821/* Ithis function can fail with an abort() due to an Lua critical error.
4822 * We are in the initialisation process of HAProxy, this abort() is
4823 * tolerated.
4824 */
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004825void hlua_init(void)
4826{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004827 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004828 int idx;
4829 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004830 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004831 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004832#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004833 struct srv_kw *kw;
4834 int tmp_error;
4835 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01004836 char *args[] = { /* SSL client configuration. */
4837 "ssl",
4838 "verify",
4839 "none",
4840 "force-sslv3",
4841 NULL
4842 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004843#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004844
Willy Tarreau87b09662015-04-03 00:22:06 +02004845 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004846 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4847
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004848 /* Register configuration keywords. */
4849 cfg_register_keywords(&cfg_kws);
4850
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004851 /* Init main lua stack. */
4852 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004853 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004854 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004855 gL.T = luaL_newstate();
4856 hlua_sethlua(&gL);
4857 gL.Tref = LUA_REFNIL;
4858 gL.task = NULL;
4859
Thierry FOURNIERbabae282015-09-17 11:36:37 +02004860 /* From this point, until the end of the initialisation fucntion,
4861 * the Lua function can fail with an abort. We are in the initialisation
4862 * process of HAProxy, this abort() is tolerated.
4863 */
4864
Willy Tarreau32f61e22015-03-18 17:54:59 +01004865 /* change the memory allocators to track memory usage */
4866 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4867
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004868 /* Initialise lua. */
4869 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004870
4871 /*
4872 *
4873 * Create "core" object.
4874 *
4875 */
4876
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004877 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004878 lua_newtable(gL.T);
4879
4880 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004881 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004882 hlua_class_const_int(gL.T, log_levels[i], i);
4883
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004884 /* Register special functions. */
4885 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004886 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004887 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004888 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER8255a752015-09-23 21:03:35 +02004889 hlua_class_function(gL.T, "register_action", hlua_register_action);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004890 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004891 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004892 hlua_class_function(gL.T, "sleep", hlua_sleep);
4893 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004894 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4895 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4896 hlua_class_function(gL.T, "set_map", hlua_set_map);
4897 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004898 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004899 hlua_class_function(gL.T, "log", hlua_log);
4900 hlua_class_function(gL.T, "Debug", hlua_log_debug);
4901 hlua_class_function(gL.T, "Info", hlua_log_info);
4902 hlua_class_function(gL.T, "Warning", hlua_log_warning);
4903 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02004904 hlua_class_function(gL.T, "done", hlua_done);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004905
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004906 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004907
4908 /*
4909 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02004910 * Register class Map
4911 *
4912 */
4913
4914 /* This table entry is the object "Map" base. */
4915 lua_newtable(gL.T);
4916
4917 /* register pattern types. */
4918 for (i=0; i<PAT_MATCH_NUM; i++)
4919 hlua_class_const_int(gL.T, pat_match_names[i], i);
4920
4921 /* register constructor. */
4922 hlua_class_function(gL.T, "new", hlua_map_new);
4923
4924 /* Create and fill the metatable. */
4925 lua_newtable(gL.T);
4926
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02004927 /* Create the __tostring identifier */
4928 lua_pushstring(gL.T, "__tostring");
4929 lua_pushstring(gL.T, CLASS_MAP);
4930 lua_pushcclosure(gL.T, hlua_dump_object, 1);
4931 lua_rawset(gL.T, -3);
4932
Thierry FOURNIER3def3932015-04-07 11:27:54 +02004933 /* Create and fille the __index entry. */
4934 lua_pushstring(gL.T, "__index");
4935 lua_newtable(gL.T);
4936
4937 /* Register . */
4938 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
4939 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
4940
4941 lua_settable(gL.T, -3);
4942
4943 /* Register previous table in the registry with reference and named entry. */
4944 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4945 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4946 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
4947 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4948
4949 /* Assign the metatable to the mai Map object. */
4950 lua_setmetatable(gL.T, -2);
4951
4952 /* Set a name to the table. */
4953 lua_setglobal(gL.T, "Map");
4954
4955 /*
4956 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004957 * Register class Channel
4958 *
4959 */
4960
4961 /* Create and fill the metatable. */
4962 lua_newtable(gL.T);
4963
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02004964 /* Create the __tostring identifier */
4965 lua_pushstring(gL.T, "__tostring");
4966 lua_pushstring(gL.T, CLASS_CHANNEL);
4967 lua_pushcclosure(gL.T, hlua_dump_object, 1);
4968 lua_rawset(gL.T, -3);
4969
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004970 /* Create and fille the __index entry. */
4971 lua_pushstring(gL.T, "__index");
4972 lua_newtable(gL.T);
4973
4974 /* Register . */
4975 hlua_class_function(gL.T, "get", hlua_channel_get);
4976 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4977 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4978 hlua_class_function(gL.T, "set", hlua_channel_set);
4979 hlua_class_function(gL.T, "append", hlua_channel_append);
4980 hlua_class_function(gL.T, "send", hlua_channel_send);
4981 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4982 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4983 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4984
4985 lua_settable(gL.T, -3);
4986
4987 /* Register previous table in the registry with reference and named entry. */
4988 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4989 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4990 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4991
4992 /*
4993 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004994 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004995 *
4996 */
4997
4998 /* Create and fill the metatable. */
4999 lua_newtable(gL.T);
5000
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02005001 /* Create the __tostring identifier */
5002 lua_pushstring(gL.T, "__tostring");
5003 lua_pushstring(gL.T, CLASS_FETCHES);
5004 lua_pushcclosure(gL.T, hlua_dump_object, 1);
5005 lua_rawset(gL.T, -3);
5006
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005007 /* Create and fille the __index entry. */
5008 lua_pushstring(gL.T, "__index");
5009 lua_newtable(gL.T);
5010
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01005011 /* Browse existing fetches and create the associated
5012 * object method.
5013 */
5014 sf = NULL;
5015 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
5016
5017 /* Dont register the keywork if the arguments check function are
5018 * not safe during the runtime.
5019 */
5020 if ((sf->val_args != NULL) &&
5021 (sf->val_args != val_payload_lv) &&
5022 (sf->val_args != val_hdr))
5023 continue;
5024
5025 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
5026 * by an underscore.
5027 */
5028 strncpy(trash.str, sf->kw, trash.size);
5029 trash.str[trash.size - 1] = '\0';
5030 for (p = trash.str; *p; p++)
5031 if (*p == '.' || *p == '-' || *p == '+')
5032 *p = '_';
5033
5034 /* Register the function. */
5035 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01005036 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01005037 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
5038 lua_settable(gL.T, -3);
5039 }
5040
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005041 lua_settable(gL.T, -3);
5042
5043 /* Register previous table in the registry with reference and named entry. */
5044 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5045 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
5046 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
5047
5048 /*
5049 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005050 * Register class Converters
5051 *
5052 */
5053
5054 /* Create and fill the metatable. */
5055 lua_newtable(gL.T);
5056
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02005057 /* Create the __tostring identifier */
5058 lua_pushstring(gL.T, "__tostring");
5059 lua_pushstring(gL.T, CLASS_CONVERTERS);
5060 lua_pushcclosure(gL.T, hlua_dump_object, 1);
5061 lua_rawset(gL.T, -3);
5062
Thierry FOURNIER594afe72015-03-10 23:58:30 +01005063 /* Create and fill the __index entry. */
5064 lua_pushstring(gL.T, "__index");
5065 lua_newtable(gL.T);
5066
5067 /* Browse existing converters and create the associated
5068 * object method.
5069 */
5070 sc = NULL;
5071 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
5072 /* Dont register the keywork if the arguments check function are
5073 * not safe during the runtime.
5074 */
5075 if (sc->val_args != NULL)
5076 continue;
5077
5078 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
5079 * by an underscore.
5080 */
5081 strncpy(trash.str, sc->kw, trash.size);
5082 trash.str[trash.size - 1] = '\0';
5083 for (p = trash.str; *p; p++)
5084 if (*p == '.' || *p == '-' || *p == '+')
5085 *p = '_';
5086
5087 /* Register the function. */
5088 lua_pushstring(gL.T, trash.str);
5089 lua_pushlightuserdata(gL.T, sc);
5090 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
5091 lua_settable(gL.T, -3);
5092 }
5093
5094 lua_settable(gL.T, -3);
5095
5096 /* Register previous table in the registry with reference and named entry. */
5097 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5098 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
5099 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
5100
5101 /*
5102 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005103 * Register class HTTP
5104 *
5105 */
5106
5107 /* Create and fill the metatable. */
5108 lua_newtable(gL.T);
5109
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02005110 /* Create the __tostring identifier */
5111 lua_pushstring(gL.T, "__tostring");
5112 lua_pushstring(gL.T, CLASS_HTTP);
5113 lua_pushcclosure(gL.T, hlua_dump_object, 1);
5114 lua_rawset(gL.T, -3);
5115
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005116 /* Create and fille the __index entry. */
5117 lua_pushstring(gL.T, "__index");
5118 lua_newtable(gL.T);
5119
5120 /* Register Lua functions. */
5121 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
5122 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
5123 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
5124 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
5125 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
5126 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
5127 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
5128 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
5129 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
5130 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
5131
5132 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
5133 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
5134 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
5135 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
5136 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
5137 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02005138 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01005139
5140 lua_settable(gL.T, -3);
5141
5142 /* Register previous table in the registry with reference and named entry. */
5143 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5144 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
5145 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
5146
5147 /*
5148 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005149 * Register class TXN
5150 *
5151 */
5152
5153 /* Create and fill the metatable. */
5154 lua_newtable(gL.T);
5155
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02005156 /* Create the __tostring identifier */
5157 lua_pushstring(gL.T, "__tostring");
5158 lua_pushstring(gL.T, CLASS_TXN);
5159 lua_pushcclosure(gL.T, hlua_dump_object, 1);
5160 lua_rawset(gL.T, -3);
5161
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01005162 /* Create and fille the __index entry. */
5163 lua_pushstring(gL.T, "__index");
5164 lua_newtable(gL.T);
5165
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005166 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01005167 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
5168 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005169 hlua_class_function(gL.T, "set_var", hlua_set_var);
5170 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005171 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005172 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
5173 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
5174 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005175 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
5176 hlua_class_function(gL.T, "log", hlua_txn_log);
5177 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
5178 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
5179 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
5180 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005181
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005182 lua_settable(gL.T, -3);
5183
5184 /* Register previous table in the registry with reference and named entry. */
5185 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5186 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
5187 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005188
5189 /*
5190 *
5191 * Register class Socket
5192 *
5193 */
5194
5195 /* Create and fill the metatable. */
5196 lua_newtable(gL.T);
5197
Thierry FOURNIERd2a3dcc2015-09-18 07:35:06 +02005198 /* Create the __tostring identifier */
5199 lua_pushstring(gL.T, "__tostring");
5200 lua_pushstring(gL.T, CLASS_SOCKET);
5201 lua_pushcclosure(gL.T, hlua_dump_object, 1);
5202 lua_rawset(gL.T, -3);
5203
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005204 /* Create and fille the __index entry. */
5205 lua_pushstring(gL.T, "__index");
5206 lua_newtable(gL.T);
5207
Baptiste Assmann84bb4932015-03-02 21:40:06 +01005208#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005209 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01005210#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005211 hlua_class_function(gL.T, "connect", hlua_socket_connect);
5212 hlua_class_function(gL.T, "send", hlua_socket_send);
5213 hlua_class_function(gL.T, "receive", hlua_socket_receive);
5214 hlua_class_function(gL.T, "close", hlua_socket_close);
5215 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
5216 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
5217 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
5218 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
5219
5220 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5221
5222 /* Register the garbage collector entry. */
5223 lua_pushstring(gL.T, "__gc");
5224 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
5225 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5226
5227 /* Register previous table in the registry with reference and named entry. */
5228 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5229 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5230 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
5231 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
5232
5233 /* Proxy and server configuration initialisation. */
5234 memset(&socket_proxy, 0, sizeof(socket_proxy));
5235 init_new_proxy(&socket_proxy);
5236 socket_proxy.parent = NULL;
5237 socket_proxy.last_change = now.tv_sec;
5238 socket_proxy.id = "LUA-SOCKET";
5239 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
5240 socket_proxy.maxconn = 0;
5241 socket_proxy.accept = NULL;
5242 socket_proxy.options2 |= PR_O2_INDEPSTR;
5243 socket_proxy.srv = NULL;
5244 socket_proxy.conn_retries = 0;
5245 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
5246
5247 /* Init TCP server: unchanged parameters */
5248 memset(&socket_tcp, 0, sizeof(socket_tcp));
5249 socket_tcp.next = NULL;
5250 socket_tcp.proxy = &socket_proxy;
5251 socket_tcp.obj_type = OBJ_TYPE_SERVER;
5252 LIST_INIT(&socket_tcp.actconns);
5253 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005254 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005255 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005256 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005257 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
5258 socket_tcp.last_change = 0;
5259 socket_tcp.id = "LUA-TCP-CONN";
5260 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5261 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5262 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
5263
5264 /* XXX: Copy default parameter from default server,
5265 * but the default server is not initialized.
5266 */
5267 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
5268 socket_tcp.minconn = socket_proxy.defsrv.minconn;
5269 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
5270 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
5271 socket_tcp.onerror = socket_proxy.defsrv.onerror;
5272 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5273 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
5274 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5275 socket_tcp.uweight = socket_proxy.defsrv.iweight;
5276 socket_tcp.iweight = socket_proxy.defsrv.iweight;
5277
5278 socket_tcp.check.status = HCHK_STATUS_INI;
5279 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
5280 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
5281 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
5282 socket_tcp.check.server = &socket_tcp;
5283
5284 socket_tcp.agent.status = HCHK_STATUS_INI;
5285 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
5286 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
5287 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
5288 socket_tcp.agent.server = &socket_tcp;
5289
5290 socket_tcp.xprt = &raw_sock;
5291
5292#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005293 /* Init TCP server: unchanged parameters */
5294 memset(&socket_ssl, 0, sizeof(socket_ssl));
5295 socket_ssl.next = NULL;
5296 socket_ssl.proxy = &socket_proxy;
5297 socket_ssl.obj_type = OBJ_TYPE_SERVER;
5298 LIST_INIT(&socket_ssl.actconns);
5299 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005300 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005301 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005302 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005303 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
5304 socket_ssl.last_change = 0;
5305 socket_ssl.id = "LUA-SSL-CONN";
5306 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5307 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5308 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
5309
5310 /* XXX: Copy default parameter from default server,
5311 * but the default server is not initialized.
5312 */
5313 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
5314 socket_ssl.minconn = socket_proxy.defsrv.minconn;
5315 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
5316 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5317 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5318 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5319 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5320 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5321 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5322 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5323
5324 socket_ssl.check.status = HCHK_STATUS_INI;
5325 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5326 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5327 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5328 socket_ssl.check.server = &socket_ssl;
5329
5330 socket_ssl.agent.status = HCHK_STATUS_INI;
5331 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5332 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5333 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5334 socket_ssl.agent.server = &socket_ssl;
5335
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005336 socket_ssl.use_ssl = 1;
5337 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005338
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005339 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005340 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5341 /*
5342 *
5343 * If the keyword is not known, we can search in the registered
5344 * server keywords. This is usefull to configure special SSL
5345 * features like client certificates and ssl_verify.
5346 *
5347 */
5348 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5349 if (tmp_error != 0) {
5350 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5351 abort(); /* This must be never arrives because the command line
5352 not editable by the user. */
5353 }
5354 idx += kw->skip;
5355 }
5356 }
5357
5358 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005359 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005360#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005361}