blob: cbc0fdedd6cc31c55b6d4e49f86aa33818f9569b [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>
4
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005#include <lauxlib.h>
6#include <lua.h>
7#include <lualib.h>
8
Thierry FOURNIER463119c2015-03-10 00:35:36 +01009#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 503
10#error "Requires Lua 5.3 or later."
Cyril Bontédc0306e2015-03-02 00:08:40 +010011#endif
12
Thierry FOURNIER380d0932015-01-23 14:27:52 +010013#include <ebpttree.h>
14
15#include <common/cfgparse.h>
16
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010017#include <types/connection.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010018#include <types/hlua.h>
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010019#include <types/proto_tcp.h>
Thierry FOURNIER380d0932015-01-23 14:27:52 +010020#include <types/proxy.h>
21
Thierry FOURNIER55da1652015-01-23 11:36:30 +010022#include <proto/arg.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010023#include <proto/channel.h>
Thierry FOURNIER9a819e72015-02-16 20:22:55 +010024#include <proto/hdr_idx.h>
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +010025#include <proto/hlua.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010026#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010027#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010028#include <proto/payload.h>
29#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010030#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010031#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010032#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010033#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020034#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020035#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010036#include <proto/ssl_sock.h>
37#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010038#include <proto/task.h>
39
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010040/* Lua uses longjmp to perform yield or throwing errors. This
41 * macro is used only for identifying the function that can
42 * not return because a longjmp is executed.
43 * __LJMP marks a prototype of hlua file that can use longjmp.
44 * WILL_LJMP() marks an lua function that will use longjmp.
45 * MAY_LJMP() marks an lua function that may use longjmp.
46 */
47#define __LJMP
48#define WILL_LJMP(func) func
49#define MAY_LJMP(func) func
50
Thierry FOURNIER380d0932015-01-23 14:27:52 +010051/* The main Lua execution context. */
52struct hlua gL;
53
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010054/* This is the memory pool containing all the signal structs. These
55 * struct are used to store each requiered signal between two tasks.
56 */
57struct pool_head *pool2_hlua_com;
58
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010059/* Used for Socket connection. */
60static struct proxy socket_proxy;
61static struct server socket_tcp;
62#ifdef USE_OPENSSL
63static struct server socket_ssl;
64#endif
65
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010066/* List head of the function called at the initialisation time. */
67struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
68
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010069/* The following variables contains the reference of the different
70 * Lua classes. These references are useful for identify metadata
71 * associated with an object.
72 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010073static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010074static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010075static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010076static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010077static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +010078static int class_http_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010079
Thierry FOURNIERbd413492015-03-03 16:52:26 +010080/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +020081 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +010082 * short timeout. Lua linked with tasks doesn't have a timeout
83 * because a task may remain alive during all the haproxy execution.
84 */
85static unsigned int hlua_timeout_session = 4000; /* session timeout. */
86static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
87
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010088/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
89 * it is used for preventing infinite loops.
90 *
91 * I test the scheer with an infinite loop containing one incrementation
92 * and one test. I run this loop between 10 seconds, I raise a ceil of
93 * 710M loops from one interrupt each 9000 instructions, so I fix the value
94 * to one interrupt each 10 000 instructions.
95 *
96 * configured | Number of
97 * instructions | loops executed
98 * between two | in milions
99 * forced yields |
100 * ---------------+---------------
101 * 10 | 160
102 * 500 | 670
103 * 1000 | 680
104 * 5000 | 700
105 * 7000 | 700
106 * 8000 | 700
107 * 9000 | 710 <- ceil
108 * 10000 | 710
109 * 100000 | 710
110 * 1000000 | 710
111 *
112 */
113static unsigned int hlua_nb_instruction = 10000;
114
Willy Tarreau32f61e22015-03-18 17:54:59 +0100115/* Descriptor for the memory allocation state. If limit is not null, it will
116 * be enforced on any memory allocation.
117 */
118struct hlua_mem_allocator {
119 size_t allocated;
120 size_t limit;
121};
122
123static struct hlua_mem_allocator hlua_global_allocator;
124
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100125/* These functions converts types between HAProxy internal args or
126 * sample and LUA types. Another function permits to check if the
127 * LUA stack contains arguments according with an required ARG_T
128 * format.
129 */
130static int hlua_arg2lua(lua_State *L, const struct arg *arg);
131static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100132__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
133 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100134static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100135static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100136static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
137
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100138/* Used to check an Lua function type in the stack. It creates and
139 * returns a reference of the function. This function throws an
140 * error if the rgument is not a "function".
141 */
142__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
143{
144 if (!lua_isfunction(L, argno)) {
145 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
146 WILL_LJMP(luaL_argerror(L, argno, msg));
147 }
148 lua_pushvalue(L, argno);
149 return luaL_ref(L, LUA_REGISTRYINDEX);
150}
151
152/* The three following functions are useful for adding entries
153 * in a table. These functions takes a string and respectively an
154 * integer, a string or a function and add it to the table in the
155 * top of the stack.
156 *
157 * These functions throws an error if no more stack size is
158 * available.
159 */
160__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100161 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100162{
163 if (!lua_checkstack(L, 2))
164 WILL_LJMP(luaL_error(L, "full stack"));
165 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100166 lua_pushinteger(L, value);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100167 lua_settable(L, -3);
168}
169__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
170 const char *value)
171{
172 if (!lua_checkstack(L, 2))
173 WILL_LJMP(luaL_error(L, "full stack"));
174 lua_pushstring(L, name);
175 lua_pushstring(L, value);
176 lua_settable(L, -3);
177}
178__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
179 int (*function)(lua_State *L))
180{
181 if (!lua_checkstack(L, 2))
182 WILL_LJMP(luaL_error(L, "full stack"));
183 lua_pushstring(L, name);
184 lua_pushcclosure(L, function, 0);
185 lua_settable(L, -3);
186}
187
188/* This function check the number of arguments available in the
189 * stack. If the number of arguments available is not the same
190 * then <nb> an error is throwed.
191 */
192__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
193{
194 if (lua_gettop(L) == nb)
195 return;
196 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
197}
198
199/* Return true if the data in stack[<ud>] is an object of
200 * type <class_ref>.
201 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100202static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100203{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100204 if (!lua_getmetatable(L, ud))
205 return 0;
206
207 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
208 if (!lua_rawequal(L, -1, -2)) {
209 lua_pop(L, 2);
210 return 0;
211 }
212
213 lua_pop(L, 2);
214 return 1;
215}
216
217/* Return an object of the expected type, or throws an error. */
218__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
219{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100220 void *p;
221
222 /* Check if the stack entry is an array. */
223 if (!lua_istable(L, ud))
224 WILL_LJMP(luaL_argerror(L, ud, NULL));
225 /* Check if the metadata have the expected type. */
226 if (!hlua_metaistype(L, ud, class_ref))
227 WILL_LJMP(luaL_argerror(L, ud, NULL));
228 /* Push on the stack at the entry [0] of the table. */
229 lua_rawgeti(L, ud, 0);
230 /* Check if this entry is userdata. */
231 p = lua_touserdata(L, -1);
232 if (!p)
233 WILL_LJMP(luaL_argerror(L, ud, NULL));
234 /* Remove the entry returned by lua_rawgeti(). */
235 lua_pop(L, 1);
236 /* Return the associated struct. */
237 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100238}
239
240/* This fucntion push an error string prefixed by the file name
241 * and the line number where the error is encountered.
242 */
243static int hlua_pusherror(lua_State *L, const char *fmt, ...)
244{
245 va_list argp;
246 va_start(argp, fmt);
247 luaL_where(L, 1);
248 lua_pushvfstring(L, fmt, argp);
249 va_end(argp);
250 lua_concat(L, 2);
251 return 1;
252}
253
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100254/* This function register a new signal. "lua" is the current lua
255 * execution context. It contains a pointer to the associated task.
256 * "link" is a list head attached to an other task that must be wake
257 * the lua task if an event occurs. This is useful with external
258 * events like TCP I/O or sleep functions. This funcion allocate
259 * memory for the signal.
260 */
261static int hlua_com_new(struct hlua *lua, struct list *link)
262{
263 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
264 if (!com)
265 return 0;
266 LIST_ADDQ(&lua->com, &com->purge_me);
267 LIST_ADDQ(link, &com->wake_me);
268 com->task = lua->task;
269 return 1;
270}
271
272/* This function purge all the pending signals when the LUA execution
273 * is finished. This prevent than a coprocess try to wake a deleted
274 * task. This function remove the memory associated to the signal.
275 */
276static void hlua_com_purge(struct hlua *lua)
277{
278 struct hlua_com *com, *back;
279
280 /* Delete all pending communication signals. */
281 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
282 LIST_DEL(&com->purge_me);
283 LIST_DEL(&com->wake_me);
284 pool_free2(pool2_hlua_com, com);
285 }
286}
287
288/* This function sends signals. It wakes all the tasks attached
289 * to a list head, and remove the signal, and free the used
290 * memory.
291 */
292static void hlua_com_wake(struct list *wake)
293{
294 struct hlua_com *com, *back;
295
296 /* Wake task and delete all pending communication signals. */
297 list_for_each_entry_safe(com, back, wake, wake_me) {
298 LIST_DEL(&com->purge_me);
299 LIST_DEL(&com->wake_me);
300 task_wakeup(com->task, TASK_WOKEN_MSG);
301 pool_free2(pool2_hlua_com, com);
302 }
303}
304
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100305/* This functions is used with sample fetch and converters. It
306 * converts the HAProxy configuration argument in a lua stack
307 * values.
308 *
309 * It takes an array of "arg", and each entry of the array is
310 * converted and pushed in the LUA stack.
311 */
312static int hlua_arg2lua(lua_State *L, const struct arg *arg)
313{
314 switch (arg->type) {
315 case ARGT_SINT:
316 lua_pushinteger(L, arg->data.sint);
317 break;
318
319 case ARGT_UINT:
320 case ARGT_TIME:
321 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100322 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100323 break;
324
325 case ARGT_STR:
326 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
327 break;
328
329 case ARGT_IPV4:
330 case ARGT_IPV6:
331 case ARGT_MSK4:
332 case ARGT_MSK6:
333 case ARGT_FE:
334 case ARGT_BE:
335 case ARGT_TAB:
336 case ARGT_SRV:
337 case ARGT_USR:
338 case ARGT_MAP:
339 default:
340 lua_pushnil(L);
341 break;
342 }
343 return 1;
344}
345
346/* This function take one entrie in an LUA stack at the index "ud",
347 * and try to convert it in an HAProxy argument entry. This is useful
348 * with sample fetch wrappers. The input arguments are gived to the
349 * lua wrapper and converted as arg list by thi function.
350 */
351static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
352{
353 switch (lua_type(L, ud)) {
354
355 case LUA_TNUMBER:
356 case LUA_TBOOLEAN:
357 arg->type = ARGT_SINT;
358 arg->data.sint = lua_tointeger(L, ud);
359 break;
360
361 case LUA_TSTRING:
362 arg->type = ARGT_STR;
363 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
364 break;
365
366 case LUA_TUSERDATA:
367 case LUA_TNIL:
368 case LUA_TTABLE:
369 case LUA_TFUNCTION:
370 case LUA_TTHREAD:
371 case LUA_TLIGHTUSERDATA:
372 arg->type = ARGT_SINT;
373 arg->data.uint = 0;
374 break;
375 }
376 return 1;
377}
378
379/* the following functions are used to convert a struct sample
380 * in Lua type. This useful to convert the return of the
381 * fetchs or converters.
382 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100383static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100384{
385 switch (smp->type) {
386 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100387 case SMP_T_BOOL:
388 case SMP_T_UINT:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100389 lua_pushinteger(L, smp->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100390 break;
391
392 case SMP_T_BIN:
393 case SMP_T_STR:
394 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
395 break;
396
397 case SMP_T_METH:
398 switch (smp->data.meth.meth) {
399 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
400 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
401 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
402 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
403 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
404 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
405 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
406 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
407 case HTTP_METH_OTHER:
408 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
409 break;
410 default:
411 lua_pushnil(L);
412 break;
413 }
414 break;
415
416 case SMP_T_IPV4:
417 case SMP_T_IPV6:
418 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100419 if (sample_casts[smp->type][SMP_T_STR] &&
420 sample_casts[smp->type][SMP_T_STR](smp))
421 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
422 else
423 lua_pushnil(L);
424 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100425 default:
426 lua_pushnil(L);
427 break;
428 }
429 return 1;
430}
431
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100432/* the following functions are used to convert a struct sample
433 * in Lua strings. This is useful to convert the return of the
434 * fetchs or converters.
435 */
436static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
437{
438 switch (smp->type) {
439
440 case SMP_T_BIN:
441 case SMP_T_STR:
442 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
443 break;
444
445 case SMP_T_METH:
446 switch (smp->data.meth.meth) {
447 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
448 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
449 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
450 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
451 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
452 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
453 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
454 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
455 case HTTP_METH_OTHER:
456 lua_pushlstring(L, smp->data.meth.str.str, smp->data.meth.str.len);
457 break;
458 default:
459 lua_pushstring(L, "");
460 break;
461 }
462 break;
463
464 case SMP_T_SINT:
465 case SMP_T_BOOL:
466 case SMP_T_UINT:
467 case SMP_T_IPV4:
468 case SMP_T_IPV6:
469 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
470 if (sample_casts[smp->type][SMP_T_STR] &&
471 sample_casts[smp->type][SMP_T_STR](smp))
472 lua_pushlstring(L, smp->data.str.str, smp->data.str.len);
473 else
474 lua_pushstring(L, "");
475 break;
476 default:
477 lua_pushstring(L, "");
478 break;
479 }
480 return 1;
481}
482
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100483/* the following functions are used to convert an Lua type in a
484 * struct sample. This is useful to provide data from a converter
485 * to the LUA code.
486 */
487static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
488{
489 switch (lua_type(L, ud)) {
490
491 case LUA_TNUMBER:
492 smp->type = SMP_T_SINT;
493 smp->data.sint = lua_tointeger(L, ud);
494 break;
495
496
497 case LUA_TBOOLEAN:
498 smp->type = SMP_T_BOOL;
499 smp->data.uint = lua_toboolean(L, ud);
500 break;
501
502 case LUA_TSTRING:
503 smp->type = SMP_T_STR;
504 smp->flags |= SMP_F_CONST;
505 smp->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.str.len);
506 break;
507
508 case LUA_TUSERDATA:
509 case LUA_TNIL:
510 case LUA_TTABLE:
511 case LUA_TFUNCTION:
512 case LUA_TTHREAD:
513 case LUA_TLIGHTUSERDATA:
514 smp->type = SMP_T_BOOL;
515 smp->data.uint = 0;
516 break;
517 }
518 return 1;
519}
520
521/* This function check the "argp" builded by another conversion function
522 * is in accord with the expected argp defined by the "mask". The fucntion
523 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100524 *
525 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
526 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100527 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100528__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
529 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100530{
531 int min_arg;
532 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100533 struct proxy *px;
534 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100535
536 idx = 0;
537 min_arg = ARGM(mask);
538 mask >>= ARGM_BITS;
539
540 while (1) {
541
542 /* Check oversize. */
543 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100544 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100545 }
546
547 /* Check for mandatory arguments. */
548 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100549 if (idx < min_arg) {
550
551 /* If miss other argument than the first one, we return an error. */
552 if (idx > 0)
553 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
554
555 /* If first argument have a certain type, some default values
556 * may be used. See the function smp_resolve_args().
557 */
558 switch (mask & ARGT_MASK) {
559
560 case ARGT_FE:
561 if (!(p->cap & PR_CAP_FE))
562 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
563 argp[idx].data.prx = p;
564 argp[idx].type = ARGT_FE;
565 argp[idx+1].type = ARGT_STOP;
566 break;
567
568 case ARGT_BE:
569 if (!(p->cap & PR_CAP_BE))
570 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
571 argp[idx].data.prx = p;
572 argp[idx].type = ARGT_BE;
573 argp[idx+1].type = ARGT_STOP;
574 break;
575
576 case ARGT_TAB:
577 argp[idx].data.prx = p;
578 argp[idx].type = ARGT_TAB;
579 argp[idx+1].type = ARGT_STOP;
580 break;
581
582 default:
583 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
584 break;
585 }
586 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100587 return 0;
588 }
589
590 /* Check for exceed the number of requiered argument. */
591 if ((mask & ARGT_MASK) == ARGT_STOP &&
592 argp[idx].type != ARGT_STOP) {
593 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
594 }
595
596 if ((mask & ARGT_MASK) == ARGT_STOP &&
597 argp[idx].type == ARGT_STOP) {
598 return 0;
599 }
600
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100601 /* Convert some argument types. */
602 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100603 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100604 if (argp[idx].type != ARGT_SINT)
605 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
606 argp[idx].type = ARGT_SINT;
607 break;
608
609 case ARGT_UINT:
610 if (argp[idx].type != ARGT_SINT)
611 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
612 argp[idx].type = ARGT_SINT;
613 break;
614
615 case ARGT_TIME:
616 if (argp[idx].type != ARGT_SINT)
617 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
618 argp[idx].type = ARGT_SINT;
619 break;
620
621 case ARGT_SIZE:
622 if (argp[idx].type != ARGT_SINT)
623 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
624 argp[idx].type = ARGT_SINT;
625 break;
626
627 case ARGT_FE:
628 if (argp[idx].type != ARGT_STR)
629 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
630 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
631 trash.str[argp[idx].data.str.len] = 0;
632 argp[idx].data.prx = findproxy(trash.str, PR_CAP_FE);
633 if (!argp[idx].data.prx)
634 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
635 argp[idx].type = ARGT_FE;
636 break;
637
638 case ARGT_BE:
639 if (argp[idx].type != ARGT_STR)
640 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
641 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
642 trash.str[argp[idx].data.str.len] = 0;
643 argp[idx].data.prx = findproxy(trash.str, PR_CAP_BE);
644 if (!argp[idx].data.prx)
645 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
646 argp[idx].type = ARGT_BE;
647 break;
648
649 case ARGT_TAB:
650 if (argp[idx].type != ARGT_STR)
651 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
652 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
653 trash.str[argp[idx].data.str.len] = 0;
654 argp[idx].data.prx = find_stktable(trash.str);
655 if (!argp[idx].data.prx)
656 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
657 argp[idx].type = ARGT_TAB;
658 break;
659
660 case ARGT_SRV:
661 if (argp[idx].type != ARGT_STR)
662 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
663 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
664 trash.str[argp[idx].data.str.len] = 0;
665 sname = strrchr(trash.str, '/');
666 if (sname) {
667 *sname++ = '\0';
668 pname = trash.str;
669 px = findproxy(pname, PR_CAP_BE);
670 if (!px)
671 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
672 }
673 else {
674 sname = trash.str;
675 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100676 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100677 argp[idx].data.srv = findserver(px, sname);
678 if (!argp[idx].data.srv)
679 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
680 argp[idx].type = ARGT_SRV;
681 break;
682
683 case ARGT_IPV4:
684 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
685 trash.str[argp[idx].data.str.len] = 0;
686 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
687 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
688 argp[idx].type = ARGT_IPV4;
689 break;
690
691 case ARGT_MSK4:
692 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
693 trash.str[argp[idx].data.str.len] = 0;
694 if (!str2mask(trash.str, &argp[idx].data.ipv4))
695 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
696 argp[idx].type = ARGT_MSK4;
697 break;
698
699 case ARGT_IPV6:
700 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
701 trash.str[argp[idx].data.str.len] = 0;
702 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
703 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
704 argp[idx].type = ARGT_IPV6;
705 break;
706
707 case ARGT_MSK6:
708 case ARGT_MAP:
709 case ARGT_REG:
710 case ARGT_USR:
711 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100712 break;
713 }
714
715 /* Check for type of argument. */
716 if ((mask & ARGT_MASK) != argp[idx].type) {
717 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
718 arg_type_names[(mask & ARGT_MASK)],
719 arg_type_names[argp[idx].type & ARGT_MASK]);
720 WILL_LJMP(luaL_argerror(L, first + idx, msg));
721 }
722
723 /* Next argument. */
724 mask >>= ARGT_BITS;
725 idx++;
726 }
727}
728
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100729/*
730 * The following functions are used to make correspondance between the the
731 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100732 *
733 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100734 * - hlua_sethlua : create the association between hlua context and lua_state.
735 */
736static inline struct hlua *hlua_gethlua(lua_State *L)
737{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100738 struct hlua **hlua = lua_getextraspace(L);
739 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100740}
741static inline void hlua_sethlua(struct hlua *hlua)
742{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100743 struct hlua **hlua_store = lua_getextraspace(hlua->T);
744 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100745}
746
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100747/* This function is used to send logs. It try to send on screen (stderr)
748 * and on the default syslog server.
749 */
750static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
751{
752 struct tm tm;
753 char *p;
754
755 /* Cleanup the log message. */
756 p = trash.str;
757 for (; *msg != '\0'; msg++, p++) {
758 if (p >= trash.str + trash.size - 1)
759 return;
760 if (isprint(*msg))
761 *p = *msg;
762 else
763 *p = '.';
764 }
765 *p = '\0';
766
767 send_log(px, level, "%s", trash.str);
768 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
769 get_localtime(date.tv_sec, &tm);
770 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
771 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
772 (int)getpid(), trash.str);
773 fflush(stderr);
774 }
775}
776
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100777/* This function just ensure that the yield will be always
778 * returned with a timeout and permit to set some flags
779 */
780__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100781 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100782{
783 struct hlua *hlua = hlua_gethlua(L);
784
785 /* Set the wake timeout. If timeout is required, we set
786 * the expiration time.
787 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100788 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100789
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100790 hlua->flags |= flags;
791
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100792 /* Process the yield. */
793 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
794}
795
Willy Tarreau87b09662015-04-03 00:22:06 +0200796/* This function initialises the Lua environment stored in the stream.
797 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100798 * an LUA coroutine. It can not be use to crete the main LUA context.
799 */
800int hlua_ctx_init(struct hlua *lua, struct task *task)
801{
802 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100803 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100804 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100805 lua->T = lua_newthread(gL.T);
806 if (!lua->T) {
807 lua->Tref = LUA_REFNIL;
808 return 0;
809 }
810 hlua_sethlua(lua);
811 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
812 lua->task = task;
813 return 1;
814}
815
Willy Tarreau87b09662015-04-03 00:22:06 +0200816/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100817 * is destroyed. The destroy also the memory context. The struct "lua"
818 * is not freed.
819 */
820void hlua_ctx_destroy(struct hlua *lua)
821{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100822 if (!lua->T)
823 return;
824
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100825 /* Purge all the pending signals. */
826 hlua_com_purge(lua);
827
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100828 /* The thread is garbage collected by Lua. */
829 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
830 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
831}
832
833/* This function is used to restore the Lua context when a coroutine
834 * fails. This function copy the common memory between old coroutine
835 * and the new coroutine. The old coroutine is destroyed, and its
836 * replaced by the new coroutine.
837 * If the flag "keep_msg" is set, the last entry of the old is assumed
838 * as string error message and it is copied in the new stack.
839 */
840static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
841{
842 lua_State *T;
843 int new_ref;
844
845 /* Renew the main LUA stack doesn't have sense. */
846 if (lua == &gL)
847 return 0;
848
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100849 /* New Lua coroutine. */
850 T = lua_newthread(gL.T);
851 if (!T)
852 return 0;
853
854 /* Copy last error message. */
855 if (keep_msg)
856 lua_xmove(lua->T, T, 1);
857
858 /* Copy data between the coroutines. */
859 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
860 lua_xmove(lua->T, T, 1);
861 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
862
863 /* Destroy old data. */
864 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
865
866 /* The thread is garbage collected by Lua. */
867 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
868
869 /* Fill the struct with the new coroutine values. */
870 lua->Mref = new_ref;
871 lua->T = T;
872 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
873
874 /* Set context. */
875 hlua_sethlua(lua);
876
877 return 1;
878}
879
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100880void hlua_hook(lua_State *L, lua_Debug *ar)
881{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100882 struct hlua *hlua = hlua_gethlua(L);
883
884 /* Lua cannot yield when its returning from a function,
885 * so, we can fix the interrupt hook to 1 instruction,
886 * expecting that the function is finnished.
887 */
888 if (lua_gethookmask(L) & LUA_MASKRET) {
889 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
890 return;
891 }
892
893 /* restore the interrupt condition. */
894 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
895
896 /* If we interrupt the Lua processing in yieldable state, we yield.
897 * If the state is not yieldable, trying yield causes an error.
898 */
899 if (lua_isyieldable(L))
900 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
901
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100902 /* If we cannot yield, update the clock and check the timeout. */
903 tv_update_date(0, 1);
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100904 if (tick_is_expired(hlua->expire, now_ms)) {
905 lua_pushfstring(L, "execution timeout");
906 WILL_LJMP(lua_error(L));
907 }
908
909 /* Try to interrupt the process at the end of the current
910 * unyieldable function.
911 */
912 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100913}
914
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100915/* This function start or resumes the Lua stack execution. If the flag
916 * "yield_allowed" if no set and the LUA stack execution returns a yield
917 * The function return an error.
918 *
919 * The function can returns 4 values:
920 * - HLUA_E_OK : The execution is terminated without any errors.
921 * - HLUA_E_AGAIN : The execution must continue at the next associated
922 * task wakeup.
923 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
924 * the top of the stack.
925 * - HLUA_E_ERR : An error has occured without error message.
926 *
927 * If an error occured, the stack is renewed and it is ready to run new
928 * LUA code.
929 */
930static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
931{
932 int ret;
933 const char *msg;
934
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100935 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100936
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100937 /* If we want to resume the task, then check first the execution timeout.
938 * if it is reached, we can interrupt the Lua processing.
939 */
940 if (tick_is_expired(lua->expire, now_ms))
941 goto timeout_reached;
942
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100943resume_execution:
944
945 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
946 * instructions. it is used for preventing infinite loops.
947 */
948 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
949
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100950 /* Remove all flags except the running flags. */
951 lua->flags = HLUA_RUN;
952
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100953 /* Call the function. */
954 ret = lua_resume(lua->T, gL.T, lua->nargs);
955 switch (ret) {
956
957 case LUA_OK:
958 ret = HLUA_E_OK;
959 break;
960
961 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100962 /* Check if the execution timeout is expired. It it is the case, we
963 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100964 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100965 if (tick_is_expired(lua->expire, now_ms)) {
966
967timeout_reached:
968
969 lua_settop(lua->T, 0); /* Empty the stack. */
970 if (!lua_checkstack(lua->T, 1)) {
971 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100972 break;
973 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100974 lua_pushfstring(lua->T, "execution timeout");
975 ret = HLUA_E_ERRMSG;
976 break;
977 }
978 /* Process the forced yield. if the general yield is not allowed or
979 * if no task were associated this the current Lua execution
980 * coroutine, we resume the execution. Else we want to return in the
981 * scheduler and we want to be waked up again, to continue the
982 * current Lua execution. So we schedule our own task.
983 */
984 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100985 if (!yield_allowed || !lua->task)
986 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100987 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100988 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100989 if (!yield_allowed) {
990 lua_settop(lua->T, 0); /* Empty the stack. */
991 if (!lua_checkstack(lua->T, 1)) {
992 ret = HLUA_E_ERR;
993 break;
994 }
995 lua_pushfstring(lua->T, "yield not allowed");
996 ret = HLUA_E_ERRMSG;
997 break;
998 }
999 ret = HLUA_E_AGAIN;
1000 break;
1001
1002 case LUA_ERRRUN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001003 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001004 if (!lua_checkstack(lua->T, 1)) {
1005 ret = HLUA_E_ERR;
1006 break;
1007 }
1008 msg = lua_tostring(lua->T, -1);
1009 lua_settop(lua->T, 0); /* Empty the stack. */
1010 lua_pop(lua->T, 1);
1011 if (msg)
1012 lua_pushfstring(lua->T, "runtime error: %s", msg);
1013 else
1014 lua_pushfstring(lua->T, "unknown runtime error");
1015 ret = HLUA_E_ERRMSG;
1016 break;
1017
1018 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001019 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001020 lua_settop(lua->T, 0); /* Empty the stack. */
1021 if (!lua_checkstack(lua->T, 1)) {
1022 ret = HLUA_E_ERR;
1023 break;
1024 }
1025 lua_pushfstring(lua->T, "out of memory error");
1026 ret = HLUA_E_ERRMSG;
1027 break;
1028
1029 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001030 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001031 if (!lua_checkstack(lua->T, 1)) {
1032 ret = HLUA_E_ERR;
1033 break;
1034 }
1035 msg = lua_tostring(lua->T, -1);
1036 lua_settop(lua->T, 0); /* Empty the stack. */
1037 lua_pop(lua->T, 1);
1038 if (msg)
1039 lua_pushfstring(lua->T, "message handler error: %s", msg);
1040 else
1041 lua_pushfstring(lua->T, "message handler error");
1042 ret = HLUA_E_ERRMSG;
1043 break;
1044
1045 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001046 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001047 lua_settop(lua->T, 0); /* Empty the stack. */
1048 if (!lua_checkstack(lua->T, 1)) {
1049 ret = HLUA_E_ERR;
1050 break;
1051 }
1052 lua_pushfstring(lua->T, "unknonwn error");
1053 ret = HLUA_E_ERRMSG;
1054 break;
1055 }
1056
1057 switch (ret) {
1058 case HLUA_E_AGAIN:
1059 break;
1060
1061 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001062 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001063 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001064 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001065 break;
1066
1067 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001068 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001069 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001070 hlua_ctx_renew(lua, 0);
1071 break;
1072
1073 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001074 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001075 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001076 break;
1077 }
1078
1079 return ret;
1080}
1081
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001082/* This function is an LUA binding. It provides a function
1083 * for deleting ACL from a referenced ACL file.
1084 */
1085__LJMP static int hlua_del_acl(lua_State *L)
1086{
1087 const char *name;
1088 const char *key;
1089 struct pat_ref *ref;
1090
1091 MAY_LJMP(check_args(L, 2, "del_acl"));
1092
1093 name = MAY_LJMP(luaL_checkstring(L, 1));
1094 key = MAY_LJMP(luaL_checkstring(L, 2));
1095
1096 ref = pat_ref_lookup(name);
1097 if (!ref)
1098 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1099
1100 pat_ref_delete(ref, key);
1101 return 0;
1102}
1103
1104/* This function is an LUA binding. It provides a function
1105 * for deleting map entry from a referenced map file.
1106 */
1107static int hlua_del_map(lua_State *L)
1108{
1109 const char *name;
1110 const char *key;
1111 struct pat_ref *ref;
1112
1113 MAY_LJMP(check_args(L, 2, "del_map"));
1114
1115 name = MAY_LJMP(luaL_checkstring(L, 1));
1116 key = MAY_LJMP(luaL_checkstring(L, 2));
1117
1118 ref = pat_ref_lookup(name);
1119 if (!ref)
1120 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1121
1122 pat_ref_delete(ref, key);
1123 return 0;
1124}
1125
1126/* This function is an LUA binding. It provides a function
1127 * for adding ACL pattern from a referenced ACL file.
1128 */
1129static int hlua_add_acl(lua_State *L)
1130{
1131 const char *name;
1132 const char *key;
1133 struct pat_ref *ref;
1134
1135 MAY_LJMP(check_args(L, 2, "add_acl"));
1136
1137 name = MAY_LJMP(luaL_checkstring(L, 1));
1138 key = MAY_LJMP(luaL_checkstring(L, 2));
1139
1140 ref = pat_ref_lookup(name);
1141 if (!ref)
1142 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1143
1144 if (pat_ref_find_elt(ref, key) == NULL)
1145 pat_ref_add(ref, key, NULL, NULL);
1146 return 0;
1147}
1148
1149/* This function is an LUA binding. It provides a function
1150 * for setting map pattern and sample from a referenced map
1151 * file.
1152 */
1153static int hlua_set_map(lua_State *L)
1154{
1155 const char *name;
1156 const char *key;
1157 const char *value;
1158 struct pat_ref *ref;
1159
1160 MAY_LJMP(check_args(L, 3, "set_map"));
1161
1162 name = MAY_LJMP(luaL_checkstring(L, 1));
1163 key = MAY_LJMP(luaL_checkstring(L, 2));
1164 value = MAY_LJMP(luaL_checkstring(L, 3));
1165
1166 ref = pat_ref_lookup(name);
1167 if (!ref)
1168 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1169
1170 if (pat_ref_find_elt(ref, key) != NULL)
1171 pat_ref_set(ref, key, value, NULL);
1172 else
1173 pat_ref_add(ref, key, value, NULL);
1174 return 0;
1175}
1176
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001177/* A class is a lot of memory that contain data. This data can be a table,
1178 * an integer or user data. This data is associated with a metatable. This
1179 * metatable have an original version registred in the global context with
1180 * the name of the object (_G[<name>] = <metable> ).
1181 *
1182 * A metable is a table that modify the standard behavior of a standard
1183 * access to the associated data. The entries of this new metatable are
1184 * defined as is:
1185 *
1186 * http://lua-users.org/wiki/MetatableEvents
1187 *
1188 * __index
1189 *
1190 * we access an absent field in a table, the result is nil. This is
1191 * true, but it is not the whole truth. Actually, such access triggers
1192 * the interpreter to look for an __index metamethod: If there is no
1193 * such method, as usually happens, then the access results in nil;
1194 * otherwise, the metamethod will provide the result.
1195 *
1196 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1197 * the key does not appear in the table, but the metatable has an __index
1198 * property:
1199 *
1200 * - if the value is a function, the function is called, passing in the
1201 * table and the key; the return value of that function is returned as
1202 * the result.
1203 *
1204 * - if the value is another table, the value of the key in that table is
1205 * asked for and returned (and if it doesn't exist in that table, but that
1206 * table's metatable has an __index property, then it continues on up)
1207 *
1208 * - Use "rawget(myTable,key)" to skip this metamethod.
1209 *
1210 * http://www.lua.org/pil/13.4.1.html
1211 *
1212 * __newindex
1213 *
1214 * Like __index, but control property assignment.
1215 *
1216 * __mode - Control weak references. A string value with one or both
1217 * of the characters 'k' and 'v' which specifies that the the
1218 * keys and/or values in the table are weak references.
1219 *
1220 * __call - Treat a table like a function. When a table is followed by
1221 * parenthesis such as "myTable( 'foo' )" and the metatable has
1222 * a __call key pointing to a function, that function is invoked
1223 * (passing any specified arguments) and the return value is
1224 * returned.
1225 *
1226 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1227 * called, if the metatable for myTable has a __metatable
1228 * key, the value of that key is returned instead of the
1229 * actual metatable.
1230 *
1231 * __tostring - Control string representation. When the builtin
1232 * "tostring( myTable )" function is called, if the metatable
1233 * for myTable has a __tostring property set to a function,
1234 * that function is invoked (passing myTable to it) and the
1235 * return value is used as the string representation.
1236 *
1237 * __len - Control table length. When the table length is requested using
1238 * the length operator ( '#' ), if the metatable for myTable has
1239 * a __len key pointing to a function, that function is invoked
1240 * (passing myTable to it) and the return value used as the value
1241 * of "#myTable".
1242 *
1243 * __gc - Userdata finalizer code. When userdata is set to be garbage
1244 * collected, if the metatable has a __gc field pointing to a
1245 * function, that function is first invoked, passing the userdata
1246 * to it. The __gc metamethod is not called for tables.
1247 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1248 *
1249 * Special metamethods for redefining standard operators:
1250 * http://www.lua.org/pil/13.1.html
1251 *
1252 * __add "+"
1253 * __sub "-"
1254 * __mul "*"
1255 * __div "/"
1256 * __unm "!"
1257 * __pow "^"
1258 * __concat ".."
1259 *
1260 * Special methods for redfining standar relations
1261 * http://www.lua.org/pil/13.2.html
1262 *
1263 * __eq "=="
1264 * __lt "<"
1265 * __le "<="
1266 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001267
1268/*
1269 *
1270 *
1271 * Class Socket
1272 *
1273 *
1274 */
1275
1276__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1277{
1278 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1279}
1280
1281/* This function is the handler called for each I/O on the established
1282 * connection. It is used for notify space avalaible to send or data
1283 * received.
1284 */
1285static void hlua_socket_handler(struct stream_interface *si)
1286{
1287 struct appctx *appctx = objt_appctx(si->end);
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001288 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001289
Willy Tarreau87b09662015-04-03 00:22:06 +02001290 /* Wakeup the main stream if the client connection is closed. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001291 if (!c || channel_output_closed(si_ic(si)) || channel_input_closed(si_oc(si))) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001292 if (appctx->ctx.hlua.socket) {
1293 appctx->ctx.hlua.socket->s = NULL;
1294 appctx->ctx.hlua.socket = NULL;
1295 }
1296 si_shutw(si);
1297 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001298 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001299 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1300 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1301 return;
1302 }
1303
1304 if (!(c->flags & CO_FL_CONNECTED))
1305 return;
1306
1307 /* This function is called after the connect. */
1308 appctx->ctx.hlua.connected = 1;
1309
1310 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001311 if (channel_may_recv(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001312 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1313
1314 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001315 if (channel_is_empty(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001316 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1317}
1318
Willy Tarreau87b09662015-04-03 00:22:06 +02001319/* This function is called when the "struct stream" is destroyed.
1320 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001321 * Wake all the pending signals.
1322 */
1323static void hlua_socket_release(struct stream_interface *si)
1324{
1325 struct appctx *appctx = objt_appctx(si->end);
1326
1327 /* Remove my link in the original object. */
1328 if (appctx->ctx.hlua.socket)
1329 appctx->ctx.hlua.socket->s = NULL;
1330
1331 /* Wake all the task waiting for me. */
1332 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1333 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1334}
1335
1336/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001337 * uses this object. If the stream does not exists, just quit.
1338 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001339 * pending signal can rest in the read and write lists. destroy
1340 * it.
1341 */
1342__LJMP static int hlua_socket_gc(lua_State *L)
1343{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001344 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001345 struct appctx *appctx;
1346
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001347 MAY_LJMP(check_args(L, 1, "__gc"));
1348
1349 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001350 if (!socket->s)
1351 return 0;
1352
Willy Tarreau87b09662015-04-03 00:22:06 +02001353 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001354 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001355 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001356 socket->s = NULL;
1357 appctx->ctx.hlua.socket = NULL;
1358
1359 return 0;
1360}
1361
1362/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001363 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001364 */
1365__LJMP static int hlua_socket_close(lua_State *L)
1366{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001367 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001368 struct appctx *appctx;
1369
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001370 MAY_LJMP(check_args(L, 1, "close"));
1371
1372 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001373 if (!socket->s)
1374 return 0;
1375
Willy Tarreau87b09662015-04-03 00:22:06 +02001376 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001377 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001378 appctx = objt_appctx(socket->s->si[0].end);
1379 appctx->ctx.hlua.socket = NULL;
1380 socket->s = NULL;
1381
1382 return 0;
1383}
1384
1385/* This Lua function assumes that the stack contain three parameters.
1386 * 1 - USERDATA containing a struct socket
1387 * 2 - INTEGER with values of the macro defined below
1388 * If the integer is -1, we must read at most one line.
1389 * If the integer is -2, we ust read all the data until the
1390 * end of the stream.
1391 * If the integer is positive value, we must read a number of
1392 * bytes corresponding to this value.
1393 */
1394#define HLSR_READ_LINE (-1)
1395#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001396__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001397{
1398 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1399 int wanted = lua_tointeger(L, 2);
1400 struct hlua *hlua = hlua_gethlua(L);
1401 struct appctx *appctx;
1402 int len;
1403 int nblk;
1404 char *blk1;
1405 int len1;
1406 char *blk2;
1407 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001408 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001409 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001410
1411 /* Check if this lua stack is schedulable. */
1412 if (!hlua || !hlua->task)
1413 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1414 "'frontend', 'backend' or 'task'"));
1415
1416 /* check for connection closed. If some data where read, return it. */
1417 if (!socket->s)
1418 goto connection_closed;
1419
Willy Tarreau94aa6172015-03-13 14:19:06 +01001420 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001421 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001422 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001423 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001424 if (nblk < 0) /* Connection close. */
1425 goto connection_closed;
1426 if (nblk == 0) /* No data avalaible. */
1427 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001428
1429 /* remove final \r\n. */
1430 if (nblk == 1) {
1431 if (blk1[len1-1] == '\n') {
1432 len1--;
1433 skip_at_end++;
1434 if (blk1[len1-1] == '\r') {
1435 len1--;
1436 skip_at_end++;
1437 }
1438 }
1439 }
1440 else {
1441 if (blk2[len2-1] == '\n') {
1442 len2--;
1443 skip_at_end++;
1444 if (blk2[len2-1] == '\r') {
1445 len2--;
1446 skip_at_end++;
1447 }
1448 }
1449 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001450 }
1451
1452 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001453 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001454 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001455 if (nblk < 0) /* Connection close. */
1456 goto connection_closed;
1457 if (nblk == 0) /* No data avalaible. */
1458 goto connection_empty;
1459 }
1460
1461 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001462 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001463 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001464 if (nblk < 0) /* Connection close. */
1465 goto connection_closed;
1466 if (nblk == 0) /* No data avalaible. */
1467 goto connection_empty;
1468
1469 if (len1 > wanted) {
1470 nblk = 1;
1471 len1 = wanted;
1472 } if (nblk == 2 && len1 + len2 > wanted)
1473 len2 = wanted - len1;
1474 }
1475
1476 len = len1;
1477
1478 luaL_addlstring(&socket->b, blk1, len1);
1479 if (nblk == 2) {
1480 len += len2;
1481 luaL_addlstring(&socket->b, blk2, len2);
1482 }
1483
1484 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001485 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001486
1487 /* Don't wait anything. */
1488 si_update(&socket->s->si[0]);
1489
1490 /* If the pattern reclaim to read all the data
1491 * in the connection, got out.
1492 */
1493 if (wanted == HLSR_READ_ALL)
1494 goto connection_empty;
1495 else if (wanted >= 0 && len < wanted)
1496 goto connection_empty;
1497
1498 /* Return result. */
1499 luaL_pushresult(&socket->b);
1500 return 1;
1501
1502connection_closed:
1503
1504 /* If the buffer containds data. */
1505 if (socket->b.n > 0) {
1506 luaL_pushresult(&socket->b);
1507 return 1;
1508 }
1509 lua_pushnil(L);
1510 lua_pushstring(L, "connection closed.");
1511 return 2;
1512
1513connection_empty:
1514
1515 appctx = objt_appctx(socket->s->si[0].end);
1516 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1517 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001518 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001519 return 0;
1520}
1521
1522/* This Lus function gets two parameters. The first one can be string
1523 * or a number. If the string is "*l", the user require one line. If
1524 * the string is "*a", the user require all the content of the stream.
1525 * If the value is a number, the user require a number of bytes equal
1526 * to the value. The default value is "*l" (a line).
1527 *
1528 * This paraeter with a variable type is converted in integer. This
1529 * integer takes this values:
1530 * -1 : read a line
1531 * -2 : read all the stream
1532 * >0 : amount if bytes.
1533 *
1534 * The second parameter is optinal. It contains a string that must be
1535 * concatenated with the read data.
1536 */
1537__LJMP static int hlua_socket_receive(struct lua_State *L)
1538{
1539 int wanted = HLSR_READ_LINE;
1540 const char *pattern;
1541 int type;
1542 char *error;
1543 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001544 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001545
1546 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1547 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1548
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001549 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001550
1551 /* check for pattern. */
1552 if (lua_gettop(L) >= 2) {
1553 type = lua_type(L, 2);
1554 if (type == LUA_TSTRING) {
1555 pattern = lua_tostring(L, 2);
1556 if (strcmp(pattern, "*a") == 0)
1557 wanted = HLSR_READ_ALL;
1558 else if (strcmp(pattern, "*l") == 0)
1559 wanted = HLSR_READ_LINE;
1560 else {
1561 wanted = strtoll(pattern, &error, 10);
1562 if (*error != '\0')
1563 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1564 }
1565 }
1566 else if (type == LUA_TNUMBER) {
1567 wanted = lua_tointeger(L, 2);
1568 if (wanted < 0)
1569 WILL_LJMP(luaL_error(L, "Unsupported size."));
1570 }
1571 }
1572
1573 /* Set pattern. */
1574 lua_pushinteger(L, wanted);
1575 lua_replace(L, 2);
1576
1577 /* init bufffer, and fiil it wih prefix. */
1578 luaL_buffinit(L, &socket->b);
1579
1580 /* Check prefix. */
1581 if (lua_gettop(L) >= 3) {
1582 if (lua_type(L, 3) != LUA_TSTRING)
1583 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1584 pattern = lua_tolstring(L, 3, &len);
1585 luaL_addlstring(&socket->b, pattern, len);
1586 }
1587
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001588 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001589}
1590
1591/* Write the Lua input string in the output buffer.
1592 * This fucntion returns a yield if no space are available.
1593 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001594static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001595{
1596 struct hlua_socket *socket;
1597 struct hlua *hlua = hlua_gethlua(L);
1598 struct appctx *appctx;
1599 size_t buf_len;
1600 const char *buf;
1601 int len;
1602 int send_len;
1603 int sent;
1604
1605 /* Check if this lua stack is schedulable. */
1606 if (!hlua || !hlua->task)
1607 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1608 "'frontend', 'backend' or 'task'"));
1609
1610 /* Get object */
1611 socket = MAY_LJMP(hlua_checksocket(L, 1));
1612 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001613 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001614
1615 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001616 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001617 lua_pushinteger(L, -1);
1618 return 1;
1619 }
1620
1621 /* Update the input buffer data. */
1622 buf += sent;
1623 send_len = buf_len - sent;
1624
1625 /* All the data are sent. */
1626 if (sent >= buf_len)
1627 return 1; /* Implicitly return the length sent. */
1628
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001629 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1630 * the request buffer if its not required.
1631 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001632 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001633 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001634 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001635 goto hlua_socket_write_yield_return;
1636 }
1637 }
1638
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001639 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001640 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001641 if (len <= 0)
1642 goto hlua_socket_write_yield_return;
1643
1644 /* send data */
1645 if (len < send_len)
1646 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001647 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001648
1649 /* "Not enough space" (-1), "Buffer too little to contain
1650 * the data" (-2) are not expected because the available length
1651 * is tested.
1652 * Other unknown error are also not expected.
1653 */
1654 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001655 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001656 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001657
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001658 MAY_LJMP(hlua_socket_close(L));
1659 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001660 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001661 return 1;
1662 }
1663
1664 /* update buffers. */
1665 si_update(&socket->s->si[0]);
Willy Tarreau94aa6172015-03-13 14:19:06 +01001666 socket->s->req.rex = TICK_ETERNITY;
1667 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001668
1669 /* Update length sent. */
1670 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001671 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001672
1673 /* All the data buffer is sent ? */
1674 if (sent + len >= buf_len)
1675 return 1;
1676
1677hlua_socket_write_yield_return:
1678 appctx = objt_appctx(socket->s->si[0].end);
1679 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1680 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001681 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001682 return 0;
1683}
1684
1685/* This function initiate the send of data. It just check the input
1686 * parameters and push an integer in the Lua stack that contain the
1687 * amount of data writed in the buffer. This is used by the function
1688 * "hlua_socket_write_yield" that can yield.
1689 *
1690 * The Lua function gets between 3 and 4 parameters. The first one is
1691 * the associated object. The second is a string buffer. The third is
1692 * a facultative integer that represents where is the buffer position
1693 * of the start of the data that can send. The first byte is the
1694 * position "1". The default value is "1". The fourth argument is a
1695 * facultative integer that represents where is the buffer position
1696 * of the end of the data that can send. The default is the last byte.
1697 */
1698static int hlua_socket_send(struct lua_State *L)
1699{
1700 int i;
1701 int j;
1702 const char *buf;
1703 size_t buf_len;
1704
1705 /* Check number of arguments. */
1706 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1707 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1708
1709 /* Get the string. */
1710 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1711
1712 /* Get and check j. */
1713 if (lua_gettop(L) == 4) {
1714 j = MAY_LJMP(luaL_checkinteger(L, 4));
1715 if (j < 0)
1716 j = buf_len + j + 1;
1717 if (j > buf_len)
1718 j = buf_len + 1;
1719 lua_pop(L, 1);
1720 }
1721 else
1722 j = buf_len;
1723
1724 /* Get and check i. */
1725 if (lua_gettop(L) == 3) {
1726 i = MAY_LJMP(luaL_checkinteger(L, 3));
1727 if (i < 0)
1728 i = buf_len + i + 1;
1729 if (i > buf_len)
1730 i = buf_len + 1;
1731 lua_pop(L, 1);
1732 } else
1733 i = 1;
1734
1735 /* Check bth i and j. */
1736 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001737 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001738 return 1;
1739 }
1740 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001741 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001742 return 1;
1743 }
1744 if (i == 0)
1745 i = 1;
1746 if (j == 0)
1747 j = 1;
1748
1749 /* Pop the string. */
1750 lua_pop(L, 1);
1751
1752 /* Update the buffer length. */
1753 buf += i - 1;
1754 buf_len = j - i + 1;
1755 lua_pushlstring(L, buf, buf_len);
1756
1757 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001758 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001759
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001760 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001761}
1762
1763#define SOCKET_INFO_EXPANDED_FORM "[0000:0000:0000:0000:0000:0000:0000:0000]:12345"
1764static char _socket_info_expanded_form[] = SOCKET_INFO_EXPANDED_FORM;
1765#define SOCKET_INFO_MAX_LEN (sizeof(_socket_info_expanded_form))
1766__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1767{
1768 static char buffer[SOCKET_INFO_MAX_LEN];
1769 int ret;
1770 int len;
1771 char *p;
1772
1773 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1774 if (ret <= 0) {
1775 lua_pushnil(L);
1776 return 1;
1777 }
1778
1779 if (ret == AF_UNIX) {
1780 lua_pushstring(L, buffer+1);
1781 return 1;
1782 }
1783 else if (ret == AF_INET6) {
1784 buffer[0] = '[';
1785 len = strlen(buffer);
1786 buffer[len] = ']';
1787 len++;
1788 buffer[len] = ':';
1789 len++;
1790 p = buffer;
1791 }
1792 else if (ret == AF_INET) {
1793 p = buffer + 1;
1794 len = strlen(p);
1795 p[len] = ':';
1796 len++;
1797 }
1798 else {
1799 lua_pushnil(L);
1800 return 1;
1801 }
1802
1803 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1804 lua_pushnil(L);
1805 return 1;
1806 }
1807
1808 lua_pushstring(L, p);
1809 return 1;
1810}
1811
1812/* Returns information about the peer of the connection. */
1813__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1814{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001815 struct hlua_socket *socket;
1816 struct connection *conn;
1817
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001818 MAY_LJMP(check_args(L, 1, "getpeername"));
1819
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001820 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001821
1822 /* Check if the tcp object is avalaible. */
1823 if (!socket->s) {
1824 lua_pushnil(L);
1825 return 1;
1826 }
1827
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001828 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001829 if (!conn) {
1830 lua_pushnil(L);
1831 return 1;
1832 }
1833
1834 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1835 unsigned int salen = sizeof(conn->addr.to);
1836 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1837 lua_pushnil(L);
1838 return 1;
1839 }
1840 conn->flags |= CO_FL_ADDR_TO_SET;
1841 }
1842
1843 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1844}
1845
1846/* Returns information about my connection side. */
1847static int hlua_socket_getsockname(struct lua_State *L)
1848{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001849 struct hlua_socket *socket;
1850 struct connection *conn;
1851
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001852 MAY_LJMP(check_args(L, 1, "getsockname"));
1853
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001854 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001855
1856 /* Check if the tcp object is avalaible. */
1857 if (!socket->s) {
1858 lua_pushnil(L);
1859 return 1;
1860 }
1861
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001862 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001863 if (!conn) {
1864 lua_pushnil(L);
1865 return 1;
1866 }
1867
1868 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
1869 unsigned int salen = sizeof(conn->addr.from);
1870 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
1871 lua_pushnil(L);
1872 return 1;
1873 }
1874 conn->flags |= CO_FL_ADDR_FROM_SET;
1875 }
1876
1877 return hlua_socket_info(L, &conn->addr.from);
1878}
1879
1880/* This struct define the applet. */
1881static struct si_applet update_applet = {
1882 .obj_type = OBJ_TYPE_APPLET,
1883 .name = "<LUA_TCP>",
1884 .fct = hlua_socket_handler,
1885 .release = hlua_socket_release,
1886};
1887
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001888__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001889{
1890 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1891 struct hlua *hlua = hlua_gethlua(L);
1892 struct appctx *appctx;
1893
1894 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001895 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001896 lua_pushnil(L);
1897 lua_pushstring(L, "Can't connect");
1898 return 2;
1899 }
1900
1901 appctx = objt_appctx(socket->s->si[0].end);
1902
1903 /* Check for connection established. */
1904 if (appctx->ctx.hlua.connected) {
1905 lua_pushinteger(L, 1);
1906 return 1;
1907 }
1908
1909 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1910 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001911 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001912 return 0;
1913}
1914
1915/* This function fail or initite the connection. */
1916__LJMP static int hlua_socket_connect(struct lua_State *L)
1917{
1918 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001919 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001920 const char *ip;
1921 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001922 struct hlua *hlua;
1923 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001924
1925 MAY_LJMP(check_args(L, 3, "connect"));
1926
1927 /* Get args. */
1928 socket = MAY_LJMP(hlua_checksocket(L, 1));
1929 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001930 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001931
Willy Tarreau350f4872014-11-28 14:42:25 +01001932 conn = si_alloc_conn(&socket->s->si[1], 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001933 if (!conn)
1934 WILL_LJMP(luaL_error(L, "connect: internal error"));
1935
1936 /* Parse ip address. */
1937 conn->addr.to.ss_family = AF_UNSPEC;
1938 if (!str2ip2(ip, &conn->addr.to, 0))
1939 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
1940
1941 /* Set port. */
1942 if (conn->addr.to.ss_family == AF_INET)
1943 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
1944 else if (conn->addr.to.ss_family == AF_INET6)
1945 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
1946
1947 /* it is important not to call the wakeup function directly but to
1948 * pass through task_wakeup(), because this one knows how to apply
1949 * priorities to tasks.
1950 */
1951 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
1952
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01001953 hlua = hlua_gethlua(L);
1954 appctx = objt_appctx(socket->s->si[0].end);
1955 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1956 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001957 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001958
1959 return 0;
1960}
1961
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001962#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001963__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
1964{
1965 struct hlua_socket *socket;
1966
1967 MAY_LJMP(check_args(L, 3, "connect_ssl"));
1968 socket = MAY_LJMP(hlua_checksocket(L, 1));
1969 socket->s->target = &socket_ssl.obj_type;
1970 return MAY_LJMP(hlua_socket_connect(L));
1971}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01001972#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001973
1974__LJMP static int hlua_socket_setoption(struct lua_State *L)
1975{
1976 return 0;
1977}
1978
1979__LJMP static int hlua_socket_settimeout(struct lua_State *L)
1980{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001981 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001982 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001983
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001984 MAY_LJMP(check_args(L, 2, "settimeout"));
1985
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001986 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001987 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001988
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001989 socket->s->req.rto = tmout;
1990 socket->s->req.wto = tmout;
1991 socket->s->res.rto = tmout;
1992 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001993
1994 return 0;
1995}
1996
1997__LJMP static int hlua_socket_new(lua_State *L)
1998{
1999 struct hlua_socket *socket;
2000 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002001 struct session *sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002002
2003 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002004 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002005 hlua_pusherror(L, "socket: full stack");
2006 goto out_fail_conf;
2007 }
2008
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002009 /* Create the object: obj[0] = userdata. */
2010 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002011 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002012 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002013 memset(socket, 0, sizeof(*socket));
2014
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002015 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002016 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002017 hlua_pusherror(L, "socket: uninitialized pools.");
2018 goto out_fail_conf;
2019 }
2020
Willy Tarreau87b09662015-04-03 00:22:06 +02002021 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002022 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2023 lua_setmetatable(L, -2);
2024
2025 /*
2026 *
2027 * Get memory for the request.
2028 *
2029 */
Willy Tarreau15b5e142015-04-04 14:38:25 +02002030 sess = pool_alloc2(pool2_session);
2031 if (!sess) {
Willy Tarreaufeb76402015-04-03 14:10:06 +02002032 hlua_pusherror(L, "socket: out of memory");
2033 goto out_fail_conf;
2034 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002035
Willy Tarreau7ea671b2015-04-04 14:46:56 +02002036 sess->accept_date = date; /* user-visible date for logging */
2037 sess->tv_accept = now; /* corrected date for internal use */
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002038 memset(sess->stkctr, 0, sizeof(sess->stkctr));
2039
Willy Tarreau87b09662015-04-03 00:22:06 +02002040 socket->s = pool_alloc2(pool2_stream);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002041 if (!socket->s) {
2042 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002043 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002044 }
2045
Willy Tarreau15b5e142015-04-04 14:38:25 +02002046 socket->s->sess = sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002047 socket->s->task = task_new();
2048 if (!socket->s->task) {
2049 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002050 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002051 }
2052
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002053 socket->s->req.buf = pool_alloc2(pool2_buffer);
2054 if (!socket->s->req.buf) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002055 hlua_pusherror(L, "socket: out of memory");
2056 goto out_fail_req_buf;
2057 }
2058
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002059 socket->s->res.buf = pool_alloc2(pool2_buffer);
2060 if (!socket->s->res.buf) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002061 hlua_pusherror(L, "socket: out of memory");
2062 goto out_fail_rep_buf;
2063 }
2064
Willy Tarreau87b09662015-04-03 00:22:06 +02002065 /* Configura empty Lua for the stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002066 socket->s->hlua.T = NULL;
2067 socket->s->hlua.Tref = LUA_REFNIL;
2068 socket->s->hlua.Mref = LUA_REFNIL;
2069 socket->s->hlua.nargs = 0;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01002070 socket->s->hlua.flags = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002071 LIST_INIT(&socket->s->hlua.com);
2072
Willy Tarreau87b09662015-04-03 00:22:06 +02002073 /* stream initialisation. */
2074 stream_init_srv_conn(socket->s);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002075
2076 /*
2077 *
2078 * Configure the associated task.
2079 *
2080 */
2081
Willy Tarreau87b09662015-04-03 00:22:06 +02002082 /* This is the dedicated function to process the stream. This function
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002083 * is able to establish the conection, process the timeouts, etc ...
2084 */
Willy Tarreau87b09662015-04-03 00:22:06 +02002085 socket->s->task->process = process_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086
Willy Tarreau87b09662015-04-03 00:22:06 +02002087 /* Back reference to stream. This is used by process_stream(). */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002088 socket->s->task->context = socket->s;
2089
2090 /* The priority of the task is normal. */
2091 socket->s->task->nice = 0;
2092
2093 /* Init the next run to eternity. Later in this function, this task is
2094 * waked.
2095 */
2096 socket->s->task->expire = TICK_ETERNITY;
2097
2098 /*
2099 *
2100 * Initialize the attached buffers
2101 *
2102 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002103 socket->s->req.buf->size = global.tune.bufsize;
2104 socket->s->res.buf->size = global.tune.bufsize;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002105
2106 /*
2107 *
2108 * Initialize channels.
2109 *
2110 */
2111
2112 /* This function reset the struct. It must be called
2113 * before the configuration.
2114 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002115 channel_init(&socket->s->req);
2116 channel_init(&socket->s->res);
Willy Tarreauef573c02014-11-28 14:17:09 +01002117 socket->s->res.flags |= CF_ISRESP;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002118
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002119 socket->s->req.analysers = 0;
2120 socket->s->req.rto = socket_proxy.timeout.client;
2121 socket->s->req.wto = socket_proxy.timeout.server;
2122 socket->s->req.rex = TICK_ETERNITY;
2123 socket->s->req.wex = TICK_ETERNITY;
2124 socket->s->req.analyse_exp = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002125
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002126 socket->s->res.analysers = 0;
2127 socket->s->res.rto = socket_proxy.timeout.server;
2128 socket->s->res.wto = socket_proxy.timeout.client;
2129 socket->s->res.rex = TICK_ETERNITY;
2130 socket->s->res.wex = TICK_ETERNITY;
2131 socket->s->res.analyse_exp = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002132
2133 /*
2134 *
Willy Tarreau87b09662015-04-03 00:22:06 +02002135 * Configure the stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002136 *
2137 */
2138
Willy Tarreau87b09662015-04-03 00:22:06 +02002139 /* The stream dont have listener. The listener is used with real
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002140 * proxies.
2141 */
Willy Tarreaufb0afa72015-04-03 14:46:27 +02002142 socket->s->sess->listener = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002143
2144 /* The flags are initialized to 0. Values are setted later. */
2145 socket->s->flags = 0;
2146
Willy Tarreau87b09662015-04-03 00:22:06 +02002147 /* Assign the configured proxy to the new stream. */
Willy Tarreaue36cbcb2015-04-03 15:40:56 +02002148 socket->s->sess->fe = &socket_proxy;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002149 socket->s->be = &socket_proxy;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002150
2151 /* XXX: Set namy variables */
2152 socket->s->store_count = 0;
2153 memset(socket->s->stkctr, 0, sizeof(socket->s->stkctr));
2154
2155 /* Configure logs. */
2156 socket->s->logs.logwait = 0;
2157 socket->s->logs.level = 0;
Willy Tarreau7ea671b2015-04-04 14:46:56 +02002158
2159 socket->s->logs.accept_date = sess->accept_date; /* user-visible date for logging */
2160 socket->s->logs.tv_accept = sess->tv_accept; /* corrected date for internal use */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002161 socket->s->do_log = NULL;
2162
2163 /* Function used if an error is occured. */
2164 socket->s->srv_error = default_srv_error;
2165
2166 /* Init the list of buffers. */
2167 LIST_INIT(&socket->s->buffer_wait);
2168
2169 /* Dont configure the unique ID. */
2170 socket->s->uniq_id = 0;
2171 socket->s->unique_id = NULL;
2172
2173 /* XXX: ? */
2174 socket->s->pend_pos = NULL;
Willy Tarreaucb7dd012015-04-03 22:16:32 +02002175 socket->s->req_cap = NULL;
2176 socket->s->res_cap = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002177
2178 /* XXX: See later. */
Willy Tarreaueee5b512015-04-03 23:46:31 +02002179 socket->s->txn = NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180
2181 /* Configure "left" stream interface as applet. This "si" produce
2182 * and use the data received from the server. The applet is initialized
2183 * and is attached to the stream interface.
2184 */
2185
2186 /* The data producer is already connected. It is the applet. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002187 socket->s->req.flags = CF_READ_ATTACHED;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002188
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002189 channel_auto_connect(&socket->s->req); /* don't wait to establish connection */
2190 channel_auto_close(&socket->s->req); /* let the producer forward close requests */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002191
Willy Tarreaua5f5d8d2014-11-28 11:26:07 +01002192 socket->s->si[0].flags = SI_FL_NONE;
Willy Tarreau819d3322014-11-28 12:12:34 +01002193 si_reset(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002194 si_set_state(&socket->s->si[0], SI_ST_EST); /* connection established (resource exists) */
2195
2196 appctx = stream_int_register_handler(&socket->s->si[0], &update_applet);
2197 if (!appctx)
2198 goto out_fail_conn1;
2199 appctx->ctx.hlua.socket = socket;
2200 appctx->ctx.hlua.connected = 0;
Willy Tarreau40606ab2015-04-03 18:08:29 +02002201 socket->s->sess->origin = &appctx->obj_type;
2202
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002203 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2204 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
2205
2206 /* Configure "right" stream interface. this "si" is used to connect
2207 * and retrieve data from the server. The connection is initialized
2208 * with the "struct server".
2209 */
Willy Tarreaua5f5d8d2014-11-28 11:26:07 +01002210 socket->s->si[1].flags = SI_FL_ISBACK;
Willy Tarreau819d3322014-11-28 12:12:34 +01002211 si_reset(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002212 si_set_state(&socket->s->si[1], SI_ST_INI);
2213 socket->s->si[1].conn_retries = socket_proxy.conn_retries;
2214
2215 /* Force destination server. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02002216 socket->s->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002217 socket->s->target = &socket_tcp.obj_type;
2218
Willy Tarreau87b09662015-04-03 00:22:06 +02002219 /* This stream is added to te lists of alive streams. */
2220 LIST_ADDQ(&streams, &socket->s->list);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002221
2222 /* XXX: I think that this list is used by stats. */
2223 LIST_INIT(&socket->s->back_refs);
2224
2225 /* Update statistics counters. */
2226 socket_proxy.feconn++; /* beconn will be increased later */
2227 jobs++;
2228 totalconn++;
2229
2230 /* Return yield waiting for connection. */
2231 return 1;
2232
2233out_fail_conn1:
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002234 pool_free2(pool2_buffer, socket->s->res.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002235out_fail_rep_buf:
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002236 pool_free2(pool2_buffer, socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002237out_fail_req_buf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002238 task_free(socket->s->task);
Willy Tarreaufeb76402015-04-03 14:10:06 +02002239out_fail_task:
Willy Tarreau87b09662015-04-03 00:22:06 +02002240 pool_free2(pool2_stream, socket->s);
Willy Tarreaufeb76402015-04-03 14:10:06 +02002241out_fail_stream:
Willy Tarreau11c36242015-04-04 15:54:03 +02002242 session_free(sess);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002243out_fail_conf:
2244 WILL_LJMP(lua_error(L));
2245 return 0;
2246}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002247
2248/*
2249 *
2250 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002251 * Class Channel
2252 *
2253 *
2254 */
2255
2256/* Returns the struct hlua_channel join to the class channel in the
2257 * stack entry "ud" or throws an argument error.
2258 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002259__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002260{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002261 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002262}
2263
Willy Tarreau47860ed2015-03-10 14:07:50 +01002264/* Pushes the channel onto the top of the stack. If the stask does not have a
2265 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002266 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002267static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002268{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002269 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002270 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002271 return 0;
2272
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002273 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002274 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002275 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002276
2277 /* Pop a class sesison metatable and affect it to the userdata. */
2278 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2279 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002280 return 1;
2281}
2282
2283/* Duplicate all the data present in the input channel and put it
2284 * in a string LUA variables. Returns -1 and push a nil value in
2285 * the stack if the channel is closed and all the data are consumed,
2286 * returns 0 if no data are available, otherwise it returns the length
2287 * of the builded string.
2288 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002289static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002290{
2291 char *blk1;
2292 char *blk2;
2293 int len1;
2294 int len2;
2295 int ret;
2296 luaL_Buffer b;
2297
Willy Tarreau47860ed2015-03-10 14:07:50 +01002298 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002299 if (unlikely(ret == 0))
2300 return 0;
2301
2302 if (unlikely(ret < 0)) {
2303 lua_pushnil(L);
2304 return -1;
2305 }
2306
2307 luaL_buffinit(L, &b);
2308 luaL_addlstring(&b, blk1, len1);
2309 if (unlikely(ret == 2))
2310 luaL_addlstring(&b, blk2, len2);
2311 luaL_pushresult(&b);
2312
2313 if (unlikely(ret == 2))
2314 return len1 + len2;
2315 return len1;
2316}
2317
2318/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2319 * a yield. This function keep the data in the buffer.
2320 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002321__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002322{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002323 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002324
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002325 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2326
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002327 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002328 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002329 return 1;
2330}
2331
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002332/* Check arguments for the function "hlua_channel_dup_yield". */
2333__LJMP static int hlua_channel_dup(lua_State *L)
2334{
2335 MAY_LJMP(check_args(L, 1, "dup"));
2336 MAY_LJMP(hlua_checkchannel(L, 1));
2337 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2338}
2339
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002340/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2341 * a yield. This function consumes the data in the buffer. It returns
2342 * a string containing the data or a nil pointer if no data are available
2343 * and the channel is closed.
2344 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002345__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002346{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002347 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002348 int ret;
2349
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002350 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002351
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002352 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002353 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002354 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002355
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002356 if (unlikely(ret == -1))
2357 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002358
Willy Tarreau47860ed2015-03-10 14:07:50 +01002359 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002360 return 1;
2361}
2362
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002363/* Check arguments for the fucntion "hlua_channel_get_yield". */
2364__LJMP static int hlua_channel_get(lua_State *L)
2365{
2366 MAY_LJMP(check_args(L, 1, "get"));
2367 MAY_LJMP(hlua_checkchannel(L, 1));
2368 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2369}
2370
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002371/* This functions consumes and returns one line. If the channel is closed,
2372 * and the last data does not contains a final '\n', the data are returned
2373 * without the final '\n'. When no more data are avalaible, it returns nil
2374 * value.
2375 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002376__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002377{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002378 char *blk1;
2379 char *blk2;
2380 int len1;
2381 int len2;
2382 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002383 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002384 int ret;
2385 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002386
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002387 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2388
Willy Tarreau47860ed2015-03-10 14:07:50 +01002389 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002390 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002391 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002392
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002393 if (ret == -1) {
2394 lua_pushnil(L);
2395 return 1;
2396 }
2397
2398 luaL_buffinit(L, &b);
2399 luaL_addlstring(&b, blk1, len1);
2400 len = len1;
2401 if (unlikely(ret == 2)) {
2402 luaL_addlstring(&b, blk2, len2);
2403 len += len2;
2404 }
2405 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002406 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002407 return 1;
2408}
2409
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002410/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2411__LJMP static int hlua_channel_getline(lua_State *L)
2412{
2413 MAY_LJMP(check_args(L, 1, "getline"));
2414 MAY_LJMP(hlua_checkchannel(L, 1));
2415 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2416}
2417
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002418/* This function takes a string as input, and append it at the
2419 * input side of channel. If the data is too big, but a space
2420 * is probably available after sending some data, the function
2421 * yield. If the data is bigger than the buffer, or if the
2422 * channel is closed, it returns -1. otherwise, it returns the
2423 * amount of data writed.
2424 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002425__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002426{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002427 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002428 size_t len;
2429 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2430 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2431 int ret;
2432 int max;
2433
Willy Tarreau47860ed2015-03-10 14:07:50 +01002434 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002435 if (max > len - l)
2436 max = len - l;
2437
Willy Tarreau47860ed2015-03-10 14:07:50 +01002438 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002439 if (ret == -2 || ret == -3) {
2440 lua_pushinteger(L, -1);
2441 return 1;
2442 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002443 if (ret == -1) {
2444 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002445 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002446 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002447 l += ret;
2448 lua_pop(L, 1);
2449 lua_pushinteger(L, l);
2450
Willy Tarreau47860ed2015-03-10 14:07:50 +01002451 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2452 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002453 /* There are no space avalaible, and the output buffer is empty.
2454 * in this case, we cannot add more data, so we cannot yield,
2455 * we return the amount of copyied data.
2456 */
2457 return 1;
2458 }
2459 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002460 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002461 return 1;
2462}
2463
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002464/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002465 * of the writed string, or -1 if the channel is closed or if the
2466 * buffer size is too little for the data.
2467 */
2468__LJMP static int hlua_channel_append(lua_State *L)
2469{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002470 size_t len;
2471
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002472 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002473 MAY_LJMP(hlua_checkchannel(L, 1));
2474 MAY_LJMP(luaL_checklstring(L, 2, &len));
2475 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002476 lua_pushinteger(L, 0);
2477
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002478 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002479}
2480
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002481/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002482 * his process by cleaning the buffer. The result is a replacement
2483 * of the current data. It returns the length of the writed string,
2484 * or -1 if the channel is closed or if the buffer size is too
2485 * little for the data.
2486 */
2487__LJMP static int hlua_channel_set(lua_State *L)
2488{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002489 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002490
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002491 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002492 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002493 lua_pushinteger(L, 0);
2494
Willy Tarreau47860ed2015-03-10 14:07:50 +01002495 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002496
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002497 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002498}
2499
2500/* Append data in the output side of the buffer. This data is immediatly
2501 * sent. The fcuntion returns the ammount of data writed. If the buffer
2502 * cannot contains the data, the function yield. The function returns -1
2503 * if the channel is closed.
2504 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002505__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002506{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002507 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002508 size_t len;
2509 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2510 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2511 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002512 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002513
Willy Tarreau47860ed2015-03-10 14:07:50 +01002514 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002515 lua_pushinteger(L, -1);
2516 return 1;
2517 }
2518
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002519 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2520 * the request buffer if its not required.
2521 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002522 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002523 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002524 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002525 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002526 }
2527 }
2528
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002529 /* the writed data will be immediatly sent, so we can check
2530 * the avalaible space without taking in account the reserve.
2531 * The reserve is guaranted for the processing of incoming
2532 * data, because the buffer will be flushed.
2533 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002534 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002535
2536 /* If there are no space avalaible, and the output buffer is empty.
2537 * in this case, we cannot add more data, so we cannot yield,
2538 * we return the amount of copyied data.
2539 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002540 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002541 return 1;
2542
2543 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002544 if (max > len - l)
2545 max = len - l;
2546
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002547 /* The buffer avalaible size may be not contiguous. This test
2548 * detects a non contiguous buffer and realign it.
2549 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002550 if (bi_space_for_replace(chn->buf) < max)
2551 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002552
2553 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002554 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002555
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002556 /* buffer replace considers that the input part is filled.
2557 * so, I must forward these new data in the output part.
2558 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002559 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002560
2561 l += max;
2562 lua_pop(L, 1);
2563 lua_pushinteger(L, l);
2564
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002565 /* If 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 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002569 max = chn->buf->size - buffer_len(chn->buf);
2570 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002571 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002572
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002573 if (l < len) {
2574 /* If we are waiting for space in the response buffer, we
2575 * must set the flag WAKERESWR. This flag required the task
2576 * wake up if any activity is detected on the response buffer.
2577 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002578 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002579 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002580 else
2581 HLUA_SET_WAKEREQWR(hlua);
2582 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002583 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002584
2585 return 1;
2586}
2587
2588/* Just a wraper of "_hlua_channel_send". This wrapper permits
2589 * yield the LUA process, and resume it without checking the
2590 * input arguments.
2591 */
2592__LJMP static int hlua_channel_send(lua_State *L)
2593{
2594 MAY_LJMP(check_args(L, 2, "send"));
2595 lua_pushinteger(L, 0);
2596
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002597 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002598}
2599
2600/* This function forward and amount of butes. The data pass from
2601 * the input side of the buffer to the output side, and can be
2602 * forwarded. This function never fails.
2603 *
2604 * The Lua function takes an amount of bytes to be forwarded in
2605 * imput. It returns the number of bytes forwarded.
2606 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002607__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002608{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002609 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002610 int len;
2611 int l;
2612 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002613 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002614
2615 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2616 len = MAY_LJMP(luaL_checkinteger(L, 2));
2617 l = MAY_LJMP(luaL_checkinteger(L, -1));
2618
2619 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002620 if (max > chn->buf->i)
2621 max = chn->buf->i;
2622 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002623 l += max;
2624
2625 lua_pop(L, 1);
2626 lua_pushinteger(L, l);
2627
2628 /* Check if it miss bytes to forward. */
2629 if (l < len) {
2630 /* The the input channel or the output channel are closed, we
2631 * must return the amount of data forwarded.
2632 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002633 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002634 return 1;
2635
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002636 /* If we are waiting for space data in the response buffer, we
2637 * must set the flag WAKERESWR. This flag required the task
2638 * wake up if any activity is detected on the response buffer.
2639 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002640 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002641 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002642 else
2643 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002644
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002645 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002646 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002647 }
2648
2649 return 1;
2650}
2651
2652/* Just check the input and prepare the stack for the previous
2653 * function "hlua_channel_forward_yield"
2654 */
2655__LJMP static int hlua_channel_forward(lua_State *L)
2656{
2657 MAY_LJMP(check_args(L, 2, "forward"));
2658 MAY_LJMP(hlua_checkchannel(L, 1));
2659 MAY_LJMP(luaL_checkinteger(L, 2));
2660
2661 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002662 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002663}
2664
2665/* Just returns the number of bytes available in the input
2666 * side of the buffer. This function never fails.
2667 */
2668__LJMP static int hlua_channel_get_in_len(lua_State *L)
2669{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002670 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002671
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002672 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002673 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002674 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002675 return 1;
2676}
2677
2678/* Just returns the number of bytes available in the output
2679 * side of the buffer. This function never fails.
2680 */
2681__LJMP static int hlua_channel_get_out_len(lua_State *L)
2682{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002683 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002684
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002685 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002686 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002687 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002688 return 1;
2689}
2690
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002691/*
2692 *
2693 *
2694 * Class Fetches
2695 *
2696 *
2697 */
2698
2699/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002700 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002701 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002702__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002703{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002704 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002705}
2706
2707/* This function creates and push in the stack a fetch object according
2708 * with a current TXN.
2709 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002710static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002711{
Willy Tarreau7073c472015-04-06 11:15:40 +02002712 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002713
2714 /* Check stack size. */
2715 if (!lua_checkstack(L, 3))
2716 return 0;
2717
2718 /* Create the object: obj[0] = userdata.
2719 * Note that the base of the Fetches object is the
2720 * transaction object.
2721 */
2722 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002723 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002724 lua_rawseti(L, -2, 0);
2725
Willy Tarreau7073c472015-04-06 11:15:40 +02002726 hsmp->s = txn->s;
2727 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002728 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002729
2730 /* Pop a class sesison metatable and affect it to the userdata. */
2731 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2732 lua_setmetatable(L, -2);
2733
2734 return 1;
2735}
2736
2737/* This function is an LUA binding. It is called with each sample-fetch.
2738 * It uses closure argument to store the associated sample-fetch. It
2739 * returns only one argument or throws an error. An error is thrown
2740 * only if an error is encountered during the argument parsing. If
2741 * the "sample-fetch" function fails, nil is returned.
2742 */
2743__LJMP static int hlua_run_sample_fetch(lua_State *L)
2744{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002745 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002746 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002747 struct arg args[ARGM_NBARGS + 1];
2748 int i;
2749 struct sample smp;
2750
2751 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002752 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002753
2754 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002755 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002756
2757 /* Get extra arguments. */
2758 for (i = 0; i < lua_gettop(L) - 1; i++) {
2759 if (i >= ARGM_NBARGS)
2760 break;
2761 hlua_lua2arg(L, i + 2, &args[i]);
2762 }
2763 args[i].type = ARGT_STOP;
2764
2765 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002766 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002767
2768 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002769 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002770 lua_pushfstring(L, "error in arguments");
2771 WILL_LJMP(lua_error(L));
2772 }
2773
2774 /* Initialise the sample. */
2775 memset(&smp, 0, sizeof(smp));
2776
2777 /* Run the sample fetch process. */
Willy Tarreau192252e2015-04-04 01:47:55 +02002778 if (!f->process(hsmp->p, hsmp->s->sess, hsmp->s, 0, args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002779 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002780 lua_pushstring(L, "");
2781 else
2782 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002783 return 1;
2784 }
2785
2786 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002787 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002788 hlua_smp2lua_str(L, &smp);
2789 else
2790 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002791 return 1;
2792}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002793
2794/*
2795 *
2796 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002797 * Class Converters
2798 *
2799 *
2800 */
2801
2802/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002803 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002804 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002805__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002806{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002807 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002808}
2809
2810/* This function creates and push in the stack a Converters object
2811 * according with a current TXN.
2812 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002813static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002814{
Willy Tarreau7073c472015-04-06 11:15:40 +02002815 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002816
2817 /* Check stack size. */
2818 if (!lua_checkstack(L, 3))
2819 return 0;
2820
2821 /* Create the object: obj[0] = userdata.
2822 * Note that the base of the Converters object is the
2823 * same than the TXN object.
2824 */
2825 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002826 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002827 lua_rawseti(L, -2, 0);
2828
Willy Tarreau7073c472015-04-06 11:15:40 +02002829 hsmp->s = txn->s;
2830 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002831 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002832
Willy Tarreau87b09662015-04-03 00:22:06 +02002833 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002834 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2835 lua_setmetatable(L, -2);
2836
2837 return 1;
2838}
2839
2840/* This function is an LUA binding. It is called with each converter.
2841 * It uses closure argument to store the associated converter. It
2842 * returns only one argument or throws an error. An error is thrown
2843 * only if an error is encountered during the argument parsing. If
2844 * the converter function function fails, nil is returned.
2845 */
2846__LJMP static int hlua_run_sample_conv(lua_State *L)
2847{
Willy Tarreauda5f1082015-04-06 11:17:13 +02002848 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002849 struct sample_conv *conv;
2850 struct arg args[ARGM_NBARGS + 1];
2851 int i;
2852 struct sample smp;
2853
2854 /* Get closure arguments. */
2855 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2856
2857 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002858 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002859
2860 /* Get extra arguments. */
2861 for (i = 0; i < lua_gettop(L) - 2; i++) {
2862 if (i >= ARGM_NBARGS)
2863 break;
2864 hlua_lua2arg(L, i + 3, &args[i]);
2865 }
2866 args[i].type = ARGT_STOP;
2867
2868 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002869 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002870
2871 /* Run the special args checker. */
2872 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2873 hlua_pusherror(L, "error in arguments");
2874 WILL_LJMP(lua_error(L));
2875 }
2876
2877 /* Initialise the sample. */
2878 if (!hlua_lua2smp(L, 2, &smp)) {
2879 hlua_pusherror(L, "error in the input argument");
2880 WILL_LJMP(lua_error(L));
2881 }
2882
2883 /* Apply expected cast. */
2884 if (!sample_casts[smp.type][conv->in_type]) {
2885 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
2886 smp_to_type[smp.type], smp_to_type[conv->in_type]);
2887 WILL_LJMP(lua_error(L));
2888 }
2889 if (sample_casts[smp.type][conv->in_type] != c_none &&
2890 !sample_casts[smp.type][conv->in_type](&smp)) {
2891 hlua_pusherror(L, "error during the input argument casting");
2892 WILL_LJMP(lua_error(L));
2893 }
2894
2895 /* Run the sample conversion process. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002896 if (!conv->process(hsmp->s, args, &smp, conv->private)) {
2897 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002898 lua_pushstring(L, "");
2899 else
2900 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002901 return 1;
2902 }
2903
2904 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002905 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002906 hlua_smp2lua_str(L, &smp);
2907 else
2908 hlua_smp2lua(L, &smp);
2909 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002910}
2911
2912/*
2913 *
2914 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002915 * Class HTTP
2916 *
2917 *
2918 */
2919
2920/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002921 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002922 */
2923__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
2924{
2925 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
2926}
2927
2928/* This function creates and push in the stack a HTTP object
2929 * according with a current TXN.
2930 */
2931static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
2932{
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002933 struct hlua_txn *htxn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002934
2935 /* Check stack size. */
2936 if (!lua_checkstack(L, 3))
2937 return 0;
2938
2939 /* Create the object: obj[0] = userdata.
2940 * Note that the base of the Converters object is the
2941 * same than the TXN object.
2942 */
2943 lua_newtable(L);
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002944 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002945 lua_rawseti(L, -2, 0);
2946
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002947 htxn->s = txn->s;
2948 htxn->p = txn->p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002949
Willy Tarreau87b09662015-04-03 00:22:06 +02002950 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002951 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
2952 lua_setmetatable(L, -2);
2953
2954 return 1;
2955}
2956
2957/* This function creates ans returns an array of HTTP headers.
2958 * This function does not fails. It is used as wrapper with the
2959 * 2 following functions.
2960 */
2961__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
2962{
2963 const char *cur_ptr, *cur_next, *p;
2964 int old_idx, cur_idx;
2965 struct hdr_idx_elem *cur_hdr;
2966 const char *hn, *hv;
2967 int hnl, hvl;
2968
2969 /* Create the table. */
2970 lua_newtable(L);
2971
Willy Tarreaueee5b512015-04-03 23:46:31 +02002972 if (!htxn->s->txn)
2973 return 1;
2974
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002975 /* Build array of headers. */
2976 old_idx = 0;
Willy Tarreaueee5b512015-04-03 23:46:31 +02002977 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002978
2979 while (1) {
Willy Tarreaueee5b512015-04-03 23:46:31 +02002980 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002981 if (!cur_idx)
2982 break;
2983 old_idx = cur_idx;
2984
Willy Tarreaueee5b512015-04-03 23:46:31 +02002985 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002986 cur_ptr = cur_next;
2987 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
2988
2989 /* Now we have one full header at cur_ptr of len cur_hdr->len,
2990 * and the next header starts at cur_next. We'll check
2991 * this header in the list as well as against the default
2992 * rule.
2993 */
2994
2995 /* look for ': *'. */
2996 hn = cur_ptr;
2997 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
2998 if (p >= cur_ptr+cur_hdr->len)
2999 continue;
3000 hnl = p - hn;
3001 p++;
3002 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3003 p++;
3004 if (p >= cur_ptr+cur_hdr->len)
3005 continue;
3006 hv = p;
3007 hvl = cur_ptr+cur_hdr->len-p;
3008
3009 /* Push values in the table. */
3010 lua_pushlstring(L, hn, hnl);
3011 lua_pushlstring(L, hv, hvl);
3012 lua_settable(L, -3);
3013 }
3014
3015 return 1;
3016}
3017
3018__LJMP static int hlua_http_req_get_headers(lua_State *L)
3019{
3020 struct hlua_txn *htxn;
3021
3022 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3023 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3024
Willy Tarreaueee5b512015-04-03 23:46:31 +02003025 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003026}
3027
3028__LJMP static int hlua_http_res_get_headers(lua_State *L)
3029{
3030 struct hlua_txn *htxn;
3031
3032 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3033 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3034
Willy Tarreaueee5b512015-04-03 23:46:31 +02003035 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003036}
3037
3038/* This function replace full header, or just a value in
3039 * the request or in the response. It is a wrapper fir the
3040 * 4 following functions.
3041 */
3042__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3043 struct http_msg *msg, int action)
3044{
3045 size_t name_len;
3046 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3047 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3048 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3049 struct my_regex re;
3050
3051 if (!regex_comp(reg, &re, 1, 1, NULL))
3052 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3053
3054 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3055 regex_free(&re);
3056 return 0;
3057}
3058
3059__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3060{
3061 struct hlua_txn *htxn;
3062
3063 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3064 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3065
Willy Tarreaueee5b512015-04-03 23:46:31 +02003066 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, HTTP_REQ_ACT_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003067}
3068
3069__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3070{
3071 struct hlua_txn *htxn;
3072
3073 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3074 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3075
Willy Tarreaueee5b512015-04-03 23:46:31 +02003076 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, HTTP_RES_ACT_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003077}
3078
3079__LJMP static int hlua_http_req_rep_val(lua_State *L)
3080{
3081 struct hlua_txn *htxn;
3082
3083 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3084 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3085
Willy Tarreaueee5b512015-04-03 23:46:31 +02003086 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, HTTP_REQ_ACT_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003087}
3088
3089__LJMP static int hlua_http_res_rep_val(lua_State *L)
3090{
3091 struct hlua_txn *htxn;
3092
3093 MAY_LJMP(check_args(L, 4, "res_rep_val"));
3094 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3095
Willy Tarreaueee5b512015-04-03 23:46:31 +02003096 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, HTTP_RES_ACT_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003097}
3098
3099/* This function deletes all the occurences of an header.
3100 * It is a wrapper for the 2 following functions.
3101 */
3102__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3103{
3104 size_t len;
3105 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3106 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003107 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003108
3109 ctx.idx = 0;
3110 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3111 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3112 return 0;
3113}
3114
3115__LJMP static int hlua_http_req_del_hdr(lua_State *L)
3116{
3117 struct hlua_txn *htxn;
3118
3119 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3120 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3121
Willy Tarreaueee5b512015-04-03 23:46:31 +02003122 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003123}
3124
3125__LJMP static int hlua_http_res_del_hdr(lua_State *L)
3126{
3127 struct hlua_txn *htxn;
3128
3129 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3130 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3131
Willy Tarreaueee5b512015-04-03 23:46:31 +02003132 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003133}
3134
3135/* This function adds an header. It is a wrapper used by
3136 * the 2 following functions.
3137 */
3138__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3139{
3140 size_t name_len;
3141 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3142 size_t value_len;
3143 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3144 char *p;
3145
3146 /* Check length. */
3147 trash.len = value_len + name_len + 2;
3148 if (trash.len > trash.size)
3149 return 0;
3150
3151 /* Creates the header string. */
3152 p = trash.str;
3153 memcpy(p, name, name_len);
3154 p += name_len;
3155 *p = ':';
3156 p++;
3157 *p = ' ';
3158 p++;
3159 memcpy(p, value, value_len);
3160
Willy Tarreaueee5b512015-04-03 23:46:31 +02003161 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003162 trash.str, trash.len) != 0);
3163
3164 return 0;
3165}
3166
3167__LJMP static int hlua_http_req_add_hdr(lua_State *L)
3168{
3169 struct hlua_txn *htxn;
3170
3171 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3172 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3173
Willy Tarreaueee5b512015-04-03 23:46:31 +02003174 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003175}
3176
3177__LJMP static int hlua_http_res_add_hdr(lua_State *L)
3178{
3179 struct hlua_txn *htxn;
3180
3181 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3182 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3183
Willy Tarreaueee5b512015-04-03 23:46:31 +02003184 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003185}
3186
3187static int hlua_http_req_set_hdr(lua_State *L)
3188{
3189 struct hlua_txn *htxn;
3190
3191 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3192 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3193
Willy Tarreaueee5b512015-04-03 23:46:31 +02003194 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3195 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003196}
3197
3198static int hlua_http_res_set_hdr(lua_State *L)
3199{
3200 struct hlua_txn *htxn;
3201
3202 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3203 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3204
Willy Tarreaueee5b512015-04-03 23:46:31 +02003205 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3206 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003207}
3208
3209/* This function set the method. */
3210static int hlua_http_req_set_meth(lua_State *L)
3211{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003212 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003213 size_t name_len;
3214 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003215
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003216 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003217 return 1;
3218}
3219
3220/* This function set the method. */
3221static int hlua_http_req_set_path(lua_State *L)
3222{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003223 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003224 size_t name_len;
3225 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003226 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003227 return 1;
3228}
3229
3230/* This function set the query-string. */
3231static int hlua_http_req_set_query(lua_State *L)
3232{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003233 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003234 size_t name_len;
3235 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003236
3237 /* Check length. */
3238 if (name_len > trash.size - 1) {
3239 lua_pushboolean(L, 0);
3240 return 1;
3241 }
3242
3243 /* Add the mark question as prefix. */
3244 chunk_reset(&trash);
3245 trash.str[trash.len++] = '?';
3246 memcpy(trash.str + trash.len, name, name_len);
3247 trash.len += name_len;
3248
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003249 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003250 return 1;
3251}
3252
3253/* This function set the uri. */
3254static int hlua_http_req_set_uri(lua_State *L)
3255{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003256 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003257 size_t name_len;
3258 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003259
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003260 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003261 return 1;
3262}
3263
3264/*
3265 *
3266 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003267 * Class TXN
3268 *
3269 *
3270 */
3271
3272/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003273 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003274 */
3275__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3276{
3277 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3278}
3279
Willy Tarreau59551662015-03-10 14:23:13 +01003280__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003281{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003282 struct hlua *hlua;
3283
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003284 MAY_LJMP(check_args(L, 2, "set_priv"));
3285
Willy Tarreau87b09662015-04-03 00:22:06 +02003286 /* It is useles to retrieve the stream, but this function
3287 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003288 */
3289 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003290 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003291
3292 /* Remove previous value. */
3293 if (hlua->Mref != -1)
3294 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3295
3296 /* Get and store new value. */
3297 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3298 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3299
3300 return 0;
3301}
3302
Willy Tarreau59551662015-03-10 14:23:13 +01003303__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003304{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003305 struct hlua *hlua;
3306
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003307 MAY_LJMP(check_args(L, 1, "get_priv"));
3308
Willy Tarreau87b09662015-04-03 00:22:06 +02003309 /* It is useles to retrieve the stream, but this function
3310 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003311 */
3312 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003313 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003314
3315 /* Push configuration index in the stack. */
3316 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3317
3318 return 1;
3319}
3320
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003321/* Create stack entry containing a class TXN. This function
3322 * return 0 if the stack does not contains free slots,
3323 * otherwise it returns 1.
3324 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003325static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003326{
Willy Tarreaude491382015-04-06 11:04:28 +02003327 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003328
3329 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003330 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003331 return 0;
3332
3333 /* NOTE: The allocation never fails. The failure
3334 * throw an error, and the function never returns.
3335 * if the throw is not avalaible, the process is aborted.
3336 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003337 /* Create the object: obj[0] = userdata. */
3338 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02003339 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003340 lua_rawseti(L, -2, 0);
3341
Willy Tarreaude491382015-04-06 11:04:28 +02003342 htxn->s = s;
3343 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003344
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003345 /* Create the "f" field that contains a list of fetches. */
3346 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02003347 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003348 return 0;
3349 lua_settable(L, -3);
3350
3351 /* Create the "sf" field that contains a list of stringsafe fetches. */
3352 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02003353 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003354 return 0;
3355 lua_settable(L, -3);
3356
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003357 /* Create the "c" field that contains a list of converters. */
3358 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02003359 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003360 return 0;
3361 lua_settable(L, -3);
3362
3363 /* Create the "sc" field that contains a list of stringsafe converters. */
3364 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02003365 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003366 return 0;
3367 lua_settable(L, -3);
3368
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003369 /* Create the "req" field that contains the request channel object. */
3370 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003371 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003372 return 0;
3373 lua_settable(L, -3);
3374
3375 /* Create the "res" field that contains the response channel object. */
3376 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003377 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003378 return 0;
3379 lua_settable(L, -3);
3380
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003381 /* Creates the HTTP object is the current proxy allows http. */
3382 lua_pushstring(L, "http");
3383 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02003384 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003385 return 0;
3386 }
3387 else
3388 lua_pushnil(L);
3389 lua_settable(L, -3);
3390
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003391 /* Pop a class sesison metatable and affect it to the userdata. */
3392 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3393 lua_setmetatable(L, -2);
3394
3395 return 1;
3396}
3397
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003398__LJMP static int hlua_txn_deflog(lua_State *L)
3399{
3400 const char *msg;
3401 struct hlua_txn *htxn;
3402
3403 MAY_LJMP(check_args(L, 2, "deflog"));
3404 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3405 msg = MAY_LJMP(luaL_checkstring(L, 2));
3406
3407 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3408 return 0;
3409}
3410
3411__LJMP static int hlua_txn_log(lua_State *L)
3412{
3413 int level;
3414 const char *msg;
3415 struct hlua_txn *htxn;
3416
3417 MAY_LJMP(check_args(L, 3, "log"));
3418 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3419 level = MAY_LJMP(luaL_checkinteger(L, 2));
3420 msg = MAY_LJMP(luaL_checkstring(L, 3));
3421
3422 if (level < 0 || level >= NB_LOG_LEVELS)
3423 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3424
3425 hlua_sendlog(htxn->s->be, level, msg);
3426 return 0;
3427}
3428
3429__LJMP static int hlua_txn_log_debug(lua_State *L)
3430{
3431 const char *msg;
3432 struct hlua_txn *htxn;
3433
3434 MAY_LJMP(check_args(L, 2, "Debug"));
3435 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3436 msg = MAY_LJMP(luaL_checkstring(L, 2));
3437 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3438 return 0;
3439}
3440
3441__LJMP static int hlua_txn_log_info(lua_State *L)
3442{
3443 const char *msg;
3444 struct hlua_txn *htxn;
3445
3446 MAY_LJMP(check_args(L, 2, "Info"));
3447 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3448 msg = MAY_LJMP(luaL_checkstring(L, 2));
3449 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3450 return 0;
3451}
3452
3453__LJMP static int hlua_txn_log_warning(lua_State *L)
3454{
3455 const char *msg;
3456 struct hlua_txn *htxn;
3457
3458 MAY_LJMP(check_args(L, 2, "Warning"));
3459 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3460 msg = MAY_LJMP(luaL_checkstring(L, 2));
3461 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3462 return 0;
3463}
3464
3465__LJMP static int hlua_txn_log_alert(lua_State *L)
3466{
3467 const char *msg;
3468 struct hlua_txn *htxn;
3469
3470 MAY_LJMP(check_args(L, 2, "Alert"));
3471 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3472 msg = MAY_LJMP(luaL_checkstring(L, 2));
3473 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3474 return 0;
3475}
3476
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003477__LJMP static int hlua_txn_set_loglevel(lua_State *L)
3478{
3479 struct hlua_txn *htxn;
3480 int ll;
3481
3482 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3483 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3484 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3485
3486 if (ll < 0 || ll > 7)
3487 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3488
3489 htxn->s->logs.level = ll;
3490 return 0;
3491}
3492
3493__LJMP static int hlua_txn_set_tos(lua_State *L)
3494{
3495 struct hlua_txn *htxn;
3496 struct connection *cli_conn;
3497 int tos;
3498
3499 MAY_LJMP(check_args(L, 2, "set_tos"));
3500 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3501 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3502
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003503 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003504 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3505
3506 return 0;
3507}
3508
3509__LJMP static int hlua_txn_set_mark(lua_State *L)
3510{
3511#ifdef SO_MARK
3512 struct hlua_txn *htxn;
3513 struct connection *cli_conn;
3514 int mark;
3515
3516 MAY_LJMP(check_args(L, 2, "set_mark"));
3517 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3518 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3519
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003520 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02003521 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003522#endif
3523 return 0;
3524}
3525
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003526/* This function is an Lua binding that send pending data
3527 * to the client, and close the stream interface.
3528 */
3529__LJMP static int hlua_txn_close(lua_State *L)
3530{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003531 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01003532 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003533
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003534 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003535 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003536
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003537 ic = &htxn->s->req;
3538 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01003539
3540 channel_abort(ic);
3541 channel_auto_close(ic);
3542 channel_erase(ic);
3543 channel_auto_read(oc);
3544 channel_auto_close(oc);
3545 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003546
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003547 return 0;
3548}
3549
3550__LJMP static int hlua_log(lua_State *L)
3551{
3552 int level;
3553 const char *msg;
3554
3555 MAY_LJMP(check_args(L, 2, "log"));
3556 level = MAY_LJMP(luaL_checkinteger(L, 1));
3557 msg = MAY_LJMP(luaL_checkstring(L, 2));
3558
3559 if (level < 0 || level >= NB_LOG_LEVELS)
3560 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3561
3562 hlua_sendlog(NULL, level, msg);
3563 return 0;
3564}
3565
3566__LJMP static int hlua_log_debug(lua_State *L)
3567{
3568 const char *msg;
3569
3570 MAY_LJMP(check_args(L, 1, "debug"));
3571 msg = MAY_LJMP(luaL_checkstring(L, 1));
3572 hlua_sendlog(NULL, LOG_DEBUG, msg);
3573 return 0;
3574}
3575
3576__LJMP static int hlua_log_info(lua_State *L)
3577{
3578 const char *msg;
3579
3580 MAY_LJMP(check_args(L, 1, "info"));
3581 msg = MAY_LJMP(luaL_checkstring(L, 1));
3582 hlua_sendlog(NULL, LOG_INFO, msg);
3583 return 0;
3584}
3585
3586__LJMP static int hlua_log_warning(lua_State *L)
3587{
3588 const char *msg;
3589
3590 MAY_LJMP(check_args(L, 1, "warning"));
3591 msg = MAY_LJMP(luaL_checkstring(L, 1));
3592 hlua_sendlog(NULL, LOG_WARNING, msg);
3593 return 0;
3594}
3595
3596__LJMP static int hlua_log_alert(lua_State *L)
3597{
3598 const char *msg;
3599
3600 MAY_LJMP(check_args(L, 1, "alert"));
3601 msg = MAY_LJMP(luaL_checkstring(L, 1));
3602 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003603 return 0;
3604}
3605
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003606__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003607{
3608 int wakeup_ms = lua_tointeger(L, -1);
3609 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003610 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003611 return 0;
3612}
3613
3614__LJMP static int hlua_sleep(lua_State *L)
3615{
3616 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003617 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003618
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003619 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003620
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003621 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003622 wakeup_ms = tick_add(now_ms, delay);
3623 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003624
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003625 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3626 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003627}
3628
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003629__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003630{
3631 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003632 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003633
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003634 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003635
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003636 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003637 wakeup_ms = tick_add(now_ms, delay);
3638 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003639
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003640 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3641 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003642}
3643
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003644/* This functionis an LUA binding. it permits to give back
3645 * the hand at the HAProxy scheduler. It is used when the
3646 * LUA processing consumes a lot of time.
3647 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003648__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003649{
3650 return 0;
3651}
3652
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003653__LJMP static int hlua_yield(lua_State *L)
3654{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003655 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3656 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003657}
3658
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003659/* This function change the nice of the currently executed
3660 * task. It is used set low or high priority at the current
3661 * task.
3662 */
Willy Tarreau59551662015-03-10 14:23:13 +01003663__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003664{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003665 struct hlua *hlua;
3666 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003667
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003668 MAY_LJMP(check_args(L, 1, "set_nice"));
3669 hlua = hlua_gethlua(L);
3670 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003671
3672 /* If he task is not set, I'm in a start mode. */
3673 if (!hlua || !hlua->task)
3674 return 0;
3675
3676 if (nice < -1024)
3677 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003678 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003679 nice = 1024;
3680
3681 hlua->task->nice = nice;
3682 return 0;
3683}
3684
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003685/* This function is used as a calback of a task. It is called by the
3686 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3687 * return an E_AGAIN signal, the emmiter of this signal must set a
3688 * signal to wake the task.
3689 */
3690static struct task *hlua_process_task(struct task *task)
3691{
3692 struct hlua *hlua = task->context;
3693 enum hlua_exec status;
3694
3695 /* We need to remove the task from the wait queue before executing
3696 * the Lua code because we don't know if it needs to wait for
3697 * another timer or not in the case of E_AGAIN.
3698 */
3699 task_delete(task);
3700
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003701 /* If it is the first call to the task, we must initialize the
3702 * execution timeouts.
3703 */
3704 if (!HLUA_IS_RUNNING(hlua))
3705 hlua->expire = tick_add(now_ms, hlua_timeout_task);
3706
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003707 /* Execute the Lua code. */
3708 status = hlua_ctx_resume(hlua, 1);
3709
3710 switch (status) {
3711 /* finished or yield */
3712 case HLUA_E_OK:
3713 hlua_ctx_destroy(hlua);
3714 task_delete(task);
3715 task_free(task);
3716 break;
3717
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003718 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3719 if (hlua->wake_time != TICK_ETERNITY)
3720 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003721 break;
3722
3723 /* finished with error. */
3724 case HLUA_E_ERRMSG:
3725 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3726 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3727 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3728 hlua_ctx_destroy(hlua);
3729 task_delete(task);
3730 task_free(task);
3731 break;
3732
3733 case HLUA_E_ERR:
3734 default:
3735 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3736 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3737 Alert("Lua task: unknown error.\n");
3738 hlua_ctx_destroy(hlua);
3739 task_delete(task);
3740 task_free(task);
3741 break;
3742 }
3743 return NULL;
3744}
3745
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003746/* This function is an LUA binding that register LUA function to be
3747 * executed after the HAProxy configuration parsing and before the
3748 * HAProxy scheduler starts. This function expect only one LUA
3749 * argument that is a function. This function returns nothing, but
3750 * throws if an error is encountered.
3751 */
3752__LJMP static int hlua_register_init(lua_State *L)
3753{
3754 struct hlua_init_function *init;
3755 int ref;
3756
3757 MAY_LJMP(check_args(L, 1, "register_init"));
3758
3759 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3760
3761 init = malloc(sizeof(*init));
3762 if (!init)
3763 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3764
3765 init->function_ref = ref;
3766 LIST_ADDQ(&hlua_init_functions, &init->l);
3767 return 0;
3768}
3769
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003770/* This functio is an LUA binding. It permits to register a task
3771 * executed in parallel of the main HAroxy activity. The task is
3772 * created and it is set in the HAProxy scheduler. It can be called
3773 * from the "init" section, "post init" or during the runtime.
3774 *
3775 * Lua prototype:
3776 *
3777 * <none> core.register_task(<function>)
3778 */
3779static int hlua_register_task(lua_State *L)
3780{
3781 struct hlua *hlua;
3782 struct task *task;
3783 int ref;
3784
3785 MAY_LJMP(check_args(L, 1, "register_task"));
3786
3787 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3788
3789 hlua = malloc(sizeof(*hlua));
3790 if (!hlua)
3791 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3792
3793 task = task_new();
3794 task->context = hlua;
3795 task->process = hlua_process_task;
3796
3797 if (!hlua_ctx_init(hlua, task))
3798 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3799
3800 /* Restore the function in the stack. */
3801 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3802 hlua->nargs = 0;
3803
3804 /* Schedule task. */
3805 task_schedule(task, now_ms);
3806
3807 return 0;
3808}
3809
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003810/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3811 * doesn't allow "yield" functions because the HAProxy engine cannot
3812 * resume converters.
3813 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003814static int hlua_sample_conv_wrapper(struct stream *stream, const struct arg *arg_p,
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003815 struct sample *smp, void *private)
3816{
3817 struct hlua_function *fcn = (struct hlua_function *)private;
3818
Willy Tarreau87b09662015-04-03 00:22:06 +02003819 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003820 * Lua context can be not initialized. This behavior
3821 * permits to save performances because a systematic
3822 * Lua initialization cause 5% performances loss.
3823 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003824 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
3825 send_log(stream->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003826 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3827 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3828 return 0;
3829 }
3830
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003831 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003832 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003833 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003834 if (!lua_checkstack(stream->hlua.T, 1)) {
3835 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003836 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3837 Alert("Lua converter '%s': full stack.\n", fcn->name);
3838 return 0;
3839 }
3840
3841 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003842 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003843
3844 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003845 if (!lua_checkstack(stream->hlua.T, 1)) {
3846 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003847 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3848 Alert("Lua converter '%s': full stack.\n", fcn->name);
3849 return 0;
3850 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003851 hlua_smp2lua(stream->hlua.T, smp);
3852 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003853
3854 /* push keywords in the stack. */
3855 if (arg_p) {
3856 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02003857 if (!lua_checkstack(stream->hlua.T, 1)) {
3858 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003859 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3860 Alert("Lua converter '%s': full stack.\n", fcn->name);
3861 return 0;
3862 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003863 hlua_arg2lua(stream->hlua.T, arg_p);
3864 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003865 }
3866 }
3867
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003868 /* We must initialize the execution timeouts. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003869 stream->hlua.expire = tick_add(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003870
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003871 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003872 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003873 }
3874
3875 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003876 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003877 /* finished. */
3878 case HLUA_E_OK:
3879 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003880 hlua_lua2smp(stream->hlua.T, -1, smp);
3881 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003882 return 1;
3883
3884 /* yield. */
3885 case HLUA_E_AGAIN:
Willy Tarreau87b09662015-04-03 00:22:06 +02003886 send_log(stream->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003887 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3888 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
3889 return 0;
3890
3891 /* finished with error. */
3892 case HLUA_E_ERRMSG:
3893 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003894 send_log(stream->be, LOG_ERR, "Lua converter '%s': %s.", fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003895 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Willy Tarreau87b09662015-04-03 00:22:06 +02003896 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
3897 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003898 return 0;
3899
3900 case HLUA_E_ERR:
3901 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003902 send_log(stream->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003903 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3904 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
3905
3906 default:
3907 return 0;
3908 }
3909}
3910
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003911/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
3912 * doesn't allow "yield" functions because the HAProxy engine cannot
3913 * resume sample-fetches.
3914 */
Willy Tarreau192252e2015-04-04 01:47:55 +02003915static int hlua_sample_fetch_wrapper(struct proxy *px, struct session *sess,
3916 struct stream *s, unsigned int opt,
3917 const struct arg *arg_p,
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003918 struct sample *smp, const char *kw, void *private)
3919{
3920 struct hlua_function *fcn = (struct hlua_function *)private;
3921
Willy Tarreau87b09662015-04-03 00:22:06 +02003922 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003923 * Lua context can be not initialized. This behavior
3924 * permits to save performances because a systematic
3925 * Lua initialization cause 5% performances loss.
3926 */
3927 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
3928 send_log(s->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
3929 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3930 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
3931 return 0;
3932 }
3933
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003934 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003935 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003936 /* Check stack available size. */
3937 if (!lua_checkstack(s->hlua.T, 2)) {
3938 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3939 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3940 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3941 return 0;
3942 }
3943
3944 /* Restore the function in the stack. */
3945 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
3946
3947 /* push arguments in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003948 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003949 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3950 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3951 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3952 return 0;
3953 }
3954 s->hlua.nargs = 1;
3955
3956 /* push keywords in the stack. */
3957 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
3958 /* Check stack available size. */
3959 if (!lua_checkstack(s->hlua.T, 1)) {
3960 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3961 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3962 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3963 return 0;
3964 }
3965 if (!lua_checkstack(s->hlua.T, 1)) {
3966 send_log(px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
3967 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3968 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
3969 return 0;
3970 }
3971 hlua_arg2lua(s->hlua.T, arg_p);
3972 s->hlua.nargs++;
3973 }
3974
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003975 /* We must initialize the execution timeouts. */
3976 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
3977
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003978 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01003979 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003980 }
3981
3982 /* Execute the function. */
3983 switch (hlua_ctx_resume(&s->hlua, 0)) {
3984 /* finished. */
3985 case HLUA_E_OK:
3986 /* Convert the returned value in sample. */
3987 hlua_lua2smp(s->hlua.T, -1, smp);
3988 lua_pop(s->hlua.T, 1);
3989
3990 /* Set the end of execution flag. */
3991 smp->flags &= ~SMP_F_MAY_CHANGE;
3992 return 1;
3993
3994 /* yield. */
3995 case HLUA_E_AGAIN:
3996 send_log(px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
3997 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3998 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
3999 return 0;
4000
4001 /* finished with error. */
4002 case HLUA_E_ERRMSG:
4003 /* Display log. */
4004 send_log(px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(s->hlua.T, -1));
4005 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4006 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(s->hlua.T, -1));
4007 lua_pop(s->hlua.T, 1);
4008 return 0;
4009
4010 case HLUA_E_ERR:
4011 /* Display log. */
4012 send_log(px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
4013 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4014 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
4015
4016 default:
4017 return 0;
4018 }
4019}
4020
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004021/* This function is an LUA binding used for registering
4022 * "sample-conv" functions. It expects a converter name used
4023 * in the haproxy configuration file, and an LUA function.
4024 */
4025__LJMP static int hlua_register_converters(lua_State *L)
4026{
4027 struct sample_conv_kw_list *sck;
4028 const char *name;
4029 int ref;
4030 int len;
4031 struct hlua_function *fcn;
4032
4033 MAY_LJMP(check_args(L, 2, "register_converters"));
4034
4035 /* First argument : converter name. */
4036 name = MAY_LJMP(luaL_checkstring(L, 1));
4037
4038 /* Second argument : lua function. */
4039 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4040
4041 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004042 sck = malloc(sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004043 if (!sck)
4044 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4045 fcn = malloc(sizeof(*fcn));
4046 if (!fcn)
4047 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4048
4049 /* Fill fcn. */
4050 fcn->name = strdup(name);
4051 if (!fcn->name)
4052 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4053 fcn->function_ref = ref;
4054
4055 /* List head */
4056 sck->list.n = sck->list.p = NULL;
4057
4058 /* converter keyword. */
4059 len = strlen("lua.") + strlen(name) + 1;
4060 sck->kw[0].kw = malloc(len);
4061 if (!sck->kw[0].kw)
4062 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4063
4064 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4065 sck->kw[0].process = hlua_sample_conv_wrapper;
4066 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4067 sck->kw[0].val_args = NULL;
4068 sck->kw[0].in_type = SMP_T_STR;
4069 sck->kw[0].out_type = SMP_T_STR;
4070 sck->kw[0].private = fcn;
4071
4072 /* End of array. */
4073 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
4074
4075 /* Register this new converter */
4076 sample_register_convs(sck);
4077
4078 return 0;
4079}
4080
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004081/* This fucntion is an LUA binding used for registering
4082 * "sample-fetch" functions. It expects a converter name used
4083 * in the haproxy configuration file, and an LUA function.
4084 */
4085__LJMP static int hlua_register_fetches(lua_State *L)
4086{
4087 const char *name;
4088 int ref;
4089 int len;
4090 struct sample_fetch_kw_list *sfk;
4091 struct hlua_function *fcn;
4092
4093 MAY_LJMP(check_args(L, 2, "register_fetches"));
4094
4095 /* First argument : sample-fetch name. */
4096 name = MAY_LJMP(luaL_checkstring(L, 1));
4097
4098 /* Second argument : lua function. */
4099 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4100
4101 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004102 sfk = malloc(sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004103 if (!sfk)
4104 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4105 fcn = malloc(sizeof(*fcn));
4106 if (!fcn)
4107 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4108
4109 /* Fill fcn. */
4110 fcn->name = strdup(name);
4111 if (!fcn->name)
4112 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4113 fcn->function_ref = ref;
4114
4115 /* List head */
4116 sfk->list.n = sfk->list.p = NULL;
4117
4118 /* sample-fetch keyword. */
4119 len = strlen("lua.") + strlen(name) + 1;
4120 sfk->kw[0].kw = malloc(len);
4121 if (!sfk->kw[0].kw)
4122 return luaL_error(L, "lua out of memory error.");
4123
4124 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4125 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4126 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4127 sfk->kw[0].val_args = NULL;
4128 sfk->kw[0].out_type = SMP_T_STR;
4129 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4130 sfk->kw[0].val = 0;
4131 sfk->kw[0].private = fcn;
4132
4133 /* End of array. */
4134 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
4135
4136 /* Register this new fetch. */
4137 sample_register_fetches(sfk);
4138
4139 return 0;
4140}
4141
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004142/* global {tcp|http}-request parser. Return 1 in succes case, else return 0. */
4143static int hlua_parse_rule(const char **args, int *cur_arg, struct proxy *px,
4144 struct hlua_rule **rule_p, char **err)
4145{
4146 struct hlua_rule *rule;
4147
4148 /* Memory for the rule. */
4149 rule = malloc(sizeof(*rule));
4150 if (!rule) {
4151 memprintf(err, "out of memory error");
4152 return 0;
4153 }
4154 *rule_p = rule;
4155
4156 /* The requiered arg is a function name. */
4157 if (!args[*cur_arg]) {
4158 memprintf(err, "expect Lua function name");
4159 return 0;
4160 }
4161
4162 /* Lookup for the symbol, and check if it is a function. */
4163 lua_getglobal(gL.T, args[*cur_arg]);
4164 if (lua_isnil(gL.T, -1)) {
4165 lua_pop(gL.T, 1);
4166 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
4167 return 0;
4168 }
4169 if (!lua_isfunction(gL.T, -1)) {
4170 lua_pop(gL.T, 1);
4171 memprintf(err, "'%s' is not a function", args[*cur_arg]);
4172 return 0;
4173 }
4174
4175 /* Reference the Lua function and store the reference. */
4176 rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
4177 rule->fcn.name = strdup(args[*cur_arg]);
4178 if (!rule->fcn.name) {
4179 memprintf(err, "out of memory error.");
4180 return 0;
4181 }
4182 (*cur_arg)++;
4183
4184 /* TODO: later accept arguments. */
4185 rule->args = NULL;
4186
4187 return 1;
4188}
4189
4190/* This function is a wrapper to execute each LUA function declared
4191 * as an action wrapper during the initialisation period. This function
4192 * return 1 if the processing is finished (with oe without error) and
4193 * return 0 if the function must be called again because the LUA
4194 * returns a yield.
4195 */
4196static int hlua_request_act_wrapper(struct hlua_rule *rule, struct proxy *px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004197 struct stream *s, unsigned int analyzer)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004198{
4199 char **arg;
4200
Willy Tarreau87b09662015-04-03 00:22:06 +02004201 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004202 * Lua context can be not initialized. This behavior
4203 * permits to save performances because a systematic
4204 * Lua initialization cause 5% performances loss.
4205 */
4206 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
4207 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.", rule->fcn.name);
4208 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4209 Alert("Lua action '%s': can't initialize Lua context.\n", rule->fcn.name);
4210 return 0;
4211 }
4212
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004213 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004214 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004215 /* Check stack available size. */
4216 if (!lua_checkstack(s->hlua.T, 1)) {
4217 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4218 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4219 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4220 return 0;
4221 }
4222
4223 /* Restore the function in the stack. */
4224 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->fcn.function_ref);
4225
Willy Tarreau87b09662015-04-03 00:22:06 +02004226 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004227 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004228 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4229 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4230 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4231 return 0;
4232 }
4233 s->hlua.nargs = 1;
4234
4235 /* push keywords in the stack. */
4236 for (arg = rule->args; arg && *arg; arg++) {
4237 if (!lua_checkstack(s->hlua.T, 1)) {
4238 send_log(px, LOG_ERR, "Lua function '%s': full stack.", rule->fcn.name);
4239 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4240 Alert("Lua function '%s': full stack.\n", rule->fcn.name);
4241 return 0;
4242 }
4243 lua_pushstring(s->hlua.T, *arg);
4244 s->hlua.nargs++;
4245 }
4246
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004247 /* We must initialize the execution timeouts. */
4248 s->hlua.expire = tick_add(now_ms, hlua_timeout_session);
4249
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004250 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004251 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004252 }
4253
4254 /* Execute the function. */
4255 switch (hlua_ctx_resume(&s->hlua, 1)) {
4256 /* finished. */
4257 case HLUA_E_OK:
4258 return 1;
4259
4260 /* yield. */
4261 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004262 /* Set timeout in the required channel. */
4263 if (s->hlua.wake_time != TICK_ETERNITY) {
4264 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004265 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004266 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004267 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004268 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004269 /* Some actions can be wake up when a "write" event
4270 * is detected on a response channel. This is useful
4271 * only for actions targetted on the requests.
4272 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004273 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004274 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01004275 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004276 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004277 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004278 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004279 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004280 return 0;
4281
4282 /* finished with error. */
4283 case HLUA_E_ERRMSG:
4284 /* Display log. */
4285 send_log(px, LOG_ERR, "Lua function '%s': %s.", rule->fcn.name, lua_tostring(s->hlua.T, -1));
4286 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4287 Alert("Lua function '%s': %s.\n", rule->fcn.name, lua_tostring(s->hlua.T, -1));
4288 lua_pop(s->hlua.T, 1);
4289 return 1;
4290
4291 case HLUA_E_ERR:
4292 /* Display log. */
4293 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.", rule->fcn.name);
4294 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4295 Alert("Lua function '%s' return an unknown error.\n", rule->fcn.name);
4296
4297 default:
4298 return 1;
4299 }
4300}
4301
4302/* Lua execution wrapper for "tcp-request". This function uses
4303 * "hlua_request_act_wrapper" for executing the LUA code.
4304 */
4305int hlua_tcp_req_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
Willy Tarreau87b09662015-04-03 00:22:06 +02004306 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004307{
4308 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004309 px, s, AN_REQ_INSPECT_FE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004310}
4311
4312/* Lua execution wrapper for "tcp-response". This function uses
4313 * "hlua_request_act_wrapper" for executing the LUA code.
4314 */
4315int hlua_tcp_res_act_wrapper(struct tcp_rule *tcp_rule, struct proxy *px,
Willy Tarreau87b09662015-04-03 00:22:06 +02004316 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004317{
4318 return hlua_request_act_wrapper((struct hlua_rule *)tcp_rule->act_prm.data,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004319 px, s, AN_RES_INSPECT);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004320}
4321
4322/* Lua execution wrapper for http-request.
4323 * This function uses "hlua_request_act_wrapper" for executing
4324 * the LUA code.
4325 */
4326int hlua_http_req_act_wrapper(struct http_req_rule *rule, struct proxy *px,
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004327 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004328{
4329 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004330 s, AN_REQ_HTTP_PROCESS_FE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004331}
4332
4333/* Lua execution wrapper for http-response.
4334 * This function uses "hlua_request_act_wrapper" for executing
4335 * the LUA code.
4336 */
4337int hlua_http_res_act_wrapper(struct http_res_rule *rule, struct proxy *px,
Willy Tarreau987e3fb2015-04-04 01:09:08 +02004338 struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004339{
4340 return hlua_request_act_wrapper((struct hlua_rule *)rule->arg.data, px,
Willy Tarreaufdcd2ae2015-04-04 01:11:28 +02004341 s, AN_RES_HTTP_PROCESS_BE);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004342}
4343
4344/* tcp-request <*> configuration wrapper. */
4345static int tcp_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4346 struct tcp_rule *rule, char **err)
4347{
4348 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004349 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004350 rule->action = TCP_ACT_CUSTOM;
4351 rule->action_ptr = hlua_tcp_req_act_wrapper;
4352 return 1;
4353}
4354
4355/* tcp-response <*> configuration wrapper. */
4356static int tcp_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4357 struct tcp_rule *rule, char **err)
4358{
4359 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->act_prm.data, err))
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004360 return 0;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004361 rule->action = TCP_ACT_CUSTOM;
4362 rule->action_ptr = hlua_tcp_res_act_wrapper;
4363 return 1;
4364}
4365
4366/* http-request <*> configuration wrapper. */
4367static int http_req_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4368 struct http_req_rule *rule, char **err)
4369{
4370 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
4371 return -1;
4372 rule->action = HTTP_REQ_ACT_CUSTOM_CONT;
4373 rule->action_ptr = hlua_http_req_act_wrapper;
4374 return 1;
4375}
4376
4377/* http-response <*> configuration wrapper. */
4378static int http_res_action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4379 struct http_res_rule *rule, char **err)
4380{
4381 if (!hlua_parse_rule(args, cur_arg, px, (struct hlua_rule **)&rule->arg.data, err))
4382 return -1;
4383 rule->action = HTTP_RES_ACT_CUSTOM_CONT;
4384 rule->action_ptr = hlua_http_res_act_wrapper;
4385 return 1;
4386}
4387
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004388static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4389 struct proxy *defpx, const char *file, int line,
4390 char **err, unsigned int *timeout)
4391{
4392 const char *error;
4393
4394 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4395 if (error && *error != '\0') {
4396 memprintf(err, "%s: invalid timeout", args[0]);
4397 return -1;
4398 }
4399 return 0;
4400}
4401
4402static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4403 struct proxy *defpx, const char *file, int line,
4404 char **err)
4405{
4406 return hlua_read_timeout(args, section_type, curpx, defpx,
4407 file, line, err, &hlua_timeout_session);
4408}
4409
4410static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4411 struct proxy *defpx, const char *file, int line,
4412 char **err)
4413{
4414 return hlua_read_timeout(args, section_type, curpx, defpx,
4415 file, line, err, &hlua_timeout_task);
4416}
4417
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004418static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4419 struct proxy *defpx, const char *file, int line,
4420 char **err)
4421{
4422 char *error;
4423
4424 hlua_nb_instruction = strtoll(args[1], &error, 10);
4425 if (*error != '\0') {
4426 memprintf(err, "%s: invalid number", args[0]);
4427 return -1;
4428 }
4429 return 0;
4430}
4431
Willy Tarreau32f61e22015-03-18 17:54:59 +01004432static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4433 struct proxy *defpx, const char *file, int line,
4434 char **err)
4435{
4436 char *error;
4437
4438 if (*(args[1]) == 0) {
4439 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4440 return -1;
4441 }
4442 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4443 if (*error != '\0') {
4444 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4445 return -1;
4446 }
4447 return 0;
4448}
4449
4450
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004451/* This function is called by the main configuration key "lua-load". It loads and
4452 * execute an lua file during the parsing of the HAProxy configuration file. It is
4453 * the main lua entry point.
4454 *
4455 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4456 * occured, otherwise it returns 0.
4457 *
4458 * In some error case, LUA set an error message in top of the stack. This function
4459 * returns this error message in the HAProxy logs and pop it from the stack.
4460 */
4461static int hlua_load(char **args, int section_type, struct proxy *curpx,
4462 struct proxy *defpx, const char *file, int line,
4463 char **err)
4464{
4465 int error;
4466
4467 /* Just load and compile the file. */
4468 error = luaL_loadfile(gL.T, args[1]);
4469 if (error) {
4470 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4471 lua_pop(gL.T, 1);
4472 return -1;
4473 }
4474
4475 /* If no syntax error where detected, execute the code. */
4476 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4477 switch (error) {
4478 case LUA_OK:
4479 break;
4480 case LUA_ERRRUN:
4481 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4482 lua_pop(gL.T, 1);
4483 return -1;
4484 case LUA_ERRMEM:
4485 memprintf(err, "lua out of memory error\n");
4486 return -1;
4487 case LUA_ERRERR:
4488 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4489 lua_pop(gL.T, 1);
4490 return -1;
4491 case LUA_ERRGCMM:
4492 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4493 lua_pop(gL.T, 1);
4494 return -1;
4495 default:
4496 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4497 lua_pop(gL.T, 1);
4498 return -1;
4499 }
4500
4501 return 0;
4502}
4503
4504/* configuration keywords declaration */
4505static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004506 { CFG_GLOBAL, "lua-load", hlua_load },
4507 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4508 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004509 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01004510 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004511 { 0, NULL, NULL },
4512}};
4513
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004514static struct http_req_action_kw_list http_req_kws = {"lua", { }, {
4515 { "lua", http_req_action_register_lua },
4516 { NULL, NULL }
4517}};
4518
4519static struct http_res_action_kw_list http_res_kws = {"lua", { }, {
4520 { "lua", http_res_action_register_lua },
4521 { NULL, NULL }
4522}};
4523
4524static struct tcp_action_kw_list tcp_req_cont_kws = {"lua", { }, {
4525 { "lua", tcp_req_action_register_lua },
4526 { NULL, NULL }
4527}};
4528
4529static struct tcp_action_kw_list tcp_res_cont_kws = {"lua", { }, {
4530 { "lua", tcp_res_action_register_lua },
4531 { NULL, NULL }
4532}};
4533
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004534int hlua_post_init()
4535{
4536 struct hlua_init_function *init;
4537 const char *msg;
4538 enum hlua_exec ret;
4539
4540 list_for_each_entry(init, &hlua_init_functions, l) {
4541 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4542 ret = hlua_ctx_resume(&gL, 0);
4543 switch (ret) {
4544 case HLUA_E_OK:
4545 lua_pop(gL.T, -1);
4546 return 1;
4547 case HLUA_E_AGAIN:
4548 Alert("lua init: yield not allowed.\n");
4549 return 0;
4550 case HLUA_E_ERRMSG:
4551 msg = lua_tostring(gL.T, -1);
4552 Alert("lua init: %s.\n", msg);
4553 return 0;
4554 case HLUA_E_ERR:
4555 default:
4556 Alert("lua init: unknown runtime error.\n");
4557 return 0;
4558 }
4559 }
4560 return 1;
4561}
4562
Willy Tarreau32f61e22015-03-18 17:54:59 +01004563/* The memory allocator used by the Lua stack. <ud> is a pointer to the
4564 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4565 * is the previously allocated size or the kind of object in case of a new
4566 * allocation. <nsize> is the requested new size.
4567 */
4568static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4569{
4570 struct hlua_mem_allocator *zone = ud;
4571
4572 if (nsize == 0) {
4573 /* it's a free */
4574 if (ptr)
4575 zone->allocated -= osize;
4576 free(ptr);
4577 return NULL;
4578 }
4579
4580 if (!ptr) {
4581 /* it's a new allocation */
4582 if (zone->limit && zone->allocated + nsize > zone->limit)
4583 return NULL;
4584
4585 ptr = malloc(nsize);
4586 if (ptr)
4587 zone->allocated += nsize;
4588 return ptr;
4589 }
4590
4591 /* it's a realloc */
4592 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4593 return NULL;
4594
4595 ptr = realloc(ptr, nsize);
4596 if (ptr)
4597 zone->allocated += nsize - osize;
4598 return ptr;
4599}
4600
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004601void hlua_init(void)
4602{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004603 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004604 int idx;
4605 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004606 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004607 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004608#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004609 struct srv_kw *kw;
4610 int tmp_error;
4611 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01004612 char *args[] = { /* SSL client configuration. */
4613 "ssl",
4614 "verify",
4615 "none",
4616 "force-sslv3",
4617 NULL
4618 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004619#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004620
Willy Tarreau87b09662015-04-03 00:22:06 +02004621 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004622 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4623
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004624 /* Register configuration keywords. */
4625 cfg_register_keywords(&cfg_kws);
4626
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004627 /* Register custom HTTP rules. */
4628 http_req_keywords_register(&http_req_kws);
4629 http_res_keywords_register(&http_res_kws);
4630 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
4631 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
4632
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004633 /* Init main lua stack. */
4634 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004635 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004636 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004637 gL.T = luaL_newstate();
4638 hlua_sethlua(&gL);
4639 gL.Tref = LUA_REFNIL;
4640 gL.task = NULL;
4641
Willy Tarreau32f61e22015-03-18 17:54:59 +01004642 /* change the memory allocators to track memory usage */
4643 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4644
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004645 /* Initialise lua. */
4646 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004647
4648 /*
4649 *
4650 * Create "core" object.
4651 *
4652 */
4653
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004654 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004655 lua_newtable(gL.T);
4656
4657 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004658 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004659 hlua_class_const_int(gL.T, log_levels[i], i);
4660
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004661 /* Register special functions. */
4662 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004663 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004664 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004665 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004666 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004667 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004668 hlua_class_function(gL.T, "sleep", hlua_sleep);
4669 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004670 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4671 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4672 hlua_class_function(gL.T, "set_map", hlua_set_map);
4673 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004674 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004675 hlua_class_function(gL.T, "log", hlua_log);
4676 hlua_class_function(gL.T, "Debug", hlua_log_debug);
4677 hlua_class_function(gL.T, "Info", hlua_log_info);
4678 hlua_class_function(gL.T, "Warning", hlua_log_warning);
4679 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004680
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004681 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004682
4683 /*
4684 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004685 * Register class Channel
4686 *
4687 */
4688
4689 /* Create and fill the metatable. */
4690 lua_newtable(gL.T);
4691
4692 /* Create and fille the __index entry. */
4693 lua_pushstring(gL.T, "__index");
4694 lua_newtable(gL.T);
4695
4696 /* Register . */
4697 hlua_class_function(gL.T, "get", hlua_channel_get);
4698 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4699 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4700 hlua_class_function(gL.T, "set", hlua_channel_set);
4701 hlua_class_function(gL.T, "append", hlua_channel_append);
4702 hlua_class_function(gL.T, "send", hlua_channel_send);
4703 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4704 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4705 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4706
4707 lua_settable(gL.T, -3);
4708
4709 /* Register previous table in the registry with reference and named entry. */
4710 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4711 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4712 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4713
4714 /*
4715 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004716 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004717 *
4718 */
4719
4720 /* Create and fill the metatable. */
4721 lua_newtable(gL.T);
4722
4723 /* Create and fille the __index entry. */
4724 lua_pushstring(gL.T, "__index");
4725 lua_newtable(gL.T);
4726
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004727 /* Browse existing fetches and create the associated
4728 * object method.
4729 */
4730 sf = NULL;
4731 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4732
4733 /* Dont register the keywork if the arguments check function are
4734 * not safe during the runtime.
4735 */
4736 if ((sf->val_args != NULL) &&
4737 (sf->val_args != val_payload_lv) &&
4738 (sf->val_args != val_hdr))
4739 continue;
4740
4741 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4742 * by an underscore.
4743 */
4744 strncpy(trash.str, sf->kw, trash.size);
4745 trash.str[trash.size - 1] = '\0';
4746 for (p = trash.str; *p; p++)
4747 if (*p == '.' || *p == '-' || *p == '+')
4748 *p = '_';
4749
4750 /* Register the function. */
4751 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01004752 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004753 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4754 lua_settable(gL.T, -3);
4755 }
4756
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004757 lua_settable(gL.T, -3);
4758
4759 /* Register previous table in the registry with reference and named entry. */
4760 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4761 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4762 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4763
4764 /*
4765 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004766 * Register class Converters
4767 *
4768 */
4769
4770 /* Create and fill the metatable. */
4771 lua_newtable(gL.T);
4772
4773 /* Create and fill the __index entry. */
4774 lua_pushstring(gL.T, "__index");
4775 lua_newtable(gL.T);
4776
4777 /* Browse existing converters and create the associated
4778 * object method.
4779 */
4780 sc = NULL;
4781 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4782 /* Dont register the keywork if the arguments check function are
4783 * not safe during the runtime.
4784 */
4785 if (sc->val_args != NULL)
4786 continue;
4787
4788 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4789 * by an underscore.
4790 */
4791 strncpy(trash.str, sc->kw, trash.size);
4792 trash.str[trash.size - 1] = '\0';
4793 for (p = trash.str; *p; p++)
4794 if (*p == '.' || *p == '-' || *p == '+')
4795 *p = '_';
4796
4797 /* Register the function. */
4798 lua_pushstring(gL.T, trash.str);
4799 lua_pushlightuserdata(gL.T, sc);
4800 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4801 lua_settable(gL.T, -3);
4802 }
4803
4804 lua_settable(gL.T, -3);
4805
4806 /* Register previous table in the registry with reference and named entry. */
4807 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4808 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4809 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4810
4811 /*
4812 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004813 * Register class HTTP
4814 *
4815 */
4816
4817 /* Create and fill the metatable. */
4818 lua_newtable(gL.T);
4819
4820 /* Create and fille the __index entry. */
4821 lua_pushstring(gL.T, "__index");
4822 lua_newtable(gL.T);
4823
4824 /* Register Lua functions. */
4825 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
4826 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
4827 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
4828 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
4829 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
4830 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
4831 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
4832 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
4833 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
4834 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
4835
4836 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
4837 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
4838 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
4839 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
4840 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
4841 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
4842
4843 lua_settable(gL.T, -3);
4844
4845 /* Register previous table in the registry with reference and named entry. */
4846 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4847 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
4848 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4849
4850 /*
4851 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004852 * Register class TXN
4853 *
4854 */
4855
4856 /* Create and fill the metatable. */
4857 lua_newtable(gL.T);
4858
4859 /* Create and fille the __index entry. */
4860 lua_pushstring(gL.T, "__index");
4861 lua_newtable(gL.T);
4862
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004863 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004864 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4865 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004866 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004867 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
4868 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
4869 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004870 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
4871 hlua_class_function(gL.T, "log", hlua_txn_log);
4872 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
4873 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
4874 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
4875 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004876
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004877 lua_settable(gL.T, -3);
4878
4879 /* Register previous table in the registry with reference and named entry. */
4880 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4881 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
4882 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004883
4884 /*
4885 *
4886 * Register class Socket
4887 *
4888 */
4889
4890 /* Create and fill the metatable. */
4891 lua_newtable(gL.T);
4892
4893 /* Create and fille the __index entry. */
4894 lua_pushstring(gL.T, "__index");
4895 lua_newtable(gL.T);
4896
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004897#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004898 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004899#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004900 hlua_class_function(gL.T, "connect", hlua_socket_connect);
4901 hlua_class_function(gL.T, "send", hlua_socket_send);
4902 hlua_class_function(gL.T, "receive", hlua_socket_receive);
4903 hlua_class_function(gL.T, "close", hlua_socket_close);
4904 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
4905 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
4906 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
4907 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
4908
4909 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4910
4911 /* Register the garbage collector entry. */
4912 lua_pushstring(gL.T, "__gc");
4913 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
4914 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4915
4916 /* Register previous table in the registry with reference and named entry. */
4917 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4918 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4919 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
4920 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
4921
4922 /* Proxy and server configuration initialisation. */
4923 memset(&socket_proxy, 0, sizeof(socket_proxy));
4924 init_new_proxy(&socket_proxy);
4925 socket_proxy.parent = NULL;
4926 socket_proxy.last_change = now.tv_sec;
4927 socket_proxy.id = "LUA-SOCKET";
4928 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
4929 socket_proxy.maxconn = 0;
4930 socket_proxy.accept = NULL;
4931 socket_proxy.options2 |= PR_O2_INDEPSTR;
4932 socket_proxy.srv = NULL;
4933 socket_proxy.conn_retries = 0;
4934 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
4935
4936 /* Init TCP server: unchanged parameters */
4937 memset(&socket_tcp, 0, sizeof(socket_tcp));
4938 socket_tcp.next = NULL;
4939 socket_tcp.proxy = &socket_proxy;
4940 socket_tcp.obj_type = OBJ_TYPE_SERVER;
4941 LIST_INIT(&socket_tcp.actconns);
4942 LIST_INIT(&socket_tcp.pendconns);
4943 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
4944 socket_tcp.last_change = 0;
4945 socket_tcp.id = "LUA-TCP-CONN";
4946 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4947 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4948 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
4949
4950 /* XXX: Copy default parameter from default server,
4951 * but the default server is not initialized.
4952 */
4953 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
4954 socket_tcp.minconn = socket_proxy.defsrv.minconn;
4955 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
4956 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
4957 socket_tcp.onerror = socket_proxy.defsrv.onerror;
4958 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
4959 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
4960 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
4961 socket_tcp.uweight = socket_proxy.defsrv.iweight;
4962 socket_tcp.iweight = socket_proxy.defsrv.iweight;
4963
4964 socket_tcp.check.status = HCHK_STATUS_INI;
4965 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
4966 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
4967 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
4968 socket_tcp.check.server = &socket_tcp;
4969
4970 socket_tcp.agent.status = HCHK_STATUS_INI;
4971 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
4972 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
4973 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
4974 socket_tcp.agent.server = &socket_tcp;
4975
4976 socket_tcp.xprt = &raw_sock;
4977
4978#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004979 /* Init TCP server: unchanged parameters */
4980 memset(&socket_ssl, 0, sizeof(socket_ssl));
4981 socket_ssl.next = NULL;
4982 socket_ssl.proxy = &socket_proxy;
4983 socket_ssl.obj_type = OBJ_TYPE_SERVER;
4984 LIST_INIT(&socket_ssl.actconns);
4985 LIST_INIT(&socket_ssl.pendconns);
4986 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
4987 socket_ssl.last_change = 0;
4988 socket_ssl.id = "LUA-SSL-CONN";
4989 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4990 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
4991 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
4992
4993 /* XXX: Copy default parameter from default server,
4994 * but the default server is not initialized.
4995 */
4996 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
4997 socket_ssl.minconn = socket_proxy.defsrv.minconn;
4998 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
4999 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5000 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5001 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5002 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5003 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5004 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5005 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5006
5007 socket_ssl.check.status = HCHK_STATUS_INI;
5008 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5009 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5010 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5011 socket_ssl.check.server = &socket_ssl;
5012
5013 socket_ssl.agent.status = HCHK_STATUS_INI;
5014 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5015 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5016 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5017 socket_ssl.agent.server = &socket_ssl;
5018
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005019 socket_ssl.use_ssl = 1;
5020 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005021
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005022 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005023 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5024 /*
5025 *
5026 * If the keyword is not known, we can search in the registered
5027 * server keywords. This is usefull to configure special SSL
5028 * features like client certificates and ssl_verify.
5029 *
5030 */
5031 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5032 if (tmp_error != 0) {
5033 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5034 abort(); /* This must be never arrives because the command line
5035 not editable by the user. */
5036 }
5037 idx += kw->skip;
5038 }
5039 }
5040
5041 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005042 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005043#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005044}