blob: 61e28d00146c90ce1c6a0a8d832e2495b3ede066 [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>
19#include <types/proxy.h>
20
Thierry FOURNIER55da1652015-01-23 11:36:30 +010021#include <proto/arg.h>
Willy Tarreau8a8d83b2015-04-13 13:24:54 +020022#include <proto/applet.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 FOURNIER3def3932015-04-07 11:27:54 +020026#include <proto/map.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010027#include <proto/obj_type.h>
Thierry FOURNIER83758bb2015-02-04 13:21:04 +010028#include <proto/pattern.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010029#include <proto/payload.h>
30#include <proto/proto_http.h>
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +010031#include <proto/proto_tcp.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010032#include <proto/raw_sock.h>
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +010033#include <proto/sample.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010034#include <proto/server.h>
Willy Tarreaufeb76402015-04-03 14:10:06 +020035#include <proto/session.h>
Willy Tarreau87b09662015-04-03 00:22:06 +020036#include <proto/stream.h>
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010037#include <proto/ssl_sock.h>
38#include <proto/stream_interface.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010039#include <proto/task.h>
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +020040#include <proto/vars.h>
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010041
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +010042/* Lua uses longjmp to perform yield or throwing errors. This
43 * macro is used only for identifying the function that can
44 * not return because a longjmp is executed.
45 * __LJMP marks a prototype of hlua file that can use longjmp.
46 * WILL_LJMP() marks an lua function that will use longjmp.
47 * MAY_LJMP() marks an lua function that may use longjmp.
48 */
49#define __LJMP
50#define WILL_LJMP(func) func
51#define MAY_LJMP(func) func
52
Thierry FOURNIER380d0932015-01-23 14:27:52 +010053/* The main Lua execution context. */
54struct hlua gL;
55
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +010056/* This is the memory pool containing all the signal structs. These
57 * struct are used to store each requiered signal between two tasks.
58 */
59struct pool_head *pool2_hlua_com;
60
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010061/* Used for Socket connection. */
62static struct proxy socket_proxy;
63static struct server socket_tcp;
64#ifdef USE_OPENSSL
65static struct server socket_ssl;
66#endif
67
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +010068/* List head of the function called at the initialisation time. */
69struct list hlua_init_functions = LIST_HEAD_INIT(hlua_init_functions);
70
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010071/* The following variables contains the reference of the different
72 * Lua classes. These references are useful for identify metadata
73 * associated with an object.
74 */
Thierry FOURNIER65f34c62015-02-16 20:11:43 +010075static int class_txn_ref;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +010076static int class_socket_ref;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +010077static int class_channel_ref;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +010078static int class_fetches_ref;
Thierry FOURNIER594afe72015-03-10 23:58:30 +010079static int class_converters_ref;
Thierry FOURNIER08504f42015-03-16 14:17:08 +010080static int class_http_ref;
Thierry FOURNIER3def3932015-04-07 11:27:54 +020081static int class_map_ref;
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +010082
Thierry FOURNIERbd413492015-03-03 16:52:26 +010083/* Global Lua execution timeout. By default Lua, execution linked
Willy Tarreau87b09662015-04-03 00:22:06 +020084 * with stream (actions, sample-fetches and converters) have a
Thierry FOURNIERbd413492015-03-03 16:52:26 +010085 * short timeout. Lua linked with tasks doesn't have a timeout
86 * because a task may remain alive during all the haproxy execution.
87 */
88static unsigned int hlua_timeout_session = 4000; /* session timeout. */
89static unsigned int hlua_timeout_task = TICK_ETERNITY; /* task timeout. */
90
Thierry FOURNIERee9f8022015-03-03 17:37:37 +010091/* Interrupts the Lua processing each "hlua_nb_instruction" instructions.
92 * it is used for preventing infinite loops.
93 *
94 * I test the scheer with an infinite loop containing one incrementation
95 * and one test. I run this loop between 10 seconds, I raise a ceil of
96 * 710M loops from one interrupt each 9000 instructions, so I fix the value
97 * to one interrupt each 10 000 instructions.
98 *
99 * configured | Number of
100 * instructions | loops executed
101 * between two | in milions
102 * forced yields |
103 * ---------------+---------------
104 * 10 | 160
105 * 500 | 670
106 * 1000 | 680
107 * 5000 | 700
108 * 7000 | 700
109 * 8000 | 700
110 * 9000 | 710 <- ceil
111 * 10000 | 710
112 * 100000 | 710
113 * 1000000 | 710
114 *
115 */
116static unsigned int hlua_nb_instruction = 10000;
117
Willy Tarreau32f61e22015-03-18 17:54:59 +0100118/* Descriptor for the memory allocation state. If limit is not null, it will
119 * be enforced on any memory allocation.
120 */
121struct hlua_mem_allocator {
122 size_t allocated;
123 size_t limit;
124};
125
126static struct hlua_mem_allocator hlua_global_allocator;
127
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100128/* These functions converts types between HAProxy internal args or
129 * sample and LUA types. Another function permits to check if the
130 * LUA stack contains arguments according with an required ARG_T
131 * format.
132 */
133static int hlua_arg2lua(lua_State *L, const struct arg *arg);
134static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100135__LJMP static int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
136 unsigned int mask, struct proxy *p);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100137static int hlua_smp2lua(lua_State *L, struct sample *smp);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100138static int hlua_smp2lua_str(lua_State *L, struct sample *smp);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100139static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp);
140
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100141/* Used to check an Lua function type in the stack. It creates and
142 * returns a reference of the function. This function throws an
143 * error if the rgument is not a "function".
144 */
145__LJMP unsigned int hlua_checkfunction(lua_State *L, int argno)
146{
147 if (!lua_isfunction(L, argno)) {
148 const char *msg = lua_pushfstring(L, "function expected, got %s", luaL_typename(L, -1));
149 WILL_LJMP(luaL_argerror(L, argno, msg));
150 }
151 lua_pushvalue(L, argno);
152 return luaL_ref(L, LUA_REGISTRYINDEX);
153}
154
155/* The three following functions are useful for adding entries
156 * in a table. These functions takes a string and respectively an
157 * integer, a string or a function and add it to the table in the
158 * top of the stack.
159 *
160 * These functions throws an error if no more stack size is
161 * available.
162 */
163__LJMP static inline void hlua_class_const_int(lua_State *L, const char *name,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100164 int value)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100165{
166 if (!lua_checkstack(L, 2))
167 WILL_LJMP(luaL_error(L, "full stack"));
168 lua_pushstring(L, name);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100169 lua_pushinteger(L, value);
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100170 lua_settable(L, -3);
171}
172__LJMP static inline void hlua_class_const_str(lua_State *L, const char *name,
173 const char *value)
174{
175 if (!lua_checkstack(L, 2))
176 WILL_LJMP(luaL_error(L, "full stack"));
177 lua_pushstring(L, name);
178 lua_pushstring(L, value);
179 lua_settable(L, -3);
180}
181__LJMP static inline void hlua_class_function(lua_State *L, const char *name,
182 int (*function)(lua_State *L))
183{
184 if (!lua_checkstack(L, 2))
185 WILL_LJMP(luaL_error(L, "full stack"));
186 lua_pushstring(L, name);
187 lua_pushcclosure(L, function, 0);
188 lua_settable(L, -3);
189}
190
191/* This function check the number of arguments available in the
192 * stack. If the number of arguments available is not the same
193 * then <nb> an error is throwed.
194 */
195__LJMP static inline void check_args(lua_State *L, int nb, char *fcn)
196{
197 if (lua_gettop(L) == nb)
198 return;
199 WILL_LJMP(luaL_error(L, "'%s' needs %d arguments", fcn, nb));
200}
201
202/* Return true if the data in stack[<ud>] is an object of
203 * type <class_ref>.
204 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100205static int hlua_metaistype(lua_State *L, int ud, int class_ref)
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100206{
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100207 if (!lua_getmetatable(L, ud))
208 return 0;
209
210 lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
211 if (!lua_rawequal(L, -1, -2)) {
212 lua_pop(L, 2);
213 return 0;
214 }
215
216 lua_pop(L, 2);
217 return 1;
218}
219
220/* Return an object of the expected type, or throws an error. */
221__LJMP static void *hlua_checkudata(lua_State *L, int ud, int class_ref)
222{
Thierry FOURNIER2297bc22015-03-11 17:43:33 +0100223 void *p;
224
225 /* Check if the stack entry is an array. */
226 if (!lua_istable(L, ud))
227 WILL_LJMP(luaL_argerror(L, ud, NULL));
228 /* Check if the metadata have the expected type. */
229 if (!hlua_metaistype(L, ud, class_ref))
230 WILL_LJMP(luaL_argerror(L, ud, NULL));
231 /* Push on the stack at the entry [0] of the table. */
232 lua_rawgeti(L, ud, 0);
233 /* Check if this entry is userdata. */
234 p = lua_touserdata(L, -1);
235 if (!p)
236 WILL_LJMP(luaL_argerror(L, ud, NULL));
237 /* Remove the entry returned by lua_rawgeti(). */
238 lua_pop(L, 1);
239 /* Return the associated struct. */
240 return p;
Thierry FOURNIERe8b9a402015-02-25 18:48:12 +0100241}
242
243/* This fucntion push an error string prefixed by the file name
244 * and the line number where the error is encountered.
245 */
246static int hlua_pusherror(lua_State *L, const char *fmt, ...)
247{
248 va_list argp;
249 va_start(argp, fmt);
250 luaL_where(L, 1);
251 lua_pushvfstring(L, fmt, argp);
252 va_end(argp);
253 lua_concat(L, 2);
254 return 1;
255}
256
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100257/* This function register a new signal. "lua" is the current lua
258 * execution context. It contains a pointer to the associated task.
259 * "link" is a list head attached to an other task that must be wake
260 * the lua task if an event occurs. This is useful with external
261 * events like TCP I/O or sleep functions. This funcion allocate
262 * memory for the signal.
263 */
264static int hlua_com_new(struct hlua *lua, struct list *link)
265{
266 struct hlua_com *com = pool_alloc2(pool2_hlua_com);
267 if (!com)
268 return 0;
269 LIST_ADDQ(&lua->com, &com->purge_me);
270 LIST_ADDQ(link, &com->wake_me);
271 com->task = lua->task;
272 return 1;
273}
274
275/* This function purge all the pending signals when the LUA execution
276 * is finished. This prevent than a coprocess try to wake a deleted
277 * task. This function remove the memory associated to the signal.
278 */
279static void hlua_com_purge(struct hlua *lua)
280{
281 struct hlua_com *com, *back;
282
283 /* Delete all pending communication signals. */
284 list_for_each_entry_safe(com, back, &lua->com, purge_me) {
285 LIST_DEL(&com->purge_me);
286 LIST_DEL(&com->wake_me);
287 pool_free2(pool2_hlua_com, com);
288 }
289}
290
291/* This function sends signals. It wakes all the tasks attached
292 * to a list head, and remove the signal, and free the used
293 * memory.
294 */
295static void hlua_com_wake(struct list *wake)
296{
297 struct hlua_com *com, *back;
298
299 /* Wake task and delete all pending communication signals. */
300 list_for_each_entry_safe(com, back, wake, wake_me) {
301 LIST_DEL(&com->purge_me);
302 LIST_DEL(&com->wake_me);
303 task_wakeup(com->task, TASK_WOKEN_MSG);
304 pool_free2(pool2_hlua_com, com);
305 }
306}
307
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100308/* This functions is used with sample fetch and converters. It
309 * converts the HAProxy configuration argument in a lua stack
310 * values.
311 *
312 * It takes an array of "arg", and each entry of the array is
313 * converted and pushed in the LUA stack.
314 */
315static int hlua_arg2lua(lua_State *L, const struct arg *arg)
316{
317 switch (arg->type) {
318 case ARGT_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100319 case ARGT_TIME:
320 case ARGT_SIZE:
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100321 lua_pushinteger(L, arg->data.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100322 break;
323
324 case ARGT_STR:
325 lua_pushlstring(L, arg->data.str.str, arg->data.str.len);
326 break;
327
328 case ARGT_IPV4:
329 case ARGT_IPV6:
330 case ARGT_MSK4:
331 case ARGT_MSK6:
332 case ARGT_FE:
333 case ARGT_BE:
334 case ARGT_TAB:
335 case ARGT_SRV:
336 case ARGT_USR:
337 case ARGT_MAP:
338 default:
339 lua_pushnil(L);
340 break;
341 }
342 return 1;
343}
344
345/* This function take one entrie in an LUA stack at the index "ud",
346 * and try to convert it in an HAProxy argument entry. This is useful
347 * with sample fetch wrappers. The input arguments are gived to the
348 * lua wrapper and converted as arg list by thi function.
349 */
350static int hlua_lua2arg(lua_State *L, int ud, struct arg *arg)
351{
352 switch (lua_type(L, ud)) {
353
354 case LUA_TNUMBER:
355 case LUA_TBOOLEAN:
356 arg->type = ARGT_SINT;
357 arg->data.sint = lua_tointeger(L, ud);
358 break;
359
360 case LUA_TSTRING:
361 arg->type = ARGT_STR;
362 arg->data.str.str = (char *)lua_tolstring(L, ud, (size_t *)&arg->data.str.len);
363 break;
364
365 case LUA_TUSERDATA:
366 case LUA_TNIL:
367 case LUA_TTABLE:
368 case LUA_TFUNCTION:
369 case LUA_TTHREAD:
370 case LUA_TLIGHTUSERDATA:
371 arg->type = ARGT_SINT;
Thierry FOURNIERbf65cd42015-07-20 17:45:02 +0200372 arg->data.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100373 break;
374 }
375 return 1;
376}
377
378/* the following functions are used to convert a struct sample
379 * in Lua type. This useful to convert the return of the
380 * fetchs or converters.
381 */
Willy Tarreau5eadada2015-03-10 17:28:54 +0100382static int hlua_smp2lua(lua_State *L, struct sample *smp)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100383{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200384 switch (smp->data.type) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100385 case SMP_T_SINT:
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100386 case SMP_T_BOOL:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200387 lua_pushinteger(L, smp->data.u.sint);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100388 break;
389
390 case SMP_T_BIN:
391 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200392 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100393 break;
394
395 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200396 switch (smp->data.u.meth.meth) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100397 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
398 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
399 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
400 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
401 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
402 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
403 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
404 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
405 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200406 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100407 break;
408 default:
409 lua_pushnil(L);
410 break;
411 }
412 break;
413
414 case SMP_T_IPV4:
415 case SMP_T_IPV6:
416 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200417 if (sample_casts[smp->data.type][SMP_T_STR] &&
418 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200419 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Willy Tarreau5eadada2015-03-10 17:28:54 +0100420 else
421 lua_pushnil(L);
422 break;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100423 default:
424 lua_pushnil(L);
425 break;
426 }
427 return 1;
428}
429
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100430/* the following functions are used to convert a struct sample
431 * in Lua strings. This is useful to convert the return of the
432 * fetchs or converters.
433 */
434static int hlua_smp2lua_str(lua_State *L, struct sample *smp)
435{
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200436 switch (smp->data.type) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100437
438 case SMP_T_BIN:
439 case SMP_T_STR:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200440 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100441 break;
442
443 case SMP_T_METH:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200444 switch (smp->data.u.meth.meth) {
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100445 case HTTP_METH_OPTIONS: lua_pushstring(L, "OPTIONS"); break;
446 case HTTP_METH_GET: lua_pushstring(L, "GET"); break;
447 case HTTP_METH_HEAD: lua_pushstring(L, "HEAD"); break;
448 case HTTP_METH_POST: lua_pushstring(L, "POST"); break;
449 case HTTP_METH_PUT: lua_pushstring(L, "PUT"); break;
450 case HTTP_METH_DELETE: lua_pushstring(L, "DELETE"); break;
451 case HTTP_METH_TRACE: lua_pushstring(L, "TRACE"); break;
452 case HTTP_METH_CONNECT: lua_pushstring(L, "CONNECT"); break;
453 case HTTP_METH_OTHER:
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200454 lua_pushlstring(L, smp->data.u.meth.str.str, smp->data.u.meth.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100455 break;
456 default:
457 lua_pushstring(L, "");
458 break;
459 }
460 break;
461
462 case SMP_T_SINT:
463 case SMP_T_BOOL:
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100464 case SMP_T_IPV4:
465 case SMP_T_IPV6:
466 case SMP_T_ADDR: /* This type is never used to qualify a sample. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200467 if (sample_casts[smp->data.type][SMP_T_STR] &&
468 sample_casts[smp->data.type][SMP_T_STR](smp))
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200469 lua_pushlstring(L, smp->data.u.str.str, smp->data.u.str.len);
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +0100470 else
471 lua_pushstring(L, "");
472 break;
473 default:
474 lua_pushstring(L, "");
475 break;
476 }
477 return 1;
478}
479
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100480/* the following functions are used to convert an Lua type in a
481 * struct sample. This is useful to provide data from a converter
482 * to the LUA code.
483 */
484static int hlua_lua2smp(lua_State *L, int ud, struct sample *smp)
485{
486 switch (lua_type(L, ud)) {
487
488 case LUA_TNUMBER:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200489 smp->data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200490 smp->data.u.sint = lua_tointeger(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100491 break;
492
493
494 case LUA_TBOOLEAN:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200495 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200496 smp->data.u.sint = lua_toboolean(L, ud);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100497 break;
498
499 case LUA_TSTRING:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200500 smp->data.type = SMP_T_STR;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100501 smp->flags |= SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200502 smp->data.u.str.str = (char *)lua_tolstring(L, ud, (size_t *)&smp->data.u.str.len);
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100503 break;
504
505 case LUA_TUSERDATA:
506 case LUA_TNIL:
507 case LUA_TTABLE:
508 case LUA_TFUNCTION:
509 case LUA_TTHREAD:
510 case LUA_TLIGHTUSERDATA:
Thierry FOURNIER93405e12015-08-26 14:19:03 +0200511 case LUA_TNONE:
512 default:
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +0200513 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200514 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100515 break;
516 }
517 return 1;
518}
519
520/* This function check the "argp" builded by another conversion function
521 * is in accord with the expected argp defined by the "mask". The fucntion
522 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100523 *
524 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
525 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100526 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100527__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
528 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100529{
530 int min_arg;
531 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100532 struct proxy *px;
533 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100534
535 idx = 0;
536 min_arg = ARGM(mask);
537 mask >>= ARGM_BITS;
538
539 while (1) {
540
541 /* Check oversize. */
542 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100543 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100544 }
545
546 /* Check for mandatory arguments. */
547 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100548 if (idx < min_arg) {
549
550 /* If miss other argument than the first one, we return an error. */
551 if (idx > 0)
552 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
553
554 /* If first argument have a certain type, some default values
555 * may be used. See the function smp_resolve_args().
556 */
557 switch (mask & ARGT_MASK) {
558
559 case ARGT_FE:
560 if (!(p->cap & PR_CAP_FE))
561 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
562 argp[idx].data.prx = p;
563 argp[idx].type = ARGT_FE;
564 argp[idx+1].type = ARGT_STOP;
565 break;
566
567 case ARGT_BE:
568 if (!(p->cap & PR_CAP_BE))
569 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
570 argp[idx].data.prx = p;
571 argp[idx].type = ARGT_BE;
572 argp[idx+1].type = ARGT_STOP;
573 break;
574
575 case ARGT_TAB:
576 argp[idx].data.prx = p;
577 argp[idx].type = ARGT_TAB;
578 argp[idx+1].type = ARGT_STOP;
579 break;
580
581 default:
582 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
583 break;
584 }
585 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100586 return 0;
587 }
588
589 /* Check for exceed the number of requiered argument. */
590 if ((mask & ARGT_MASK) == ARGT_STOP &&
591 argp[idx].type != ARGT_STOP) {
592 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
593 }
594
595 if ((mask & ARGT_MASK) == ARGT_STOP &&
596 argp[idx].type == ARGT_STOP) {
597 return 0;
598 }
599
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100600 /* Convert some argument types. */
601 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100602 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100603 if (argp[idx].type != ARGT_SINT)
604 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
605 argp[idx].type = ARGT_SINT;
606 break;
607
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100608 case ARGT_TIME:
609 if (argp[idx].type != ARGT_SINT)
610 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200611 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100612 break;
613
614 case ARGT_SIZE:
615 if (argp[idx].type != ARGT_SINT)
616 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200617 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100618 break;
619
620 case ARGT_FE:
621 if (argp[idx].type != ARGT_STR)
622 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
623 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
624 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200625 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100626 if (!argp[idx].data.prx)
627 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
628 argp[idx].type = ARGT_FE;
629 break;
630
631 case ARGT_BE:
632 if (argp[idx].type != ARGT_STR)
633 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
634 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
635 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200636 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100637 if (!argp[idx].data.prx)
638 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
639 argp[idx].type = ARGT_BE;
640 break;
641
642 case ARGT_TAB:
643 if (argp[idx].type != ARGT_STR)
644 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
645 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
646 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200647 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100648 if (!argp[idx].data.prx)
649 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
650 argp[idx].type = ARGT_TAB;
651 break;
652
653 case ARGT_SRV:
654 if (argp[idx].type != ARGT_STR)
655 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
656 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
657 trash.str[argp[idx].data.str.len] = 0;
658 sname = strrchr(trash.str, '/');
659 if (sname) {
660 *sname++ = '\0';
661 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200662 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100663 if (!px)
664 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
665 }
666 else {
667 sname = trash.str;
668 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100669 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100670 argp[idx].data.srv = findserver(px, sname);
671 if (!argp[idx].data.srv)
672 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
673 argp[idx].type = ARGT_SRV;
674 break;
675
676 case ARGT_IPV4:
677 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
678 trash.str[argp[idx].data.str.len] = 0;
679 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
680 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
681 argp[idx].type = ARGT_IPV4;
682 break;
683
684 case ARGT_MSK4:
685 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
686 trash.str[argp[idx].data.str.len] = 0;
687 if (!str2mask(trash.str, &argp[idx].data.ipv4))
688 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
689 argp[idx].type = ARGT_MSK4;
690 break;
691
692 case ARGT_IPV6:
693 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
694 trash.str[argp[idx].data.str.len] = 0;
695 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
696 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
697 argp[idx].type = ARGT_IPV6;
698 break;
699
700 case ARGT_MSK6:
701 case ARGT_MAP:
702 case ARGT_REG:
703 case ARGT_USR:
704 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100705 break;
706 }
707
708 /* Check for type of argument. */
709 if ((mask & ARGT_MASK) != argp[idx].type) {
710 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
711 arg_type_names[(mask & ARGT_MASK)],
712 arg_type_names[argp[idx].type & ARGT_MASK]);
713 WILL_LJMP(luaL_argerror(L, first + idx, msg));
714 }
715
716 /* Next argument. */
717 mask >>= ARGT_BITS;
718 idx++;
719 }
720}
721
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100722/*
723 * The following functions are used to make correspondance between the the
724 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100725 *
726 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100727 * - hlua_sethlua : create the association between hlua context and lua_state.
728 */
729static inline struct hlua *hlua_gethlua(lua_State *L)
730{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100731 struct hlua **hlua = lua_getextraspace(L);
732 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100733}
734static inline void hlua_sethlua(struct hlua *hlua)
735{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100736 struct hlua **hlua_store = lua_getextraspace(hlua->T);
737 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100738}
739
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100740/* This function is used to send logs. It try to send on screen (stderr)
741 * and on the default syslog server.
742 */
743static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
744{
745 struct tm tm;
746 char *p;
747
748 /* Cleanup the log message. */
749 p = trash.str;
750 for (; *msg != '\0'; msg++, p++) {
751 if (p >= trash.str + trash.size - 1)
752 return;
753 if (isprint(*msg))
754 *p = *msg;
755 else
756 *p = '.';
757 }
758 *p = '\0';
759
760 send_log(px, level, "%s", trash.str);
761 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
Willy Tarreaua678b432015-08-28 10:14:59 +0200762 get_localtime(date.tv_sec, &tm);
763 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100764 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
765 (int)getpid(), trash.str);
766 fflush(stderr);
767 }
768}
769
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100770/* This function just ensure that the yield will be always
771 * returned with a timeout and permit to set some flags
772 */
773__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100774 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100775{
776 struct hlua *hlua = hlua_gethlua(L);
777
778 /* Set the wake timeout. If timeout is required, we set
779 * the expiration time.
780 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100781 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100782
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100783 hlua->flags |= flags;
784
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100785 /* Process the yield. */
786 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
787}
788
Willy Tarreau87b09662015-04-03 00:22:06 +0200789/* This function initialises the Lua environment stored in the stream.
790 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100791 * an LUA coroutine. It can not be use to crete the main LUA context.
792 */
793int hlua_ctx_init(struct hlua *lua, struct task *task)
794{
795 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100796 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100797 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100798 lua->T = lua_newthread(gL.T);
799 if (!lua->T) {
800 lua->Tref = LUA_REFNIL;
801 return 0;
802 }
803 hlua_sethlua(lua);
804 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
805 lua->task = task;
806 return 1;
807}
808
Willy Tarreau87b09662015-04-03 00:22:06 +0200809/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100810 * is destroyed. The destroy also the memory context. The struct "lua"
811 * is not freed.
812 */
813void hlua_ctx_destroy(struct hlua *lua)
814{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100815 if (!lua->T)
816 return;
817
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100818 /* Purge all the pending signals. */
819 hlua_com_purge(lua);
820
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100821 /* The thread is garbage collected by Lua. */
822 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
823 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
824}
825
826/* This function is used to restore the Lua context when a coroutine
827 * fails. This function copy the common memory between old coroutine
828 * and the new coroutine. The old coroutine is destroyed, and its
829 * replaced by the new coroutine.
830 * If the flag "keep_msg" is set, the last entry of the old is assumed
831 * as string error message and it is copied in the new stack.
832 */
833static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
834{
835 lua_State *T;
836 int new_ref;
837
838 /* Renew the main LUA stack doesn't have sense. */
839 if (lua == &gL)
840 return 0;
841
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100842 /* New Lua coroutine. */
843 T = lua_newthread(gL.T);
844 if (!T)
845 return 0;
846
847 /* Copy last error message. */
848 if (keep_msg)
849 lua_xmove(lua->T, T, 1);
850
851 /* Copy data between the coroutines. */
852 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
853 lua_xmove(lua->T, T, 1);
854 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
855
856 /* Destroy old data. */
857 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
858
859 /* The thread is garbage collected by Lua. */
860 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
861
862 /* Fill the struct with the new coroutine values. */
863 lua->Mref = new_ref;
864 lua->T = T;
865 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
866
867 /* Set context. */
868 hlua_sethlua(lua);
869
870 return 1;
871}
872
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100873void hlua_hook(lua_State *L, lua_Debug *ar)
874{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100875 struct hlua *hlua = hlua_gethlua(L);
876
877 /* Lua cannot yield when its returning from a function,
878 * so, we can fix the interrupt hook to 1 instruction,
879 * expecting that the function is finnished.
880 */
881 if (lua_gethookmask(L) & LUA_MASKRET) {
882 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
883 return;
884 }
885
886 /* restore the interrupt condition. */
887 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
888
889 /* If we interrupt the Lua processing in yieldable state, we yield.
890 * If the state is not yieldable, trying yield causes an error.
891 */
892 if (lua_isyieldable(L))
893 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
894
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100895 /* If we cannot yield, update the clock and check the timeout. */
896 tv_update_date(0, 1);
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100897 if (tick_is_expired(hlua->expire, now_ms)) {
898 lua_pushfstring(L, "execution timeout");
899 WILL_LJMP(lua_error(L));
900 }
901
902 /* Try to interrupt the process at the end of the current
903 * unyieldable function.
904 */
905 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100906}
907
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100908/* This function start or resumes the Lua stack execution. If the flag
909 * "yield_allowed" if no set and the LUA stack execution returns a yield
910 * The function return an error.
911 *
912 * The function can returns 4 values:
913 * - HLUA_E_OK : The execution is terminated without any errors.
914 * - HLUA_E_AGAIN : The execution must continue at the next associated
915 * task wakeup.
916 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
917 * the top of the stack.
918 * - HLUA_E_ERR : An error has occured without error message.
919 *
920 * If an error occured, the stack is renewed and it is ready to run new
921 * LUA code.
922 */
923static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
924{
925 int ret;
926 const char *msg;
927
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100928 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100929
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100930 /* If we want to resume the task, then check first the execution timeout.
931 * if it is reached, we can interrupt the Lua processing.
932 */
933 if (tick_is_expired(lua->expire, now_ms))
934 goto timeout_reached;
935
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100936resume_execution:
937
938 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
939 * instructions. it is used for preventing infinite loops.
940 */
941 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
942
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100943 /* Remove all flags except the running flags. */
944 lua->flags = HLUA_RUN;
945
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100946 /* Call the function. */
947 ret = lua_resume(lua->T, gL.T, lua->nargs);
948 switch (ret) {
949
950 case LUA_OK:
951 ret = HLUA_E_OK;
952 break;
953
954 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100955 /* Check if the execution timeout is expired. It it is the case, we
956 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100957 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100958 if (tick_is_expired(lua->expire, now_ms)) {
959
960timeout_reached:
961
962 lua_settop(lua->T, 0); /* Empty the stack. */
963 if (!lua_checkstack(lua->T, 1)) {
964 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100965 break;
966 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100967 lua_pushfstring(lua->T, "execution timeout");
968 ret = HLUA_E_ERRMSG;
969 break;
970 }
971 /* Process the forced yield. if the general yield is not allowed or
972 * if no task were associated this the current Lua execution
973 * coroutine, we resume the execution. Else we want to return in the
974 * scheduler and we want to be waked up again, to continue the
975 * current Lua execution. So we schedule our own task.
976 */
977 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100978 if (!yield_allowed || !lua->task)
979 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100980 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100981 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100982 if (!yield_allowed) {
983 lua_settop(lua->T, 0); /* Empty the stack. */
984 if (!lua_checkstack(lua->T, 1)) {
985 ret = HLUA_E_ERR;
986 break;
987 }
988 lua_pushfstring(lua->T, "yield not allowed");
989 ret = HLUA_E_ERRMSG;
990 break;
991 }
992 ret = HLUA_E_AGAIN;
993 break;
994
995 case LUA_ERRRUN:
Thierry FOURNIER0a99b892015-08-26 00:14:17 +0200996
997 /* Special exit case. The traditionnal exit is returned as an error
998 * because the errors ares the only one mean to return immediately
999 * from and lua execution.
1000 */
1001 if (lua->flags & HLUA_EXIT) {
1002 ret = HLUA_E_OK;
Thierry FOURNIERe1587b32015-08-28 09:54:13 +02001003 hlua_ctx_renew(lua, 0);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001004 break;
1005 }
1006
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001007 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001008 if (!lua_checkstack(lua->T, 1)) {
1009 ret = HLUA_E_ERR;
1010 break;
1011 }
1012 msg = lua_tostring(lua->T, -1);
1013 lua_settop(lua->T, 0); /* Empty the stack. */
1014 lua_pop(lua->T, 1);
1015 if (msg)
1016 lua_pushfstring(lua->T, "runtime error: %s", msg);
1017 else
1018 lua_pushfstring(lua->T, "unknown runtime error");
1019 ret = HLUA_E_ERRMSG;
1020 break;
1021
1022 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001023 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001024 lua_settop(lua->T, 0); /* Empty the stack. */
1025 if (!lua_checkstack(lua->T, 1)) {
1026 ret = HLUA_E_ERR;
1027 break;
1028 }
1029 lua_pushfstring(lua->T, "out of memory error");
1030 ret = HLUA_E_ERRMSG;
1031 break;
1032
1033 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001034 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001035 if (!lua_checkstack(lua->T, 1)) {
1036 ret = HLUA_E_ERR;
1037 break;
1038 }
1039 msg = lua_tostring(lua->T, -1);
1040 lua_settop(lua->T, 0); /* Empty the stack. */
1041 lua_pop(lua->T, 1);
1042 if (msg)
1043 lua_pushfstring(lua->T, "message handler error: %s", msg);
1044 else
1045 lua_pushfstring(lua->T, "message handler error");
1046 ret = HLUA_E_ERRMSG;
1047 break;
1048
1049 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001050 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001051 lua_settop(lua->T, 0); /* Empty the stack. */
1052 if (!lua_checkstack(lua->T, 1)) {
1053 ret = HLUA_E_ERR;
1054 break;
1055 }
1056 lua_pushfstring(lua->T, "unknonwn error");
1057 ret = HLUA_E_ERRMSG;
1058 break;
1059 }
1060
1061 switch (ret) {
1062 case HLUA_E_AGAIN:
1063 break;
1064
1065 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001066 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001067 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001068 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001069 break;
1070
1071 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001072 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001073 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001074 hlua_ctx_renew(lua, 0);
1075 break;
1076
1077 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001078 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001079 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001080 break;
1081 }
1082
1083 return ret;
1084}
1085
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001086/* This function exit the current code. */
1087__LJMP static int hlua_done(lua_State *L)
1088{
1089 struct hlua *hlua = hlua_gethlua(L);
1090
1091 hlua->flags |= HLUA_EXIT;
1092 WILL_LJMP(lua_error(L));
1093
1094 return 0;
1095}
1096
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001097/* This function is an LUA binding. It provides a function
1098 * for deleting ACL from a referenced ACL file.
1099 */
1100__LJMP static int hlua_del_acl(lua_State *L)
1101{
1102 const char *name;
1103 const char *key;
1104 struct pat_ref *ref;
1105
1106 MAY_LJMP(check_args(L, 2, "del_acl"));
1107
1108 name = MAY_LJMP(luaL_checkstring(L, 1));
1109 key = MAY_LJMP(luaL_checkstring(L, 2));
1110
1111 ref = pat_ref_lookup(name);
1112 if (!ref)
1113 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1114
1115 pat_ref_delete(ref, key);
1116 return 0;
1117}
1118
1119/* This function is an LUA binding. It provides a function
1120 * for deleting map entry from a referenced map file.
1121 */
1122static int hlua_del_map(lua_State *L)
1123{
1124 const char *name;
1125 const char *key;
1126 struct pat_ref *ref;
1127
1128 MAY_LJMP(check_args(L, 2, "del_map"));
1129
1130 name = MAY_LJMP(luaL_checkstring(L, 1));
1131 key = MAY_LJMP(luaL_checkstring(L, 2));
1132
1133 ref = pat_ref_lookup(name);
1134 if (!ref)
1135 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1136
1137 pat_ref_delete(ref, key);
1138 return 0;
1139}
1140
1141/* This function is an LUA binding. It provides a function
1142 * for adding ACL pattern from a referenced ACL file.
1143 */
1144static int hlua_add_acl(lua_State *L)
1145{
1146 const char *name;
1147 const char *key;
1148 struct pat_ref *ref;
1149
1150 MAY_LJMP(check_args(L, 2, "add_acl"));
1151
1152 name = MAY_LJMP(luaL_checkstring(L, 1));
1153 key = MAY_LJMP(luaL_checkstring(L, 2));
1154
1155 ref = pat_ref_lookup(name);
1156 if (!ref)
1157 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1158
1159 if (pat_ref_find_elt(ref, key) == NULL)
1160 pat_ref_add(ref, key, NULL, NULL);
1161 return 0;
1162}
1163
1164/* This function is an LUA binding. It provides a function
1165 * for setting map pattern and sample from a referenced map
1166 * file.
1167 */
1168static int hlua_set_map(lua_State *L)
1169{
1170 const char *name;
1171 const char *key;
1172 const char *value;
1173 struct pat_ref *ref;
1174
1175 MAY_LJMP(check_args(L, 3, "set_map"));
1176
1177 name = MAY_LJMP(luaL_checkstring(L, 1));
1178 key = MAY_LJMP(luaL_checkstring(L, 2));
1179 value = MAY_LJMP(luaL_checkstring(L, 3));
1180
1181 ref = pat_ref_lookup(name);
1182 if (!ref)
1183 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1184
1185 if (pat_ref_find_elt(ref, key) != NULL)
1186 pat_ref_set(ref, key, value, NULL);
1187 else
1188 pat_ref_add(ref, key, value, NULL);
1189 return 0;
1190}
1191
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001192/* A class is a lot of memory that contain data. This data can be a table,
1193 * an integer or user data. This data is associated with a metatable. This
1194 * metatable have an original version registred in the global context with
1195 * the name of the object (_G[<name>] = <metable> ).
1196 *
1197 * A metable is a table that modify the standard behavior of a standard
1198 * access to the associated data. The entries of this new metatable are
1199 * defined as is:
1200 *
1201 * http://lua-users.org/wiki/MetatableEvents
1202 *
1203 * __index
1204 *
1205 * we access an absent field in a table, the result is nil. This is
1206 * true, but it is not the whole truth. Actually, such access triggers
1207 * the interpreter to look for an __index metamethod: If there is no
1208 * such method, as usually happens, then the access results in nil;
1209 * otherwise, the metamethod will provide the result.
1210 *
1211 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1212 * the key does not appear in the table, but the metatable has an __index
1213 * property:
1214 *
1215 * - if the value is a function, the function is called, passing in the
1216 * table and the key; the return value of that function is returned as
1217 * the result.
1218 *
1219 * - if the value is another table, the value of the key in that table is
1220 * asked for and returned (and if it doesn't exist in that table, but that
1221 * table's metatable has an __index property, then it continues on up)
1222 *
1223 * - Use "rawget(myTable,key)" to skip this metamethod.
1224 *
1225 * http://www.lua.org/pil/13.4.1.html
1226 *
1227 * __newindex
1228 *
1229 * Like __index, but control property assignment.
1230 *
1231 * __mode - Control weak references. A string value with one or both
1232 * of the characters 'k' and 'v' which specifies that the the
1233 * keys and/or values in the table are weak references.
1234 *
1235 * __call - Treat a table like a function. When a table is followed by
1236 * parenthesis such as "myTable( 'foo' )" and the metatable has
1237 * a __call key pointing to a function, that function is invoked
1238 * (passing any specified arguments) and the return value is
1239 * returned.
1240 *
1241 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1242 * called, if the metatable for myTable has a __metatable
1243 * key, the value of that key is returned instead of the
1244 * actual metatable.
1245 *
1246 * __tostring - Control string representation. When the builtin
1247 * "tostring( myTable )" function is called, if the metatable
1248 * for myTable has a __tostring property set to a function,
1249 * that function is invoked (passing myTable to it) and the
1250 * return value is used as the string representation.
1251 *
1252 * __len - Control table length. When the table length is requested using
1253 * the length operator ( '#' ), if the metatable for myTable has
1254 * a __len key pointing to a function, that function is invoked
1255 * (passing myTable to it) and the return value used as the value
1256 * of "#myTable".
1257 *
1258 * __gc - Userdata finalizer code. When userdata is set to be garbage
1259 * collected, if the metatable has a __gc field pointing to a
1260 * function, that function is first invoked, passing the userdata
1261 * to it. The __gc metamethod is not called for tables.
1262 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1263 *
1264 * Special metamethods for redefining standard operators:
1265 * http://www.lua.org/pil/13.1.html
1266 *
1267 * __add "+"
1268 * __sub "-"
1269 * __mul "*"
1270 * __div "/"
1271 * __unm "!"
1272 * __pow "^"
1273 * __concat ".."
1274 *
1275 * Special methods for redfining standar relations
1276 * http://www.lua.org/pil/13.2.html
1277 *
1278 * __eq "=="
1279 * __lt "<"
1280 * __le "<="
1281 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001282
1283/*
1284 *
1285 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001286 * Class Map
1287 *
1288 *
1289 */
1290
1291/* Returns a struct hlua_map if the stack entry "ud" is
1292 * a class session, otherwise it throws an error.
1293 */
1294__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1295{
1296 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1297}
1298
1299/* This function is the map constructor. It don't need
1300 * the class Map object. It creates and return a new Map
1301 * object. It must be called only during "body" or "init"
1302 * context because it process some filesystem accesses.
1303 */
1304__LJMP static int hlua_map_new(struct lua_State *L)
1305{
1306 const char *fn;
1307 int match = PAT_MATCH_STR;
1308 struct sample_conv conv;
1309 const char *file = "";
1310 int line = 0;
1311 lua_Debug ar;
1312 char *err = NULL;
1313 struct arg args[2];
1314
1315 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1316 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1317
1318 fn = MAY_LJMP(luaL_checkstring(L, 1));
1319
1320 if (lua_gettop(L) >= 2) {
1321 match = MAY_LJMP(luaL_checkinteger(L, 2));
1322 if (match < 0 || match >= PAT_MATCH_NUM)
1323 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1324 }
1325
1326 /* Get Lua filename and line number. */
1327 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1328 lua_getinfo(L, "Sl", &ar); /* get info about it */
1329 if (ar.currentline > 0) { /* is there info? */
1330 file = ar.short_src;
1331 line = ar.currentline;
1332 }
1333 }
1334
1335 /* fill fake sample_conv struct. */
1336 conv.kw = ""; /* unused. */
1337 conv.process = NULL; /* unused. */
1338 conv.arg_mask = 0; /* unused. */
1339 conv.val_args = NULL; /* unused. */
1340 conv.out_type = SMP_T_STR;
1341 conv.private = (void *)(long)match;
1342 switch (match) {
1343 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1344 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1345 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1346 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1347 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1348 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1349 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001350 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001351 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1352 default:
1353 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1354 }
1355
1356 /* fill fake args. */
1357 args[0].type = ARGT_STR;
1358 args[0].data.str.str = (char *)fn;
1359 args[1].type = ARGT_STOP;
1360
1361 /* load the map. */
1362 if (!sample_load_map(args, &conv, file, line, &err)) {
1363 /* error case: we cant use luaL_error because we must
1364 * free the err variable.
1365 */
1366 luaL_where(L, 1);
1367 lua_pushfstring(L, "'new': %s.", err);
1368 lua_concat(L, 2);
1369 free(err);
1370 WILL_LJMP(lua_error(L));
1371 }
1372
1373 /* create the lua object. */
1374 lua_newtable(L);
1375 lua_pushlightuserdata(L, args[0].data.map);
1376 lua_rawseti(L, -2, 0);
1377
1378 /* Pop a class Map metatable and affect it to the userdata. */
1379 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1380 lua_setmetatable(L, -2);
1381
1382
1383 return 1;
1384}
1385
1386__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1387{
1388 struct map_descriptor *desc;
1389 struct pattern *pat;
1390 struct sample smp;
1391
1392 MAY_LJMP(check_args(L, 2, "lookup"));
1393 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001394 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001395 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001396 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001397 }
1398 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001399 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001400 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001401 smp.data.u.str.str = (char *)MAY_LJMP(luaL_checklstring(L, 2, (size_t *)&smp.data.u.str.len));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001402 }
1403
1404 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001405 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001406 if (str)
1407 lua_pushstring(L, "");
1408 else
1409 lua_pushnil(L);
1410 return 1;
1411 }
1412
1413 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001414 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001415 return 1;
1416}
1417
1418__LJMP static int hlua_map_lookup(struct lua_State *L)
1419{
1420 return _hlua_map_lookup(L, 0);
1421}
1422
1423__LJMP static int hlua_map_slookup(struct lua_State *L)
1424{
1425 return _hlua_map_lookup(L, 1);
1426}
1427
1428/*
1429 *
1430 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001431 * Class Socket
1432 *
1433 *
1434 */
1435
1436__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1437{
1438 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1439}
1440
1441/* This function is the handler called for each I/O on the established
1442 * connection. It is used for notify space avalaible to send or data
1443 * received.
1444 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001445static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001446{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001447 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001448 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001449
Willy Tarreau87b09662015-04-03 00:22:06 +02001450 /* Wakeup the main stream if the client connection is closed. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001451 if (!c || channel_output_closed(si_ic(si)) || channel_input_closed(si_oc(si))) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001452 if (appctx->ctx.hlua.socket) {
1453 appctx->ctx.hlua.socket->s = NULL;
1454 appctx->ctx.hlua.socket = NULL;
1455 }
1456 si_shutw(si);
1457 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001458 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001459 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1460 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001461 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001462 }
1463
1464 if (!(c->flags & CO_FL_CONNECTED))
Willy Tarreaud4da1962015-04-20 01:31:23 +02001465 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001466
1467 /* This function is called after the connect. */
1468 appctx->ctx.hlua.connected = 1;
1469
1470 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001471 if (channel_may_recv(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001472 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1473
1474 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001475 if (channel_is_empty(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001476 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1477}
1478
Willy Tarreau87b09662015-04-03 00:22:06 +02001479/* This function is called when the "struct stream" is destroyed.
1480 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001481 * Wake all the pending signals.
1482 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001483static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001484{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001485 /* Remove my link in the original object. */
1486 if (appctx->ctx.hlua.socket)
1487 appctx->ctx.hlua.socket->s = NULL;
1488
1489 /* Wake all the task waiting for me. */
1490 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1491 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1492}
1493
1494/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001495 * uses this object. If the stream does not exists, just quit.
1496 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001497 * pending signal can rest in the read and write lists. destroy
1498 * it.
1499 */
1500__LJMP static int hlua_socket_gc(lua_State *L)
1501{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001502 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001503 struct appctx *appctx;
1504
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001505 MAY_LJMP(check_args(L, 1, "__gc"));
1506
1507 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001508 if (!socket->s)
1509 return 0;
1510
Willy Tarreau87b09662015-04-03 00:22:06 +02001511 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001512 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001513 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001514 socket->s = NULL;
1515 appctx->ctx.hlua.socket = NULL;
1516
1517 return 0;
1518}
1519
1520/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001521 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001522 */
1523__LJMP static int hlua_socket_close(lua_State *L)
1524{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001525 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001526 struct appctx *appctx;
1527
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001528 MAY_LJMP(check_args(L, 1, "close"));
1529
1530 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001531 if (!socket->s)
1532 return 0;
1533
Willy Tarreau87b09662015-04-03 00:22:06 +02001534 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001535 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001536 appctx = objt_appctx(socket->s->si[0].end);
1537 appctx->ctx.hlua.socket = NULL;
1538 socket->s = NULL;
1539
1540 return 0;
1541}
1542
1543/* This Lua function assumes that the stack contain three parameters.
1544 * 1 - USERDATA containing a struct socket
1545 * 2 - INTEGER with values of the macro defined below
1546 * If the integer is -1, we must read at most one line.
1547 * If the integer is -2, we ust read all the data until the
1548 * end of the stream.
1549 * If the integer is positive value, we must read a number of
1550 * bytes corresponding to this value.
1551 */
1552#define HLSR_READ_LINE (-1)
1553#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001554__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001555{
1556 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1557 int wanted = lua_tointeger(L, 2);
1558 struct hlua *hlua = hlua_gethlua(L);
1559 struct appctx *appctx;
1560 int len;
1561 int nblk;
1562 char *blk1;
1563 int len1;
1564 char *blk2;
1565 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001566 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001567 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001568
1569 /* Check if this lua stack is schedulable. */
1570 if (!hlua || !hlua->task)
1571 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1572 "'frontend', 'backend' or 'task'"));
1573
1574 /* check for connection closed. If some data where read, return it. */
1575 if (!socket->s)
1576 goto connection_closed;
1577
Willy Tarreau94aa6172015-03-13 14:19:06 +01001578 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001579 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001580 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001581 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001582 if (nblk < 0) /* Connection close. */
1583 goto connection_closed;
1584 if (nblk == 0) /* No data avalaible. */
1585 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001586
1587 /* remove final \r\n. */
1588 if (nblk == 1) {
1589 if (blk1[len1-1] == '\n') {
1590 len1--;
1591 skip_at_end++;
1592 if (blk1[len1-1] == '\r') {
1593 len1--;
1594 skip_at_end++;
1595 }
1596 }
1597 }
1598 else {
1599 if (blk2[len2-1] == '\n') {
1600 len2--;
1601 skip_at_end++;
1602 if (blk2[len2-1] == '\r') {
1603 len2--;
1604 skip_at_end++;
1605 }
1606 }
1607 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001608 }
1609
1610 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001611 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001612 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001613 if (nblk < 0) /* Connection close. */
1614 goto connection_closed;
1615 if (nblk == 0) /* No data avalaible. */
1616 goto connection_empty;
1617 }
1618
1619 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001620 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001621 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001622 if (nblk < 0) /* Connection close. */
1623 goto connection_closed;
1624 if (nblk == 0) /* No data avalaible. */
1625 goto connection_empty;
1626
1627 if (len1 > wanted) {
1628 nblk = 1;
1629 len1 = wanted;
1630 } if (nblk == 2 && len1 + len2 > wanted)
1631 len2 = wanted - len1;
1632 }
1633
1634 len = len1;
1635
1636 luaL_addlstring(&socket->b, blk1, len1);
1637 if (nblk == 2) {
1638 len += len2;
1639 luaL_addlstring(&socket->b, blk2, len2);
1640 }
1641
1642 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001643 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001644
1645 /* Don't wait anything. */
Willy Tarreau828824a2015-04-19 17:20:03 +02001646 si_applet_done(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001647
1648 /* If the pattern reclaim to read all the data
1649 * in the connection, got out.
1650 */
1651 if (wanted == HLSR_READ_ALL)
1652 goto connection_empty;
1653 else if (wanted >= 0 && len < wanted)
1654 goto connection_empty;
1655
1656 /* Return result. */
1657 luaL_pushresult(&socket->b);
1658 return 1;
1659
1660connection_closed:
1661
1662 /* If the buffer containds data. */
1663 if (socket->b.n > 0) {
1664 luaL_pushresult(&socket->b);
1665 return 1;
1666 }
1667 lua_pushnil(L);
1668 lua_pushstring(L, "connection closed.");
1669 return 2;
1670
1671connection_empty:
1672
1673 appctx = objt_appctx(socket->s->si[0].end);
1674 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1675 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001676 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001677 return 0;
1678}
1679
1680/* This Lus function gets two parameters. The first one can be string
1681 * or a number. If the string is "*l", the user require one line. If
1682 * the string is "*a", the user require all the content of the stream.
1683 * If the value is a number, the user require a number of bytes equal
1684 * to the value. The default value is "*l" (a line).
1685 *
1686 * This paraeter with a variable type is converted in integer. This
1687 * integer takes this values:
1688 * -1 : read a line
1689 * -2 : read all the stream
1690 * >0 : amount if bytes.
1691 *
1692 * The second parameter is optinal. It contains a string that must be
1693 * concatenated with the read data.
1694 */
1695__LJMP static int hlua_socket_receive(struct lua_State *L)
1696{
1697 int wanted = HLSR_READ_LINE;
1698 const char *pattern;
1699 int type;
1700 char *error;
1701 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001702 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001703
1704 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1705 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1706
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001707 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001708
1709 /* check for pattern. */
1710 if (lua_gettop(L) >= 2) {
1711 type = lua_type(L, 2);
1712 if (type == LUA_TSTRING) {
1713 pattern = lua_tostring(L, 2);
1714 if (strcmp(pattern, "*a") == 0)
1715 wanted = HLSR_READ_ALL;
1716 else if (strcmp(pattern, "*l") == 0)
1717 wanted = HLSR_READ_LINE;
1718 else {
1719 wanted = strtoll(pattern, &error, 10);
1720 if (*error != '\0')
1721 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1722 }
1723 }
1724 else if (type == LUA_TNUMBER) {
1725 wanted = lua_tointeger(L, 2);
1726 if (wanted < 0)
1727 WILL_LJMP(luaL_error(L, "Unsupported size."));
1728 }
1729 }
1730
1731 /* Set pattern. */
1732 lua_pushinteger(L, wanted);
1733 lua_replace(L, 2);
1734
1735 /* init bufffer, and fiil it wih prefix. */
1736 luaL_buffinit(L, &socket->b);
1737
1738 /* Check prefix. */
1739 if (lua_gettop(L) >= 3) {
1740 if (lua_type(L, 3) != LUA_TSTRING)
1741 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1742 pattern = lua_tolstring(L, 3, &len);
1743 luaL_addlstring(&socket->b, pattern, len);
1744 }
1745
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001746 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001747}
1748
1749/* Write the Lua input string in the output buffer.
1750 * This fucntion returns a yield if no space are available.
1751 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001752static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001753{
1754 struct hlua_socket *socket;
1755 struct hlua *hlua = hlua_gethlua(L);
1756 struct appctx *appctx;
1757 size_t buf_len;
1758 const char *buf;
1759 int len;
1760 int send_len;
1761 int sent;
1762
1763 /* Check if this lua stack is schedulable. */
1764 if (!hlua || !hlua->task)
1765 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1766 "'frontend', 'backend' or 'task'"));
1767
1768 /* Get object */
1769 socket = MAY_LJMP(hlua_checksocket(L, 1));
1770 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001771 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001772
1773 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001774 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001775 lua_pushinteger(L, -1);
1776 return 1;
1777 }
1778
1779 /* Update the input buffer data. */
1780 buf += sent;
1781 send_len = buf_len - sent;
1782
1783 /* All the data are sent. */
1784 if (sent >= buf_len)
1785 return 1; /* Implicitly return the length sent. */
1786
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001787 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1788 * the request buffer if its not required.
1789 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001790 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001791 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001792 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001793 goto hlua_socket_write_yield_return;
1794 }
1795 }
1796
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001797 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001798 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001799 if (len <= 0)
1800 goto hlua_socket_write_yield_return;
1801
1802 /* send data */
1803 if (len < send_len)
1804 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001805 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001806
1807 /* "Not enough space" (-1), "Buffer too little to contain
1808 * the data" (-2) are not expected because the available length
1809 * is tested.
1810 * Other unknown error are also not expected.
1811 */
1812 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001813 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001814 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001815
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001816 MAY_LJMP(hlua_socket_close(L));
1817 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001818 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001819 return 1;
1820 }
1821
1822 /* update buffers. */
Willy Tarreau828824a2015-04-19 17:20:03 +02001823 si_applet_done(&socket->s->si[0]);
Willy Tarreau94aa6172015-03-13 14:19:06 +01001824 socket->s->req.rex = TICK_ETERNITY;
1825 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001826
1827 /* Update length sent. */
1828 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001829 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001830
1831 /* All the data buffer is sent ? */
1832 if (sent + len >= buf_len)
1833 return 1;
1834
1835hlua_socket_write_yield_return:
1836 appctx = objt_appctx(socket->s->si[0].end);
1837 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1838 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001839 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001840 return 0;
1841}
1842
1843/* This function initiate the send of data. It just check the input
1844 * parameters and push an integer in the Lua stack that contain the
1845 * amount of data writed in the buffer. This is used by the function
1846 * "hlua_socket_write_yield" that can yield.
1847 *
1848 * The Lua function gets between 3 and 4 parameters. The first one is
1849 * the associated object. The second is a string buffer. The third is
1850 * a facultative integer that represents where is the buffer position
1851 * of the start of the data that can send. The first byte is the
1852 * position "1". The default value is "1". The fourth argument is a
1853 * facultative integer that represents where is the buffer position
1854 * of the end of the data that can send. The default is the last byte.
1855 */
1856static int hlua_socket_send(struct lua_State *L)
1857{
1858 int i;
1859 int j;
1860 const char *buf;
1861 size_t buf_len;
1862
1863 /* Check number of arguments. */
1864 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1865 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1866
1867 /* Get the string. */
1868 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1869
1870 /* Get and check j. */
1871 if (lua_gettop(L) == 4) {
1872 j = MAY_LJMP(luaL_checkinteger(L, 4));
1873 if (j < 0)
1874 j = buf_len + j + 1;
1875 if (j > buf_len)
1876 j = buf_len + 1;
1877 lua_pop(L, 1);
1878 }
1879 else
1880 j = buf_len;
1881
1882 /* Get and check i. */
1883 if (lua_gettop(L) == 3) {
1884 i = MAY_LJMP(luaL_checkinteger(L, 3));
1885 if (i < 0)
1886 i = buf_len + i + 1;
1887 if (i > buf_len)
1888 i = buf_len + 1;
1889 lua_pop(L, 1);
1890 } else
1891 i = 1;
1892
1893 /* Check bth i and j. */
1894 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001895 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001896 return 1;
1897 }
1898 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001899 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001900 return 1;
1901 }
1902 if (i == 0)
1903 i = 1;
1904 if (j == 0)
1905 j = 1;
1906
1907 /* Pop the string. */
1908 lua_pop(L, 1);
1909
1910 /* Update the buffer length. */
1911 buf += i - 1;
1912 buf_len = j - i + 1;
1913 lua_pushlstring(L, buf, buf_len);
1914
1915 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001916 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001917
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001918 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001919}
1920
Willy Tarreau22b0a682015-06-17 19:43:49 +02001921#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001922__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1923{
1924 static char buffer[SOCKET_INFO_MAX_LEN];
1925 int ret;
1926 int len;
1927 char *p;
1928
1929 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1930 if (ret <= 0) {
1931 lua_pushnil(L);
1932 return 1;
1933 }
1934
1935 if (ret == AF_UNIX) {
1936 lua_pushstring(L, buffer+1);
1937 return 1;
1938 }
1939 else if (ret == AF_INET6) {
1940 buffer[0] = '[';
1941 len = strlen(buffer);
1942 buffer[len] = ']';
1943 len++;
1944 buffer[len] = ':';
1945 len++;
1946 p = buffer;
1947 }
1948 else if (ret == AF_INET) {
1949 p = buffer + 1;
1950 len = strlen(p);
1951 p[len] = ':';
1952 len++;
1953 }
1954 else {
1955 lua_pushnil(L);
1956 return 1;
1957 }
1958
1959 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1960 lua_pushnil(L);
1961 return 1;
1962 }
1963
1964 lua_pushstring(L, p);
1965 return 1;
1966}
1967
1968/* Returns information about the peer of the connection. */
1969__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1970{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001971 struct hlua_socket *socket;
1972 struct connection *conn;
1973
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001974 MAY_LJMP(check_args(L, 1, "getpeername"));
1975
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001976 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001977
1978 /* Check if the tcp object is avalaible. */
1979 if (!socket->s) {
1980 lua_pushnil(L);
1981 return 1;
1982 }
1983
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001984 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001985 if (!conn) {
1986 lua_pushnil(L);
1987 return 1;
1988 }
1989
1990 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1991 unsigned int salen = sizeof(conn->addr.to);
1992 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1993 lua_pushnil(L);
1994 return 1;
1995 }
1996 conn->flags |= CO_FL_ADDR_TO_SET;
1997 }
1998
1999 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2000}
2001
2002/* Returns information about my connection side. */
2003static int hlua_socket_getsockname(struct lua_State *L)
2004{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002005 struct hlua_socket *socket;
2006 struct connection *conn;
2007
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002008 MAY_LJMP(check_args(L, 1, "getsockname"));
2009
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002010 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002011
2012 /* Check if the tcp object is avalaible. */
2013 if (!socket->s) {
2014 lua_pushnil(L);
2015 return 1;
2016 }
2017
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002018 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002019 if (!conn) {
2020 lua_pushnil(L);
2021 return 1;
2022 }
2023
2024 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2025 unsigned int salen = sizeof(conn->addr.from);
2026 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2027 lua_pushnil(L);
2028 return 1;
2029 }
2030 conn->flags |= CO_FL_ADDR_FROM_SET;
2031 }
2032
2033 return hlua_socket_info(L, &conn->addr.from);
2034}
2035
2036/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002037static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002038 .obj_type = OBJ_TYPE_APPLET,
2039 .name = "<LUA_TCP>",
2040 .fct = hlua_socket_handler,
2041 .release = hlua_socket_release,
2042};
2043
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002044__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002045{
2046 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2047 struct hlua *hlua = hlua_gethlua(L);
2048 struct appctx *appctx;
2049
2050 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002051 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002052 lua_pushnil(L);
2053 lua_pushstring(L, "Can't connect");
2054 return 2;
2055 }
2056
2057 appctx = objt_appctx(socket->s->si[0].end);
2058
2059 /* Check for connection established. */
2060 if (appctx->ctx.hlua.connected) {
2061 lua_pushinteger(L, 1);
2062 return 1;
2063 }
2064
2065 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2066 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002067 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002068 return 0;
2069}
2070
2071/* This function fail or initite the connection. */
2072__LJMP static int hlua_socket_connect(struct lua_State *L)
2073{
2074 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002075 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002076 const char *ip;
2077 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002078 struct hlua *hlua;
2079 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002080
2081 MAY_LJMP(check_args(L, 3, "connect"));
2082
2083 /* Get args. */
2084 socket = MAY_LJMP(hlua_checksocket(L, 1));
2085 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002086 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002087
Willy Tarreau973a5422015-08-05 21:47:23 +02002088 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002089 if (!conn)
2090 WILL_LJMP(luaL_error(L, "connect: internal error"));
2091
2092 /* Parse ip address. */
2093 conn->addr.to.ss_family = AF_UNSPEC;
2094 if (!str2ip2(ip, &conn->addr.to, 0))
2095 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
2096
2097 /* Set port. */
2098 if (conn->addr.to.ss_family == AF_INET)
2099 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2100 else if (conn->addr.to.ss_family == AF_INET6)
2101 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2102
2103 /* it is important not to call the wakeup function directly but to
2104 * pass through task_wakeup(), because this one knows how to apply
2105 * priorities to tasks.
2106 */
2107 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
2108
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002109 hlua = hlua_gethlua(L);
2110 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002111
2112 /* inform the stream that we want to be notified whenever the
2113 * connection completes.
2114 */
2115 si_applet_cant_get(&socket->s->si[0]);
2116 si_applet_cant_put(&socket->s->si[0]);
2117
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002118 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2119 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002120 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002121
2122 return 0;
2123}
2124
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002125#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002126__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2127{
2128 struct hlua_socket *socket;
2129
2130 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2131 socket = MAY_LJMP(hlua_checksocket(L, 1));
2132 socket->s->target = &socket_ssl.obj_type;
2133 return MAY_LJMP(hlua_socket_connect(L));
2134}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002135#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002136
2137__LJMP static int hlua_socket_setoption(struct lua_State *L)
2138{
2139 return 0;
2140}
2141
2142__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2143{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002144 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002145 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002146
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002147 MAY_LJMP(check_args(L, 2, "settimeout"));
2148
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002149 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002150 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002151
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002152 socket->s->req.rto = tmout;
2153 socket->s->req.wto = tmout;
2154 socket->s->res.rto = tmout;
2155 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002156
2157 return 0;
2158}
2159
2160__LJMP static int hlua_socket_new(lua_State *L)
2161{
2162 struct hlua_socket *socket;
2163 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002164 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002165 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002166 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002167
2168 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002169 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002170 hlua_pusherror(L, "socket: full stack");
2171 goto out_fail_conf;
2172 }
2173
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002174 /* Create the object: obj[0] = userdata. */
2175 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002176 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002177 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002178 memset(socket, 0, sizeof(*socket));
2179
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002180 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002181 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002182 hlua_pusherror(L, "socket: uninitialized pools.");
2183 goto out_fail_conf;
2184 }
2185
Willy Tarreau87b09662015-04-03 00:22:06 +02002186 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002187 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2188 lua_setmetatable(L, -2);
2189
Willy Tarreaud420a972015-04-06 00:39:18 +02002190 /* Create the applet context */
2191 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002192 if (!appctx) {
2193 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002194 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002195 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002196
Willy Tarreaud420a972015-04-06 00:39:18 +02002197 appctx->ctx.hlua.socket = socket;
2198 appctx->ctx.hlua.connected = 0;
2199 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2200 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002201
Willy Tarreaud420a972015-04-06 00:39:18 +02002202 /* Now create a session, task and stream for this applet */
2203 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2204 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002205 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002206 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002207 }
2208
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002209 task = task_new();
2210 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002211 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002212 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002213 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002214 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002215
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002216 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002217 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002218 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002219 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002220 }
2221
Willy Tarreaud420a972015-04-06 00:39:18 +02002222 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002223 socket->s = strm;
2224 strm->hlua.T = NULL;
2225 strm->hlua.Tref = LUA_REFNIL;
2226 strm->hlua.Mref = LUA_REFNIL;
2227 strm->hlua.nargs = 0;
2228 strm->hlua.flags = 0;
2229 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002231 /* Configure "right" stream interface. this "si" is used to connect
2232 * and retrieve data from the server. The connection is initialized
2233 * with the "struct server".
2234 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002235 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236
2237 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002238 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2239 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002240
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002241 /* Update statistics counters. */
2242 socket_proxy.feconn++; /* beconn will be increased later */
2243 jobs++;
2244 totalconn++;
2245
2246 /* Return yield waiting for connection. */
2247 return 1;
2248
Willy Tarreaud420a972015-04-06 00:39:18 +02002249 out_fail_stream:
2250 task_free(task);
2251 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002252 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002253 out_fail_sess:
2254 appctx_free(appctx);
2255 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002256 WILL_LJMP(lua_error(L));
2257 return 0;
2258}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002259
2260/*
2261 *
2262 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002263 * Class Channel
2264 *
2265 *
2266 */
2267
2268/* Returns the struct hlua_channel join to the class channel in the
2269 * stack entry "ud" or throws an argument error.
2270 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002271__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002272{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002273 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002274}
2275
Willy Tarreau47860ed2015-03-10 14:07:50 +01002276/* Pushes the channel onto the top of the stack. If the stask does not have a
2277 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002278 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002279static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002280{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002281 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002282 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002283 return 0;
2284
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002285 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002286 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002287 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002288
2289 /* Pop a class sesison metatable and affect it to the userdata. */
2290 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2291 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002292 return 1;
2293}
2294
2295/* Duplicate all the data present in the input channel and put it
2296 * in a string LUA variables. Returns -1 and push a nil value in
2297 * the stack if the channel is closed and all the data are consumed,
2298 * returns 0 if no data are available, otherwise it returns the length
2299 * of the builded string.
2300 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002301static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002302{
2303 char *blk1;
2304 char *blk2;
2305 int len1;
2306 int len2;
2307 int ret;
2308 luaL_Buffer b;
2309
Willy Tarreau47860ed2015-03-10 14:07:50 +01002310 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002311 if (unlikely(ret == 0))
2312 return 0;
2313
2314 if (unlikely(ret < 0)) {
2315 lua_pushnil(L);
2316 return -1;
2317 }
2318
2319 luaL_buffinit(L, &b);
2320 luaL_addlstring(&b, blk1, len1);
2321 if (unlikely(ret == 2))
2322 luaL_addlstring(&b, blk2, len2);
2323 luaL_pushresult(&b);
2324
2325 if (unlikely(ret == 2))
2326 return len1 + len2;
2327 return len1;
2328}
2329
2330/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2331 * a yield. This function keep the data in the buffer.
2332 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002333__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002334{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002335 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002336
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002337 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2338
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002339 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002340 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002341 return 1;
2342}
2343
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002344/* Check arguments for the function "hlua_channel_dup_yield". */
2345__LJMP static int hlua_channel_dup(lua_State *L)
2346{
2347 MAY_LJMP(check_args(L, 1, "dup"));
2348 MAY_LJMP(hlua_checkchannel(L, 1));
2349 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2350}
2351
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002352/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2353 * a yield. This function consumes the data in the buffer. It returns
2354 * a string containing the data or a nil pointer if no data are available
2355 * and the channel is closed.
2356 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002357__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002358{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002359 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002360 int ret;
2361
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002362 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002363
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002364 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002365 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002366 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002367
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002368 if (unlikely(ret == -1))
2369 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002370
Willy Tarreau47860ed2015-03-10 14:07:50 +01002371 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002372 return 1;
2373}
2374
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002375/* Check arguments for the fucntion "hlua_channel_get_yield". */
2376__LJMP static int hlua_channel_get(lua_State *L)
2377{
2378 MAY_LJMP(check_args(L, 1, "get"));
2379 MAY_LJMP(hlua_checkchannel(L, 1));
2380 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2381}
2382
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002383/* This functions consumes and returns one line. If the channel is closed,
2384 * and the last data does not contains a final '\n', the data are returned
2385 * without the final '\n'. When no more data are avalaible, it returns nil
2386 * value.
2387 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002388__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002389{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002390 char *blk1;
2391 char *blk2;
2392 int len1;
2393 int len2;
2394 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002395 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002396 int ret;
2397 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002398
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002399 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2400
Willy Tarreau47860ed2015-03-10 14:07:50 +01002401 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002402 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002403 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002404
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002405 if (ret == -1) {
2406 lua_pushnil(L);
2407 return 1;
2408 }
2409
2410 luaL_buffinit(L, &b);
2411 luaL_addlstring(&b, blk1, len1);
2412 len = len1;
2413 if (unlikely(ret == 2)) {
2414 luaL_addlstring(&b, blk2, len2);
2415 len += len2;
2416 }
2417 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002418 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002419 return 1;
2420}
2421
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002422/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2423__LJMP static int hlua_channel_getline(lua_State *L)
2424{
2425 MAY_LJMP(check_args(L, 1, "getline"));
2426 MAY_LJMP(hlua_checkchannel(L, 1));
2427 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2428}
2429
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002430/* This function takes a string as input, and append it at the
2431 * input side of channel. If the data is too big, but a space
2432 * is probably available after sending some data, the function
2433 * yield. If the data is bigger than the buffer, or if the
2434 * channel is closed, it returns -1. otherwise, it returns the
2435 * amount of data writed.
2436 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002437__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002438{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002439 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002440 size_t len;
2441 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2442 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2443 int ret;
2444 int max;
2445
Willy Tarreau47860ed2015-03-10 14:07:50 +01002446 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002447 if (max > len - l)
2448 max = len - l;
2449
Willy Tarreau47860ed2015-03-10 14:07:50 +01002450 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002451 if (ret == -2 || ret == -3) {
2452 lua_pushinteger(L, -1);
2453 return 1;
2454 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002455 if (ret == -1) {
2456 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002457 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002458 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002459 l += ret;
2460 lua_pop(L, 1);
2461 lua_pushinteger(L, l);
2462
Willy Tarreau47860ed2015-03-10 14:07:50 +01002463 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2464 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002465 /* There are no space avalaible, and the output buffer is empty.
2466 * in this case, we cannot add more data, so we cannot yield,
2467 * we return the amount of copyied data.
2468 */
2469 return 1;
2470 }
2471 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002472 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002473 return 1;
2474}
2475
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002476/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002477 * of the writed string, or -1 if the channel is closed or if the
2478 * buffer size is too little for the data.
2479 */
2480__LJMP static int hlua_channel_append(lua_State *L)
2481{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002482 size_t len;
2483
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002484 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002485 MAY_LJMP(hlua_checkchannel(L, 1));
2486 MAY_LJMP(luaL_checklstring(L, 2, &len));
2487 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002488 lua_pushinteger(L, 0);
2489
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002490 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002491}
2492
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002493/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002494 * his process by cleaning the buffer. The result is a replacement
2495 * of the current data. It returns the length of the writed string,
2496 * or -1 if the channel is closed or if the buffer size is too
2497 * little for the data.
2498 */
2499__LJMP static int hlua_channel_set(lua_State *L)
2500{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002501 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002502
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002503 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002504 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002505 lua_pushinteger(L, 0);
2506
Willy Tarreau47860ed2015-03-10 14:07:50 +01002507 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002508
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002509 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002510}
2511
2512/* Append data in the output side of the buffer. This data is immediatly
2513 * sent. The fcuntion returns the ammount of data writed. If the buffer
2514 * cannot contains the data, the function yield. The function returns -1
2515 * if the channel is closed.
2516 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002517__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002518{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002519 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002520 size_t len;
2521 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2522 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2523 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002524 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002525
Willy Tarreau47860ed2015-03-10 14:07:50 +01002526 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002527 lua_pushinteger(L, -1);
2528 return 1;
2529 }
2530
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002531 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2532 * the request buffer if its not required.
2533 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002534 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002535 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002536 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002537 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002538 }
2539 }
2540
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002541 /* the writed data will be immediatly sent, so we can check
2542 * the avalaible space without taking in account the reserve.
2543 * The reserve is guaranted for the processing of incoming
2544 * data, because the buffer will be flushed.
2545 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002546 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002547
2548 /* If there are no space avalaible, and the output buffer is empty.
2549 * in this case, we cannot add more data, so we cannot yield,
2550 * we return the amount of copyied data.
2551 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002552 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002553 return 1;
2554
2555 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002556 if (max > len - l)
2557 max = len - l;
2558
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002559 /* The buffer avalaible size may be not contiguous. This test
2560 * detects a non contiguous buffer and realign it.
2561 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002562 if (bi_space_for_replace(chn->buf) < max)
2563 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002564
2565 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002566 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002567
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002568 /* buffer replace considers that the input part is filled.
2569 * so, I must forward these new data in the output part.
2570 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002571 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002572
2573 l += max;
2574 lua_pop(L, 1);
2575 lua_pushinteger(L, l);
2576
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002577 /* If there are no space avalaible, and the output buffer is empty.
2578 * in this case, we cannot add more data, so we cannot yield,
2579 * we return the amount of copyied data.
2580 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002581 max = chn->buf->size - buffer_len(chn->buf);
2582 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002583 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002584
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002585 if (l < len) {
2586 /* If we are waiting for space in the response buffer, we
2587 * must set the flag WAKERESWR. This flag required the task
2588 * wake up if any activity is detected on the response buffer.
2589 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002590 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002591 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002592 else
2593 HLUA_SET_WAKEREQWR(hlua);
2594 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002595 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002596
2597 return 1;
2598}
2599
2600/* Just a wraper of "_hlua_channel_send". This wrapper permits
2601 * yield the LUA process, and resume it without checking the
2602 * input arguments.
2603 */
2604__LJMP static int hlua_channel_send(lua_State *L)
2605{
2606 MAY_LJMP(check_args(L, 2, "send"));
2607 lua_pushinteger(L, 0);
2608
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002609 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002610}
2611
2612/* This function forward and amount of butes. The data pass from
2613 * the input side of the buffer to the output side, and can be
2614 * forwarded. This function never fails.
2615 *
2616 * The Lua function takes an amount of bytes to be forwarded in
2617 * imput. It returns the number of bytes forwarded.
2618 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002619__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002620{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002621 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002622 int len;
2623 int l;
2624 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002625 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002626
2627 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2628 len = MAY_LJMP(luaL_checkinteger(L, 2));
2629 l = MAY_LJMP(luaL_checkinteger(L, -1));
2630
2631 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002632 if (max > chn->buf->i)
2633 max = chn->buf->i;
2634 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002635 l += max;
2636
2637 lua_pop(L, 1);
2638 lua_pushinteger(L, l);
2639
2640 /* Check if it miss bytes to forward. */
2641 if (l < len) {
2642 /* The the input channel or the output channel are closed, we
2643 * must return the amount of data forwarded.
2644 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002645 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002646 return 1;
2647
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002648 /* If we are waiting for space data in the response buffer, we
2649 * must set the flag WAKERESWR. This flag required the task
2650 * wake up if any activity is detected on the response buffer.
2651 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002652 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002653 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002654 else
2655 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002656
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002657 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002658 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002659 }
2660
2661 return 1;
2662}
2663
2664/* Just check the input and prepare the stack for the previous
2665 * function "hlua_channel_forward_yield"
2666 */
2667__LJMP static int hlua_channel_forward(lua_State *L)
2668{
2669 MAY_LJMP(check_args(L, 2, "forward"));
2670 MAY_LJMP(hlua_checkchannel(L, 1));
2671 MAY_LJMP(luaL_checkinteger(L, 2));
2672
2673 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002674 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002675}
2676
2677/* Just returns the number of bytes available in the input
2678 * side of the buffer. This function never fails.
2679 */
2680__LJMP static int hlua_channel_get_in_len(lua_State *L)
2681{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002682 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002683
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002684 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002685 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002686 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002687 return 1;
2688}
2689
2690/* Just returns the number of bytes available in the output
2691 * side of the buffer. This function never fails.
2692 */
2693__LJMP static int hlua_channel_get_out_len(lua_State *L)
2694{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002695 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002696
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002697 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002698 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002699 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002700 return 1;
2701}
2702
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002703/*
2704 *
2705 *
2706 * Class Fetches
2707 *
2708 *
2709 */
2710
2711/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002712 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002713 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002714__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002715{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002716 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002717}
2718
2719/* This function creates and push in the stack a fetch object according
2720 * with a current TXN.
2721 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002722static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002723{
Willy Tarreau7073c472015-04-06 11:15:40 +02002724 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002725
2726 /* Check stack size. */
2727 if (!lua_checkstack(L, 3))
2728 return 0;
2729
2730 /* Create the object: obj[0] = userdata.
2731 * Note that the base of the Fetches object is the
2732 * transaction object.
2733 */
2734 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002735 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002736 lua_rawseti(L, -2, 0);
2737
Willy Tarreau7073c472015-04-06 11:15:40 +02002738 hsmp->s = txn->s;
2739 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002740 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002741
2742 /* Pop a class sesison metatable and affect it to the userdata. */
2743 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2744 lua_setmetatable(L, -2);
2745
2746 return 1;
2747}
2748
2749/* This function is an LUA binding. It is called with each sample-fetch.
2750 * It uses closure argument to store the associated sample-fetch. It
2751 * returns only one argument or throws an error. An error is thrown
2752 * only if an error is encountered during the argument parsing. If
2753 * the "sample-fetch" function fails, nil is returned.
2754 */
2755__LJMP static int hlua_run_sample_fetch(lua_State *L)
2756{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002757 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002758 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002759 struct arg args[ARGM_NBARGS + 1];
2760 int i;
2761 struct sample smp;
2762
2763 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002764 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002765
2766 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002767 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002768
2769 /* Get extra arguments. */
2770 for (i = 0; i < lua_gettop(L) - 1; i++) {
2771 if (i >= ARGM_NBARGS)
2772 break;
2773 hlua_lua2arg(L, i + 2, &args[i]);
2774 }
2775 args[i].type = ARGT_STOP;
2776
2777 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002778 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002779
2780 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002781 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002782 lua_pushfstring(L, "error in arguments");
2783 WILL_LJMP(lua_error(L));
2784 }
2785
2786 /* Initialise the sample. */
2787 memset(&smp, 0, sizeof(smp));
2788
2789 /* Run the sample fetch process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02002790 smp.px = hsmp->p;
2791 smp.sess = hsmp->s->sess;
2792 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002793 smp.opt = 0;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02002794 if (!f->process(args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002795 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002796 lua_pushstring(L, "");
2797 else
2798 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002799 return 1;
2800 }
2801
2802 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002803 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002804 hlua_smp2lua_str(L, &smp);
2805 else
2806 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002807 return 1;
2808}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002809
2810/*
2811 *
2812 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002813 * Class Converters
2814 *
2815 *
2816 */
2817
2818/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002819 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002820 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002821__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002822{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002823 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002824}
2825
2826/* This function creates and push in the stack a Converters object
2827 * according with a current TXN.
2828 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002829static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002830{
Willy Tarreau7073c472015-04-06 11:15:40 +02002831 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002832
2833 /* Check stack size. */
2834 if (!lua_checkstack(L, 3))
2835 return 0;
2836
2837 /* Create the object: obj[0] = userdata.
2838 * Note that the base of the Converters object is the
2839 * same than the TXN object.
2840 */
2841 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002842 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002843 lua_rawseti(L, -2, 0);
2844
Willy Tarreau7073c472015-04-06 11:15:40 +02002845 hsmp->s = txn->s;
2846 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002847 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002848
Willy Tarreau87b09662015-04-03 00:22:06 +02002849 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002850 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2851 lua_setmetatable(L, -2);
2852
2853 return 1;
2854}
2855
2856/* This function is an LUA binding. It is called with each converter.
2857 * It uses closure argument to store the associated converter. It
2858 * returns only one argument or throws an error. An error is thrown
2859 * only if an error is encountered during the argument parsing. If
2860 * the converter function function fails, nil is returned.
2861 */
2862__LJMP static int hlua_run_sample_conv(lua_State *L)
2863{
Willy Tarreauda5f1082015-04-06 11:17:13 +02002864 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002865 struct sample_conv *conv;
2866 struct arg args[ARGM_NBARGS + 1];
2867 int i;
2868 struct sample smp;
2869
2870 /* Get closure arguments. */
2871 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2872
2873 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002874 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002875
2876 /* Get extra arguments. */
2877 for (i = 0; i < lua_gettop(L) - 2; i++) {
2878 if (i >= ARGM_NBARGS)
2879 break;
2880 hlua_lua2arg(L, i + 3, &args[i]);
2881 }
2882 args[i].type = ARGT_STOP;
2883
2884 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002885 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002886
2887 /* Run the special args checker. */
2888 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2889 hlua_pusherror(L, "error in arguments");
2890 WILL_LJMP(lua_error(L));
2891 }
2892
2893 /* Initialise the sample. */
2894 if (!hlua_lua2smp(L, 2, &smp)) {
2895 hlua_pusherror(L, "error in the input argument");
2896 WILL_LJMP(lua_error(L));
2897 }
2898
2899 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002900 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002901 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002902 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002903 WILL_LJMP(lua_error(L));
2904 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002905 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
2906 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002907 hlua_pusherror(L, "error during the input argument casting");
2908 WILL_LJMP(lua_error(L));
2909 }
2910
2911 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02002912 smp.px = hsmp->p;
2913 smp.sess = hsmp->s->sess;
2914 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002915 smp.opt = 0;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02002916 if (!conv->process(args, &smp, conv->private)) {
Willy Tarreauda5f1082015-04-06 11:17:13 +02002917 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002918 lua_pushstring(L, "");
2919 else
Willy Tarreaua678b432015-08-28 10:14:59 +02002920 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002921 return 1;
2922 }
2923
2924 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002925 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002926 hlua_smp2lua_str(L, &smp);
2927 else
2928 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02002929 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002930}
2931
2932/*
2933 *
2934 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002935 * Class HTTP
2936 *
2937 *
2938 */
2939
2940/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002941 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002942 */
2943__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
2944{
2945 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
2946}
2947
2948/* This function creates and push in the stack a HTTP object
2949 * according with a current TXN.
2950 */
2951static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
2952{
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002953 struct hlua_txn *htxn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002954
2955 /* Check stack size. */
2956 if (!lua_checkstack(L, 3))
2957 return 0;
2958
2959 /* Create the object: obj[0] = userdata.
2960 * Note that the base of the Converters object is the
2961 * same than the TXN object.
2962 */
2963 lua_newtable(L);
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002964 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002965 lua_rawseti(L, -2, 0);
2966
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002967 htxn->s = txn->s;
2968 htxn->p = txn->p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002969
Willy Tarreau87b09662015-04-03 00:22:06 +02002970 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002971 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
2972 lua_setmetatable(L, -2);
2973
2974 return 1;
2975}
2976
2977/* This function creates ans returns an array of HTTP headers.
2978 * This function does not fails. It is used as wrapper with the
2979 * 2 following functions.
2980 */
2981__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
2982{
2983 const char *cur_ptr, *cur_next, *p;
2984 int old_idx, cur_idx;
2985 struct hdr_idx_elem *cur_hdr;
2986 const char *hn, *hv;
2987 int hnl, hvl;
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01002988 int type;
2989 const char *in;
2990 char *out;
2991 int len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002992
2993 /* Create the table. */
2994 lua_newtable(L);
2995
Willy Tarreaueee5b512015-04-03 23:46:31 +02002996 if (!htxn->s->txn)
2997 return 1;
2998
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002999 /* Build array of headers. */
3000 old_idx = 0;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003001 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003002
3003 while (1) {
Willy Tarreaueee5b512015-04-03 23:46:31 +02003004 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003005 if (!cur_idx)
3006 break;
3007 old_idx = cur_idx;
3008
Willy Tarreaueee5b512015-04-03 23:46:31 +02003009 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003010 cur_ptr = cur_next;
3011 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
3012
3013 /* Now we have one full header at cur_ptr of len cur_hdr->len,
3014 * and the next header starts at cur_next. We'll check
3015 * this header in the list as well as against the default
3016 * rule.
3017 */
3018
3019 /* look for ': *'. */
3020 hn = cur_ptr;
3021 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
3022 if (p >= cur_ptr+cur_hdr->len)
3023 continue;
3024 hnl = p - hn;
3025 p++;
3026 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3027 p++;
3028 if (p >= cur_ptr+cur_hdr->len)
3029 continue;
3030 hv = p;
3031 hvl = cur_ptr+cur_hdr->len-p;
3032
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003033 /* Lowercase the key. Don't check the size of trash, it have
3034 * the size of one buffer and the input data contains in one
3035 * buffer.
3036 */
3037 out = trash.str;
3038 for (in=hn; in<hn+hnl; in++, out++)
3039 *out = tolower(*in);
3040 *out = '\0';
3041
3042 /* Check for existing entry:
3043 * assume that the table is on the top of the stack, and
3044 * push the key in the stack, the function lua_gettable()
3045 * perform the lookup.
3046 */
3047 lua_pushlstring(L, trash.str, hnl);
3048 lua_gettable(L, -2);
3049 type = lua_type(L, -1);
3050
3051 switch (type) {
3052 case LUA_TNIL:
3053 /* Table not found, create it. */
3054 lua_pop(L, 1); /* remove the nil value. */
3055 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
3056 lua_newtable(L); /* create and push empty table. */
3057 lua_pushlstring(L, hv, hvl); /* push header value. */
3058 lua_rawseti(L, -2, 0); /* index header value (pop it). */
3059 lua_rawset(L, -3); /* index new table with header name (pop the values). */
3060 break;
3061
3062 case LUA_TTABLE:
3063 /* Entry found: push the value in the table. */
3064 len = lua_rawlen(L, -1);
3065 lua_pushlstring(L, hv, hvl); /* push header value. */
3066 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
3067 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
3068 break;
3069
3070 default:
3071 /* Other cases are errors. */
3072 hlua_pusherror(L, "internal error during the parsing of headers.");
3073 WILL_LJMP(lua_error(L));
3074 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003075 }
3076
3077 return 1;
3078}
3079
3080__LJMP static int hlua_http_req_get_headers(lua_State *L)
3081{
3082 struct hlua_txn *htxn;
3083
3084 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3085 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3086
Willy Tarreaueee5b512015-04-03 23:46:31 +02003087 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003088}
3089
3090__LJMP static int hlua_http_res_get_headers(lua_State *L)
3091{
3092 struct hlua_txn *htxn;
3093
3094 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3095 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3096
Willy Tarreaueee5b512015-04-03 23:46:31 +02003097 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003098}
3099
3100/* This function replace full header, or just a value in
3101 * the request or in the response. It is a wrapper fir the
3102 * 4 following functions.
3103 */
3104__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3105 struct http_msg *msg, int action)
3106{
3107 size_t name_len;
3108 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3109 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3110 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3111 struct my_regex re;
3112
3113 if (!regex_comp(reg, &re, 1, 1, NULL))
3114 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3115
3116 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3117 regex_free(&re);
3118 return 0;
3119}
3120
3121__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3122{
3123 struct hlua_txn *htxn;
3124
3125 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3126 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3127
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003128 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003129}
3130
3131__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3132{
3133 struct hlua_txn *htxn;
3134
3135 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3136 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3137
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003138 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003139}
3140
3141__LJMP static int hlua_http_req_rep_val(lua_State *L)
3142{
3143 struct hlua_txn *htxn;
3144
3145 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3146 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3147
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003148 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003149}
3150
3151__LJMP static int hlua_http_res_rep_val(lua_State *L)
3152{
3153 struct hlua_txn *htxn;
3154
3155 MAY_LJMP(check_args(L, 4, "res_rep_val"));
3156 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3157
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003158 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003159}
3160
3161/* This function deletes all the occurences of an header.
3162 * It is a wrapper for the 2 following functions.
3163 */
3164__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3165{
3166 size_t len;
3167 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3168 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003169 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003170
3171 ctx.idx = 0;
3172 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3173 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3174 return 0;
3175}
3176
3177__LJMP static int hlua_http_req_del_hdr(lua_State *L)
3178{
3179 struct hlua_txn *htxn;
3180
3181 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3182 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3183
Willy Tarreaueee5b512015-04-03 23:46:31 +02003184 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003185}
3186
3187__LJMP static int hlua_http_res_del_hdr(lua_State *L)
3188{
3189 struct hlua_txn *htxn;
3190
3191 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3192 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3193
Willy Tarreaueee5b512015-04-03 23:46:31 +02003194 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003195}
3196
3197/* This function adds an header. It is a wrapper used by
3198 * the 2 following functions.
3199 */
3200__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3201{
3202 size_t name_len;
3203 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3204 size_t value_len;
3205 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3206 char *p;
3207
3208 /* Check length. */
3209 trash.len = value_len + name_len + 2;
3210 if (trash.len > trash.size)
3211 return 0;
3212
3213 /* Creates the header string. */
3214 p = trash.str;
3215 memcpy(p, name, name_len);
3216 p += name_len;
3217 *p = ':';
3218 p++;
3219 *p = ' ';
3220 p++;
3221 memcpy(p, value, value_len);
3222
Willy Tarreaueee5b512015-04-03 23:46:31 +02003223 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003224 trash.str, trash.len) != 0);
3225
3226 return 0;
3227}
3228
3229__LJMP static int hlua_http_req_add_hdr(lua_State *L)
3230{
3231 struct hlua_txn *htxn;
3232
3233 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3234 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3235
Willy Tarreaueee5b512015-04-03 23:46:31 +02003236 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003237}
3238
3239__LJMP static int hlua_http_res_add_hdr(lua_State *L)
3240{
3241 struct hlua_txn *htxn;
3242
3243 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3244 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3245
Willy Tarreaueee5b512015-04-03 23:46:31 +02003246 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003247}
3248
3249static int hlua_http_req_set_hdr(lua_State *L)
3250{
3251 struct hlua_txn *htxn;
3252
3253 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3254 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3255
Willy Tarreaueee5b512015-04-03 23:46:31 +02003256 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3257 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003258}
3259
3260static int hlua_http_res_set_hdr(lua_State *L)
3261{
3262 struct hlua_txn *htxn;
3263
3264 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3265 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3266
Willy Tarreaueee5b512015-04-03 23:46:31 +02003267 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3268 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003269}
3270
3271/* This function set the method. */
3272static int hlua_http_req_set_meth(lua_State *L)
3273{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003274 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003275 size_t name_len;
3276 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003277
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003278 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003279 return 1;
3280}
3281
3282/* This function set the method. */
3283static int hlua_http_req_set_path(lua_State *L)
3284{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003285 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003286 size_t name_len;
3287 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003288 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003289 return 1;
3290}
3291
3292/* This function set the query-string. */
3293static int hlua_http_req_set_query(lua_State *L)
3294{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003295 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003296 size_t name_len;
3297 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003298
3299 /* Check length. */
3300 if (name_len > trash.size - 1) {
3301 lua_pushboolean(L, 0);
3302 return 1;
3303 }
3304
3305 /* Add the mark question as prefix. */
3306 chunk_reset(&trash);
3307 trash.str[trash.len++] = '?';
3308 memcpy(trash.str + trash.len, name, name_len);
3309 trash.len += name_len;
3310
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003311 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003312 return 1;
3313}
3314
3315/* This function set the uri. */
3316static int hlua_http_req_set_uri(lua_State *L)
3317{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003318 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003319 size_t name_len;
3320 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003321
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003322 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003323 return 1;
3324}
3325
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02003326/* This function set the response code. */
3327static int hlua_http_res_set_status(lua_State *L)
3328{
3329 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3330 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
3331
3332 http_set_status(code, htxn->s);
3333 return 0;
3334}
3335
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003336/*
3337 *
3338 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003339 * Class TXN
3340 *
3341 *
3342 */
3343
3344/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003345 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003346 */
3347__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3348{
3349 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3350}
3351
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02003352__LJMP static int hlua_set_var(lua_State *L)
3353{
3354 struct hlua_txn *htxn;
3355 const char *name;
3356 size_t len;
3357 struct sample smp;
3358
3359 MAY_LJMP(check_args(L, 3, "set_var"));
3360
3361 /* It is useles to retrieve the stream, but this function
3362 * runs only in a stream context.
3363 */
3364 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3365 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3366
3367 /* Converts the third argument in a sample. */
3368 hlua_lua2smp(L, 3, &smp);
3369
3370 /* Store the sample in a variable. */
3371 vars_set_by_name(name, len, htxn->s, &smp);
3372 return 0;
3373}
3374
3375__LJMP static int hlua_get_var(lua_State *L)
3376{
3377 struct hlua_txn *htxn;
3378 const char *name;
3379 size_t len;
3380 struct sample smp;
3381
3382 MAY_LJMP(check_args(L, 2, "get_var"));
3383
3384 /* It is useles to retrieve the stream, but this function
3385 * runs only in a stream context.
3386 */
3387 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3388 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3389
3390 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
3391 lua_pushnil(L);
3392 return 1;
3393 }
3394
3395 return hlua_smp2lua(L, &smp);
3396}
3397
Willy Tarreau59551662015-03-10 14:23:13 +01003398__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003399{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003400 struct hlua *hlua;
3401
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003402 MAY_LJMP(check_args(L, 2, "set_priv"));
3403
Willy Tarreau87b09662015-04-03 00:22:06 +02003404 /* It is useles to retrieve the stream, but this function
3405 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003406 */
3407 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003408 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003409
3410 /* Remove previous value. */
3411 if (hlua->Mref != -1)
3412 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3413
3414 /* Get and store new value. */
3415 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3416 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3417
3418 return 0;
3419}
3420
Willy Tarreau59551662015-03-10 14:23:13 +01003421__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003422{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003423 struct hlua *hlua;
3424
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003425 MAY_LJMP(check_args(L, 1, "get_priv"));
3426
Willy Tarreau87b09662015-04-03 00:22:06 +02003427 /* It is useles to retrieve the stream, but this function
3428 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003429 */
3430 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003431 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003432
3433 /* Push configuration index in the stack. */
3434 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3435
3436 return 1;
3437}
3438
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003439/* Create stack entry containing a class TXN. This function
3440 * return 0 if the stack does not contains free slots,
3441 * otherwise it returns 1.
3442 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003443static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003444{
Willy Tarreaude491382015-04-06 11:04:28 +02003445 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003446
3447 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003448 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003449 return 0;
3450
3451 /* NOTE: The allocation never fails. The failure
3452 * throw an error, and the function never returns.
3453 * if the throw is not avalaible, the process is aborted.
3454 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003455 /* Create the object: obj[0] = userdata. */
3456 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02003457 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003458 lua_rawseti(L, -2, 0);
3459
Willy Tarreaude491382015-04-06 11:04:28 +02003460 htxn->s = s;
3461 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003462
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003463 /* Create the "f" field that contains a list of fetches. */
3464 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02003465 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003466 return 0;
3467 lua_settable(L, -3);
3468
3469 /* Create the "sf" field that contains a list of stringsafe fetches. */
3470 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02003471 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003472 return 0;
3473 lua_settable(L, -3);
3474
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003475 /* Create the "c" field that contains a list of converters. */
3476 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02003477 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003478 return 0;
3479 lua_settable(L, -3);
3480
3481 /* Create the "sc" field that contains a list of stringsafe converters. */
3482 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02003483 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003484 return 0;
3485 lua_settable(L, -3);
3486
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003487 /* Create the "req" field that contains the request channel object. */
3488 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003489 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003490 return 0;
3491 lua_settable(L, -3);
3492
3493 /* Create the "res" field that contains the response channel object. */
3494 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003495 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003496 return 0;
3497 lua_settable(L, -3);
3498
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003499 /* Creates the HTTP object is the current proxy allows http. */
3500 lua_pushstring(L, "http");
3501 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02003502 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003503 return 0;
3504 }
3505 else
3506 lua_pushnil(L);
3507 lua_settable(L, -3);
3508
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003509 /* Pop a class sesison metatable and affect it to the userdata. */
3510 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3511 lua_setmetatable(L, -2);
3512
3513 return 1;
3514}
3515
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003516__LJMP static int hlua_txn_deflog(lua_State *L)
3517{
3518 const char *msg;
3519 struct hlua_txn *htxn;
3520
3521 MAY_LJMP(check_args(L, 2, "deflog"));
3522 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3523 msg = MAY_LJMP(luaL_checkstring(L, 2));
3524
3525 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3526 return 0;
3527}
3528
3529__LJMP static int hlua_txn_log(lua_State *L)
3530{
3531 int level;
3532 const char *msg;
3533 struct hlua_txn *htxn;
3534
3535 MAY_LJMP(check_args(L, 3, "log"));
3536 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3537 level = MAY_LJMP(luaL_checkinteger(L, 2));
3538 msg = MAY_LJMP(luaL_checkstring(L, 3));
3539
3540 if (level < 0 || level >= NB_LOG_LEVELS)
3541 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3542
3543 hlua_sendlog(htxn->s->be, level, msg);
3544 return 0;
3545}
3546
3547__LJMP static int hlua_txn_log_debug(lua_State *L)
3548{
3549 const char *msg;
3550 struct hlua_txn *htxn;
3551
3552 MAY_LJMP(check_args(L, 2, "Debug"));
3553 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3554 msg = MAY_LJMP(luaL_checkstring(L, 2));
3555 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3556 return 0;
3557}
3558
3559__LJMP static int hlua_txn_log_info(lua_State *L)
3560{
3561 const char *msg;
3562 struct hlua_txn *htxn;
3563
3564 MAY_LJMP(check_args(L, 2, "Info"));
3565 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3566 msg = MAY_LJMP(luaL_checkstring(L, 2));
3567 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3568 return 0;
3569}
3570
3571__LJMP static int hlua_txn_log_warning(lua_State *L)
3572{
3573 const char *msg;
3574 struct hlua_txn *htxn;
3575
3576 MAY_LJMP(check_args(L, 2, "Warning"));
3577 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3578 msg = MAY_LJMP(luaL_checkstring(L, 2));
3579 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3580 return 0;
3581}
3582
3583__LJMP static int hlua_txn_log_alert(lua_State *L)
3584{
3585 const char *msg;
3586 struct hlua_txn *htxn;
3587
3588 MAY_LJMP(check_args(L, 2, "Alert"));
3589 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3590 msg = MAY_LJMP(luaL_checkstring(L, 2));
3591 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3592 return 0;
3593}
3594
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003595__LJMP static int hlua_txn_set_loglevel(lua_State *L)
3596{
3597 struct hlua_txn *htxn;
3598 int ll;
3599
3600 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3601 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3602 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3603
3604 if (ll < 0 || ll > 7)
3605 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3606
3607 htxn->s->logs.level = ll;
3608 return 0;
3609}
3610
3611__LJMP static int hlua_txn_set_tos(lua_State *L)
3612{
3613 struct hlua_txn *htxn;
3614 struct connection *cli_conn;
3615 int tos;
3616
3617 MAY_LJMP(check_args(L, 2, "set_tos"));
3618 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3619 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3620
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003621 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003622 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3623
3624 return 0;
3625}
3626
3627__LJMP static int hlua_txn_set_mark(lua_State *L)
3628{
3629#ifdef SO_MARK
3630 struct hlua_txn *htxn;
3631 struct connection *cli_conn;
3632 int mark;
3633
3634 MAY_LJMP(check_args(L, 2, "set_mark"));
3635 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3636 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3637
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003638 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02003639 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003640#endif
3641 return 0;
3642}
3643
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003644/* This function is an Lua binding that send pending data
3645 * to the client, and close the stream interface.
3646 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02003647__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003648{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003649 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01003650 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003651
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003652 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003653 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003654
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003655 ic = &htxn->s->req;
3656 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01003657
Willy Tarreau630ef452015-08-28 10:06:15 +02003658 if (htxn->s->txn) {
3659 /* HTTP mode, let's stay in sync with the stream */
3660 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
3661 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
3662 htxn->s->txn->req.sov = 0;
3663 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
3664 oc->analysers = AN_RES_HTTP_XFER_BODY;
3665 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
3666 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
3667
3668 /* Trim any possible response */
3669 oc->buf->i = 0;
3670 htxn->s->txn->rsp.next = htxn->s->txn->rsp.sov = 0;
3671
3672 /* Note that if we want to support keep-alive, we need
3673 * to bypass the close/shutr_now calls below, but that
3674 * may only be done if the HTTP request was already
3675 * processed and the connection header is known (ie
3676 * not during TCP rules).
3677 */
3678 }
3679
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003680 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01003681 channel_abort(ic);
3682 channel_auto_close(ic);
3683 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003684
3685 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01003686 channel_auto_read(oc);
3687 channel_auto_close(oc);
3688 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003689
Willy Tarreau0458b082015-08-28 09:40:04 +02003690 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02003691
3692 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003693 return 0;
3694}
3695
3696__LJMP static int hlua_log(lua_State *L)
3697{
3698 int level;
3699 const char *msg;
3700
3701 MAY_LJMP(check_args(L, 2, "log"));
3702 level = MAY_LJMP(luaL_checkinteger(L, 1));
3703 msg = MAY_LJMP(luaL_checkstring(L, 2));
3704
3705 if (level < 0 || level >= NB_LOG_LEVELS)
3706 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3707
3708 hlua_sendlog(NULL, level, msg);
3709 return 0;
3710}
3711
3712__LJMP static int hlua_log_debug(lua_State *L)
3713{
3714 const char *msg;
3715
3716 MAY_LJMP(check_args(L, 1, "debug"));
3717 msg = MAY_LJMP(luaL_checkstring(L, 1));
3718 hlua_sendlog(NULL, LOG_DEBUG, msg);
3719 return 0;
3720}
3721
3722__LJMP static int hlua_log_info(lua_State *L)
3723{
3724 const char *msg;
3725
3726 MAY_LJMP(check_args(L, 1, "info"));
3727 msg = MAY_LJMP(luaL_checkstring(L, 1));
3728 hlua_sendlog(NULL, LOG_INFO, msg);
3729 return 0;
3730}
3731
3732__LJMP static int hlua_log_warning(lua_State *L)
3733{
3734 const char *msg;
3735
3736 MAY_LJMP(check_args(L, 1, "warning"));
3737 msg = MAY_LJMP(luaL_checkstring(L, 1));
3738 hlua_sendlog(NULL, LOG_WARNING, msg);
3739 return 0;
3740}
3741
3742__LJMP static int hlua_log_alert(lua_State *L)
3743{
3744 const char *msg;
3745
3746 MAY_LJMP(check_args(L, 1, "alert"));
3747 msg = MAY_LJMP(luaL_checkstring(L, 1));
3748 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003749 return 0;
3750}
3751
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003752__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003753{
3754 int wakeup_ms = lua_tointeger(L, -1);
3755 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003756 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003757 return 0;
3758}
3759
3760__LJMP static int hlua_sleep(lua_State *L)
3761{
3762 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003763 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003764
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003765 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003766
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003767 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003768 wakeup_ms = tick_add(now_ms, delay);
3769 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003770
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003771 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3772 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003773}
3774
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003775__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003776{
3777 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003778 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003779
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003780 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003781
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003782 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003783 wakeup_ms = tick_add(now_ms, delay);
3784 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003785
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003786 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3787 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003788}
3789
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003790/* This functionis an LUA binding. it permits to give back
3791 * the hand at the HAProxy scheduler. It is used when the
3792 * LUA processing consumes a lot of time.
3793 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003794__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003795{
3796 return 0;
3797}
3798
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003799__LJMP static int hlua_yield(lua_State *L)
3800{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003801 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3802 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003803}
3804
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003805/* This function change the nice of the currently executed
3806 * task. It is used set low or high priority at the current
3807 * task.
3808 */
Willy Tarreau59551662015-03-10 14:23:13 +01003809__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003810{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003811 struct hlua *hlua;
3812 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003813
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003814 MAY_LJMP(check_args(L, 1, "set_nice"));
3815 hlua = hlua_gethlua(L);
3816 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003817
3818 /* If he task is not set, I'm in a start mode. */
3819 if (!hlua || !hlua->task)
3820 return 0;
3821
3822 if (nice < -1024)
3823 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003824 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003825 nice = 1024;
3826
3827 hlua->task->nice = nice;
3828 return 0;
3829}
3830
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003831/* This function is used as a calback of a task. It is called by the
3832 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3833 * return an E_AGAIN signal, the emmiter of this signal must set a
3834 * signal to wake the task.
3835 */
3836static struct task *hlua_process_task(struct task *task)
3837{
3838 struct hlua *hlua = task->context;
3839 enum hlua_exec status;
3840
3841 /* We need to remove the task from the wait queue before executing
3842 * the Lua code because we don't know if it needs to wait for
3843 * another timer or not in the case of E_AGAIN.
3844 */
3845 task_delete(task);
3846
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003847 /* If it is the first call to the task, we must initialize the
3848 * execution timeouts.
3849 */
3850 if (!HLUA_IS_RUNNING(hlua))
Camilo Lopez685c0142015-08-02 19:07:28 -04003851 hlua->expire = tick_add_ifset(now_ms, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003852
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003853 /* Execute the Lua code. */
3854 status = hlua_ctx_resume(hlua, 1);
3855
3856 switch (status) {
3857 /* finished or yield */
3858 case HLUA_E_OK:
3859 hlua_ctx_destroy(hlua);
3860 task_delete(task);
3861 task_free(task);
3862 break;
3863
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003864 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3865 if (hlua->wake_time != TICK_ETERNITY)
3866 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003867 break;
3868
3869 /* finished with error. */
3870 case HLUA_E_ERRMSG:
3871 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3872 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3873 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3874 hlua_ctx_destroy(hlua);
3875 task_delete(task);
3876 task_free(task);
3877 break;
3878
3879 case HLUA_E_ERR:
3880 default:
3881 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3882 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3883 Alert("Lua task: unknown error.\n");
3884 hlua_ctx_destroy(hlua);
3885 task_delete(task);
3886 task_free(task);
3887 break;
3888 }
3889 return NULL;
3890}
3891
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003892/* This function is an LUA binding that register LUA function to be
3893 * executed after the HAProxy configuration parsing and before the
3894 * HAProxy scheduler starts. This function expect only one LUA
3895 * argument that is a function. This function returns nothing, but
3896 * throws if an error is encountered.
3897 */
3898__LJMP static int hlua_register_init(lua_State *L)
3899{
3900 struct hlua_init_function *init;
3901 int ref;
3902
3903 MAY_LJMP(check_args(L, 1, "register_init"));
3904
3905 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3906
3907 init = malloc(sizeof(*init));
3908 if (!init)
3909 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3910
3911 init->function_ref = ref;
3912 LIST_ADDQ(&hlua_init_functions, &init->l);
3913 return 0;
3914}
3915
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003916/* This functio is an LUA binding. It permits to register a task
3917 * executed in parallel of the main HAroxy activity. The task is
3918 * created and it is set in the HAProxy scheduler. It can be called
3919 * from the "init" section, "post init" or during the runtime.
3920 *
3921 * Lua prototype:
3922 *
3923 * <none> core.register_task(<function>)
3924 */
3925static int hlua_register_task(lua_State *L)
3926{
3927 struct hlua *hlua;
3928 struct task *task;
3929 int ref;
3930
3931 MAY_LJMP(check_args(L, 1, "register_task"));
3932
3933 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3934
3935 hlua = malloc(sizeof(*hlua));
3936 if (!hlua)
3937 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3938
3939 task = task_new();
3940 task->context = hlua;
3941 task->process = hlua_process_task;
3942
3943 if (!hlua_ctx_init(hlua, task))
3944 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3945
3946 /* Restore the function in the stack. */
3947 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3948 hlua->nargs = 0;
3949
3950 /* Schedule task. */
3951 task_schedule(task, now_ms);
3952
3953 return 0;
3954}
3955
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003956/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3957 * doesn't allow "yield" functions because the HAProxy engine cannot
3958 * resume converters.
3959 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003960static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003961{
3962 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003963 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003964
Willy Tarreau87b09662015-04-03 00:22:06 +02003965 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003966 * Lua context can be not initialized. This behavior
3967 * permits to save performances because a systematic
3968 * Lua initialization cause 5% performances loss.
3969 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003970 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
3971 send_log(stream->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003972 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3973 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3974 return 0;
3975 }
3976
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003977 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003978 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003979 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003980 if (!lua_checkstack(stream->hlua.T, 1)) {
3981 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003982 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3983 Alert("Lua converter '%s': full stack.\n", fcn->name);
3984 return 0;
3985 }
3986
3987 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003988 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003989
3990 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003991 if (!lua_checkstack(stream->hlua.T, 1)) {
3992 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003993 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3994 Alert("Lua converter '%s': full stack.\n", fcn->name);
3995 return 0;
3996 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003997 hlua_smp2lua(stream->hlua.T, smp);
3998 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003999
4000 /* push keywords in the stack. */
4001 if (arg_p) {
4002 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02004003 if (!lua_checkstack(stream->hlua.T, 1)) {
4004 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004005 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4006 Alert("Lua converter '%s': full stack.\n", fcn->name);
4007 return 0;
4008 }
Willy Tarreau87b09662015-04-03 00:22:06 +02004009 hlua_arg2lua(stream->hlua.T, arg_p);
4010 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004011 }
4012 }
4013
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004014 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004015 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004016
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004017 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004018 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004019 }
4020
4021 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004022 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004023 /* finished. */
4024 case HLUA_E_OK:
4025 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004026 hlua_lua2smp(stream->hlua.T, -1, smp);
4027 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004028 return 1;
4029
4030 /* yield. */
4031 case HLUA_E_AGAIN:
Willy Tarreau87b09662015-04-03 00:22:06 +02004032 send_log(stream->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004033 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4034 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
4035 return 0;
4036
4037 /* finished with error. */
4038 case HLUA_E_ERRMSG:
4039 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004040 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 +01004041 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Willy Tarreau87b09662015-04-03 00:22:06 +02004042 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
4043 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004044 return 0;
4045
4046 case HLUA_E_ERR:
4047 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004048 send_log(stream->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004049 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4050 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
4051
4052 default:
4053 return 0;
4054 }
4055}
4056
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004057/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
4058 * doesn't allow "yield" functions because the HAProxy engine cannot
4059 * resume sample-fetches.
4060 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004061static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
4062 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004063{
4064 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004065 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004066
Willy Tarreau87b09662015-04-03 00:22:06 +02004067 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004068 * Lua context can be not initialized. This behavior
4069 * permits to save performances because a systematic
4070 * Lua initialization cause 5% performances loss.
4071 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004072 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
4073 send_log(stream->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004074 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4075 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
4076 return 0;
4077 }
4078
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004079 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004080 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004081 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004082 if (!lua_checkstack(stream->hlua.T, 2)) {
4083 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004084 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4085 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4086 return 0;
4087 }
4088
4089 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004090 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004091
4092 /* push arguments in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004093 if (!hlua_txn_new(stream->hlua.T, stream, smp->px)) {
4094 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004095 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4096 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4097 return 0;
4098 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004099 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004100
4101 /* push keywords in the stack. */
4102 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
4103 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004104 if (!lua_checkstack(stream->hlua.T, 1)) {
4105 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004106 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4107 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4108 return 0;
4109 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004110 if (!lua_checkstack(stream->hlua.T, 1)) {
4111 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004112 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4113 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4114 return 0;
4115 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004116 hlua_arg2lua(stream->hlua.T, arg_p);
4117 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004118 }
4119
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004120 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004121 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004122
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004123 /* Set the currently running flag. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004124 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004125 }
4126
4127 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004128 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004129 /* finished. */
4130 case HLUA_E_OK:
4131 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004132 hlua_lua2smp(stream->hlua.T, -1, smp);
4133 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004134
4135 /* Set the end of execution flag. */
4136 smp->flags &= ~SMP_F_MAY_CHANGE;
4137 return 1;
4138
4139 /* yield. */
4140 case HLUA_E_AGAIN:
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004141 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004142 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4143 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
4144 return 0;
4145
4146 /* finished with error. */
4147 case HLUA_E_ERRMSG:
4148 /* Display log. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004149 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': %s.", fcn->name, lua_tostring(stream->hlua.T, -1));
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004150 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004151 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
4152 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004153 return 0;
4154
4155 case HLUA_E_ERR:
4156 /* Display log. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004157 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004158 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4159 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
4160
4161 default:
4162 return 0;
4163 }
4164}
4165
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004166/* This function is an LUA binding used for registering
4167 * "sample-conv" functions. It expects a converter name used
4168 * in the haproxy configuration file, and an LUA function.
4169 */
4170__LJMP static int hlua_register_converters(lua_State *L)
4171{
4172 struct sample_conv_kw_list *sck;
4173 const char *name;
4174 int ref;
4175 int len;
4176 struct hlua_function *fcn;
4177
4178 MAY_LJMP(check_args(L, 2, "register_converters"));
4179
4180 /* First argument : converter name. */
4181 name = MAY_LJMP(luaL_checkstring(L, 1));
4182
4183 /* Second argument : lua function. */
4184 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4185
4186 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004187 sck = malloc(sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004188 if (!sck)
4189 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4190 fcn = malloc(sizeof(*fcn));
4191 if (!fcn)
4192 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4193
4194 /* Fill fcn. */
4195 fcn->name = strdup(name);
4196 if (!fcn->name)
4197 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4198 fcn->function_ref = ref;
4199
4200 /* List head */
4201 sck->list.n = sck->list.p = NULL;
4202
4203 /* converter keyword. */
4204 len = strlen("lua.") + strlen(name) + 1;
4205 sck->kw[0].kw = malloc(len);
4206 if (!sck->kw[0].kw)
4207 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4208
4209 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4210 sck->kw[0].process = hlua_sample_conv_wrapper;
4211 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4212 sck->kw[0].val_args = NULL;
4213 sck->kw[0].in_type = SMP_T_STR;
4214 sck->kw[0].out_type = SMP_T_STR;
4215 sck->kw[0].private = fcn;
4216
4217 /* End of array. */
4218 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
4219
4220 /* Register this new converter */
4221 sample_register_convs(sck);
4222
4223 return 0;
4224}
4225
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004226/* This fucntion is an LUA binding used for registering
4227 * "sample-fetch" functions. It expects a converter name used
4228 * in the haproxy configuration file, and an LUA function.
4229 */
4230__LJMP static int hlua_register_fetches(lua_State *L)
4231{
4232 const char *name;
4233 int ref;
4234 int len;
4235 struct sample_fetch_kw_list *sfk;
4236 struct hlua_function *fcn;
4237
4238 MAY_LJMP(check_args(L, 2, "register_fetches"));
4239
4240 /* First argument : sample-fetch name. */
4241 name = MAY_LJMP(luaL_checkstring(L, 1));
4242
4243 /* Second argument : lua function. */
4244 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4245
4246 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004247 sfk = malloc(sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004248 if (!sfk)
4249 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4250 fcn = malloc(sizeof(*fcn));
4251 if (!fcn)
4252 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4253
4254 /* Fill fcn. */
4255 fcn->name = strdup(name);
4256 if (!fcn->name)
4257 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4258 fcn->function_ref = ref;
4259
4260 /* List head */
4261 sfk->list.n = sfk->list.p = NULL;
4262
4263 /* sample-fetch keyword. */
4264 len = strlen("lua.") + strlen(name) + 1;
4265 sfk->kw[0].kw = malloc(len);
4266 if (!sfk->kw[0].kw)
4267 return luaL_error(L, "lua out of memory error.");
4268
4269 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4270 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4271 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4272 sfk->kw[0].val_args = NULL;
4273 sfk->kw[0].out_type = SMP_T_STR;
4274 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4275 sfk->kw[0].val = 0;
4276 sfk->kw[0].private = fcn;
4277
4278 /* End of array. */
4279 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
4280
4281 /* Register this new fetch. */
4282 sample_register_fetches(sfk);
4283
4284 return 0;
4285}
4286
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004287/* This function is a wrapper to execute each LUA function declared
4288 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004289 * return ACT_RET_CONT if the processing is finished (with or without
4290 * error) and return ACT_RET_YIELD if the function must be called again
4291 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004292 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004293static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
4294 struct session *sess, struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004295{
4296 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004297 unsigned int analyzer;
4298
4299 switch (rule->from) {
4300 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; break;
4301 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; break;
4302 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; break;
4303 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; break;
4304 default:
4305 send_log(px, LOG_ERR, "Lua: internal error while execute action.");
4306 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4307 Alert("Lua: internal error while execute action.\n");
4308 return ACT_RET_CONT;
4309 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004310
Willy Tarreau87b09662015-04-03 00:22:06 +02004311 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004312 * Lua context can be not initialized. This behavior
4313 * permits to save performances because a systematic
4314 * Lua initialization cause 5% performances loss.
4315 */
4316 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004317 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.",
4318 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004319 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004320 Alert("Lua action '%s': can't initialize Lua context.\n",
4321 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004322 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004323 }
4324
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004325 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004326 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004327 /* Check stack available size. */
4328 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004329 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4330 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004331 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004332 Alert("Lua function '%s': full stack.\n",
4333 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004334 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004335 }
4336
4337 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004338 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004339
Willy Tarreau87b09662015-04-03 00:22:06 +02004340 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004341 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004342 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4343 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004344 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004345 Alert("Lua function '%s': full stack.\n",
4346 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004347 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004348 }
4349 s->hlua.nargs = 1;
4350
4351 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004352 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004353 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004354 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4355 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004356 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004357 Alert("Lua function '%s': full stack.\n",
4358 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004359 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004360 }
4361 lua_pushstring(s->hlua.T, *arg);
4362 s->hlua.nargs++;
4363 }
4364
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004365 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004366 s->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004367
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004368 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004369 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004370 }
4371
4372 /* Execute the function. */
4373 switch (hlua_ctx_resume(&s->hlua, 1)) {
4374 /* finished. */
4375 case HLUA_E_OK:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004376 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004377
4378 /* yield. */
4379 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004380 /* Set timeout in the required channel. */
4381 if (s->hlua.wake_time != TICK_ETERNITY) {
4382 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004383 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004384 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004385 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004386 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004387 /* Some actions can be wake up when a "write" event
4388 * is detected on a response channel. This is useful
4389 * only for actions targetted on the requests.
4390 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004391 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004392 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01004393 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004394 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004395 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004396 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004397 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004398 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004399
4400 /* finished with error. */
4401 case HLUA_E_ERRMSG:
4402 /* Display log. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004403 send_log(px, LOG_ERR, "Lua function '%s': %s.",
4404 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004405 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004406 Alert("Lua function '%s': %s.\n",
4407 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004408 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004409 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004410
4411 case HLUA_E_ERR:
4412 /* Display log. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004413 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.",
4414 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004415 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004416 Alert("Lua function '%s' return an unknown error.\n",
4417 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004418
4419 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004420 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004421 }
4422}
4423
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004424/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
4425 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004426 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004427static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4428 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004429{
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004430 /* Memory for the rule. */
4431 rule->arg.hlua_rule = malloc(sizeof(*rule->arg.hlua_rule));
4432 if (!rule->arg.hlua_rule) {
4433 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004434 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004435 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004436
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004437 /* The requiered arg is a function name. */
4438 if (!args[*cur_arg]) {
4439 memprintf(err, "expect Lua function name");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004440 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004441 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004442
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004443 /* Lookup for the symbol, and check if it is a function. */
4444 lua_getglobal(gL.T, args[*cur_arg]);
4445 if (lua_isnil(gL.T, -1)) {
4446 lua_pop(gL.T, 1);
4447 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004448 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004449 }
4450 if (!lua_isfunction(gL.T, -1)) {
4451 lua_pop(gL.T, 1);
4452 memprintf(err, "'%s' is not a function", args[*cur_arg]);
4453 return ACT_RET_PRS_ERR;
4454 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004455
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004456 /* Reference the Lua function and store the reference. */
4457 rule->arg.hlua_rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
4458 rule->arg.hlua_rule->fcn.name = strdup(args[*cur_arg]);
4459 if (!rule->arg.hlua_rule->fcn.name) {
4460 memprintf(err, "out of memory error.");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004461 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004462 }
4463 (*cur_arg)++;
4464
4465 /* TODO: later accept arguments. */
4466 rule->arg.hlua_rule->args = NULL;
4467
Thierry FOURNIER42148732015-09-02 17:17:33 +02004468 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004469 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004470 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004471}
4472
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004473static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4474 struct proxy *defpx, const char *file, int line,
4475 char **err, unsigned int *timeout)
4476{
4477 const char *error;
4478
4479 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4480 if (error && *error != '\0') {
4481 memprintf(err, "%s: invalid timeout", args[0]);
4482 return -1;
4483 }
4484 return 0;
4485}
4486
4487static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4488 struct proxy *defpx, const char *file, int line,
4489 char **err)
4490{
4491 return hlua_read_timeout(args, section_type, curpx, defpx,
4492 file, line, err, &hlua_timeout_session);
4493}
4494
4495static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4496 struct proxy *defpx, const char *file, int line,
4497 char **err)
4498{
4499 return hlua_read_timeout(args, section_type, curpx, defpx,
4500 file, line, err, &hlua_timeout_task);
4501}
4502
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004503static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4504 struct proxy *defpx, const char *file, int line,
4505 char **err)
4506{
4507 char *error;
4508
4509 hlua_nb_instruction = strtoll(args[1], &error, 10);
4510 if (*error != '\0') {
4511 memprintf(err, "%s: invalid number", args[0]);
4512 return -1;
4513 }
4514 return 0;
4515}
4516
Willy Tarreau32f61e22015-03-18 17:54:59 +01004517static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4518 struct proxy *defpx, const char *file, int line,
4519 char **err)
4520{
4521 char *error;
4522
4523 if (*(args[1]) == 0) {
4524 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4525 return -1;
4526 }
4527 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4528 if (*error != '\0') {
4529 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4530 return -1;
4531 }
4532 return 0;
4533}
4534
4535
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004536/* This function is called by the main configuration key "lua-load". It loads and
4537 * execute an lua file during the parsing of the HAProxy configuration file. It is
4538 * the main lua entry point.
4539 *
4540 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4541 * occured, otherwise it returns 0.
4542 *
4543 * In some error case, LUA set an error message in top of the stack. This function
4544 * returns this error message in the HAProxy logs and pop it from the stack.
4545 */
4546static int hlua_load(char **args, int section_type, struct proxy *curpx,
4547 struct proxy *defpx, const char *file, int line,
4548 char **err)
4549{
4550 int error;
4551
4552 /* Just load and compile the file. */
4553 error = luaL_loadfile(gL.T, args[1]);
4554 if (error) {
4555 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4556 lua_pop(gL.T, 1);
4557 return -1;
4558 }
4559
4560 /* If no syntax error where detected, execute the code. */
4561 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4562 switch (error) {
4563 case LUA_OK:
4564 break;
4565 case LUA_ERRRUN:
4566 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4567 lua_pop(gL.T, 1);
4568 return -1;
4569 case LUA_ERRMEM:
4570 memprintf(err, "lua out of memory error\n");
4571 return -1;
4572 case LUA_ERRERR:
4573 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4574 lua_pop(gL.T, 1);
4575 return -1;
4576 case LUA_ERRGCMM:
4577 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4578 lua_pop(gL.T, 1);
4579 return -1;
4580 default:
4581 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4582 lua_pop(gL.T, 1);
4583 return -1;
4584 }
4585
4586 return 0;
4587}
4588
4589/* configuration keywords declaration */
4590static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004591 { CFG_GLOBAL, "lua-load", hlua_load },
4592 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4593 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004594 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01004595 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004596 { 0, NULL, NULL },
4597}};
4598
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004599static struct action_kw_list http_req_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004600 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004601 { NULL, NULL }
4602}};
4603
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004604static struct action_kw_list http_res_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004605 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004606 { NULL, NULL }
4607}};
4608
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004609static struct action_kw_list tcp_req_cont_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004610 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004611 { NULL, NULL }
4612}};
4613
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004614static struct action_kw_list tcp_res_cont_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004615 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004616 { NULL, NULL }
4617}};
4618
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004619int hlua_post_init()
4620{
4621 struct hlua_init_function *init;
4622 const char *msg;
4623 enum hlua_exec ret;
4624
4625 list_for_each_entry(init, &hlua_init_functions, l) {
4626 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4627 ret = hlua_ctx_resume(&gL, 0);
4628 switch (ret) {
4629 case HLUA_E_OK:
4630 lua_pop(gL.T, -1);
4631 return 1;
4632 case HLUA_E_AGAIN:
4633 Alert("lua init: yield not allowed.\n");
4634 return 0;
4635 case HLUA_E_ERRMSG:
4636 msg = lua_tostring(gL.T, -1);
4637 Alert("lua init: %s.\n", msg);
4638 return 0;
4639 case HLUA_E_ERR:
4640 default:
4641 Alert("lua init: unknown runtime error.\n");
4642 return 0;
4643 }
4644 }
4645 return 1;
4646}
4647
Willy Tarreau32f61e22015-03-18 17:54:59 +01004648/* The memory allocator used by the Lua stack. <ud> is a pointer to the
4649 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4650 * is the previously allocated size or the kind of object in case of a new
4651 * allocation. <nsize> is the requested new size.
4652 */
4653static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4654{
4655 struct hlua_mem_allocator *zone = ud;
4656
4657 if (nsize == 0) {
4658 /* it's a free */
4659 if (ptr)
4660 zone->allocated -= osize;
4661 free(ptr);
4662 return NULL;
4663 }
4664
4665 if (!ptr) {
4666 /* it's a new allocation */
4667 if (zone->limit && zone->allocated + nsize > zone->limit)
4668 return NULL;
4669
4670 ptr = malloc(nsize);
4671 if (ptr)
4672 zone->allocated += nsize;
4673 return ptr;
4674 }
4675
4676 /* it's a realloc */
4677 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4678 return NULL;
4679
4680 ptr = realloc(ptr, nsize);
4681 if (ptr)
4682 zone->allocated += nsize - osize;
4683 return ptr;
4684}
4685
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004686void hlua_init(void)
4687{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004688 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004689 int idx;
4690 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004691 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004692 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004693#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004694 struct srv_kw *kw;
4695 int tmp_error;
4696 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01004697 char *args[] = { /* SSL client configuration. */
4698 "ssl",
4699 "verify",
4700 "none",
4701 "force-sslv3",
4702 NULL
4703 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004704#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004705
Willy Tarreau87b09662015-04-03 00:22:06 +02004706 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004707 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4708
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004709 /* Register configuration keywords. */
4710 cfg_register_keywords(&cfg_kws);
4711
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004712 /* Register custom HTTP rules. */
4713 http_req_keywords_register(&http_req_kws);
4714 http_res_keywords_register(&http_res_kws);
4715 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
4716 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
4717
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004718 /* Init main lua stack. */
4719 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004720 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004721 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004722 gL.T = luaL_newstate();
4723 hlua_sethlua(&gL);
4724 gL.Tref = LUA_REFNIL;
4725 gL.task = NULL;
4726
Willy Tarreau32f61e22015-03-18 17:54:59 +01004727 /* change the memory allocators to track memory usage */
4728 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4729
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004730 /* Initialise lua. */
4731 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004732
4733 /*
4734 *
4735 * Create "core" object.
4736 *
4737 */
4738
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004739 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004740 lua_newtable(gL.T);
4741
4742 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004743 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004744 hlua_class_const_int(gL.T, log_levels[i], i);
4745
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004746 /* Register special functions. */
4747 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004748 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004749 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004750 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004751 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004752 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004753 hlua_class_function(gL.T, "sleep", hlua_sleep);
4754 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004755 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4756 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4757 hlua_class_function(gL.T, "set_map", hlua_set_map);
4758 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004759 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004760 hlua_class_function(gL.T, "log", hlua_log);
4761 hlua_class_function(gL.T, "Debug", hlua_log_debug);
4762 hlua_class_function(gL.T, "Info", hlua_log_info);
4763 hlua_class_function(gL.T, "Warning", hlua_log_warning);
4764 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02004765 hlua_class_function(gL.T, "done", hlua_done);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004766
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004767 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004768
4769 /*
4770 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02004771 * Register class Map
4772 *
4773 */
4774
4775 /* This table entry is the object "Map" base. */
4776 lua_newtable(gL.T);
4777
4778 /* register pattern types. */
4779 for (i=0; i<PAT_MATCH_NUM; i++)
4780 hlua_class_const_int(gL.T, pat_match_names[i], i);
4781
4782 /* register constructor. */
4783 hlua_class_function(gL.T, "new", hlua_map_new);
4784
4785 /* Create and fill the metatable. */
4786 lua_newtable(gL.T);
4787
4788 /* Create and fille the __index entry. */
4789 lua_pushstring(gL.T, "__index");
4790 lua_newtable(gL.T);
4791
4792 /* Register . */
4793 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
4794 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
4795
4796 lua_settable(gL.T, -3);
4797
4798 /* Register previous table in the registry with reference and named entry. */
4799 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4800 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4801 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
4802 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4803
4804 /* Assign the metatable to the mai Map object. */
4805 lua_setmetatable(gL.T, -2);
4806
4807 /* Set a name to the table. */
4808 lua_setglobal(gL.T, "Map");
4809
4810 /*
4811 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004812 * Register class Channel
4813 *
4814 */
4815
4816 /* Create and fill the metatable. */
4817 lua_newtable(gL.T);
4818
4819 /* Create and fille the __index entry. */
4820 lua_pushstring(gL.T, "__index");
4821 lua_newtable(gL.T);
4822
4823 /* Register . */
4824 hlua_class_function(gL.T, "get", hlua_channel_get);
4825 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4826 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4827 hlua_class_function(gL.T, "set", hlua_channel_set);
4828 hlua_class_function(gL.T, "append", hlua_channel_append);
4829 hlua_class_function(gL.T, "send", hlua_channel_send);
4830 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4831 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4832 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4833
4834 lua_settable(gL.T, -3);
4835
4836 /* Register previous table in the registry with reference and named entry. */
4837 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4838 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4839 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4840
4841 /*
4842 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004843 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004844 *
4845 */
4846
4847 /* Create and fill the metatable. */
4848 lua_newtable(gL.T);
4849
4850 /* Create and fille the __index entry. */
4851 lua_pushstring(gL.T, "__index");
4852 lua_newtable(gL.T);
4853
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004854 /* Browse existing fetches and create the associated
4855 * object method.
4856 */
4857 sf = NULL;
4858 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4859
4860 /* Dont register the keywork if the arguments check function are
4861 * not safe during the runtime.
4862 */
4863 if ((sf->val_args != NULL) &&
4864 (sf->val_args != val_payload_lv) &&
4865 (sf->val_args != val_hdr))
4866 continue;
4867
4868 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4869 * by an underscore.
4870 */
4871 strncpy(trash.str, sf->kw, trash.size);
4872 trash.str[trash.size - 1] = '\0';
4873 for (p = trash.str; *p; p++)
4874 if (*p == '.' || *p == '-' || *p == '+')
4875 *p = '_';
4876
4877 /* Register the function. */
4878 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01004879 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004880 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4881 lua_settable(gL.T, -3);
4882 }
4883
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004884 lua_settable(gL.T, -3);
4885
4886 /* Register previous table in the registry with reference and named entry. */
4887 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4888 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4889 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4890
4891 /*
4892 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004893 * Register class Converters
4894 *
4895 */
4896
4897 /* Create and fill the metatable. */
4898 lua_newtable(gL.T);
4899
4900 /* Create and fill the __index entry. */
4901 lua_pushstring(gL.T, "__index");
4902 lua_newtable(gL.T);
4903
4904 /* Browse existing converters and create the associated
4905 * object method.
4906 */
4907 sc = NULL;
4908 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4909 /* Dont register the keywork if the arguments check function are
4910 * not safe during the runtime.
4911 */
4912 if (sc->val_args != NULL)
4913 continue;
4914
4915 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4916 * by an underscore.
4917 */
4918 strncpy(trash.str, sc->kw, trash.size);
4919 trash.str[trash.size - 1] = '\0';
4920 for (p = trash.str; *p; p++)
4921 if (*p == '.' || *p == '-' || *p == '+')
4922 *p = '_';
4923
4924 /* Register the function. */
4925 lua_pushstring(gL.T, trash.str);
4926 lua_pushlightuserdata(gL.T, sc);
4927 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4928 lua_settable(gL.T, -3);
4929 }
4930
4931 lua_settable(gL.T, -3);
4932
4933 /* Register previous table in the registry with reference and named entry. */
4934 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4935 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4936 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4937
4938 /*
4939 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004940 * Register class HTTP
4941 *
4942 */
4943
4944 /* Create and fill the metatable. */
4945 lua_newtable(gL.T);
4946
4947 /* Create and fille the __index entry. */
4948 lua_pushstring(gL.T, "__index");
4949 lua_newtable(gL.T);
4950
4951 /* Register Lua functions. */
4952 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
4953 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
4954 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
4955 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
4956 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
4957 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
4958 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
4959 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
4960 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
4961 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
4962
4963 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
4964 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
4965 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
4966 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
4967 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
4968 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004969 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004970
4971 lua_settable(gL.T, -3);
4972
4973 /* Register previous table in the registry with reference and named entry. */
4974 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4975 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
4976 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4977
4978 /*
4979 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004980 * Register class TXN
4981 *
4982 */
4983
4984 /* Create and fill the metatable. */
4985 lua_newtable(gL.T);
4986
4987 /* Create and fille the __index entry. */
4988 lua_pushstring(gL.T, "__index");
4989 lua_newtable(gL.T);
4990
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004991 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004992 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4993 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004994 hlua_class_function(gL.T, "set_var", hlua_set_var);
4995 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02004996 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004997 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
4998 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
4999 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005000 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
5001 hlua_class_function(gL.T, "log", hlua_txn_log);
5002 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
5003 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
5004 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
5005 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005006
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005007 lua_settable(gL.T, -3);
5008
5009 /* Register previous table in the registry with reference and named entry. */
5010 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5011 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
5012 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005013
5014 /*
5015 *
5016 * Register class Socket
5017 *
5018 */
5019
5020 /* Create and fill the metatable. */
5021 lua_newtable(gL.T);
5022
5023 /* Create and fille the __index entry. */
5024 lua_pushstring(gL.T, "__index");
5025 lua_newtable(gL.T);
5026
Baptiste Assmann84bb4932015-03-02 21:40:06 +01005027#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005028 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01005029#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005030 hlua_class_function(gL.T, "connect", hlua_socket_connect);
5031 hlua_class_function(gL.T, "send", hlua_socket_send);
5032 hlua_class_function(gL.T, "receive", hlua_socket_receive);
5033 hlua_class_function(gL.T, "close", hlua_socket_close);
5034 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
5035 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
5036 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
5037 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
5038
5039 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5040
5041 /* Register the garbage collector entry. */
5042 lua_pushstring(gL.T, "__gc");
5043 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
5044 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5045
5046 /* Register previous table in the registry with reference and named entry. */
5047 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5048 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5049 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
5050 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
5051
5052 /* Proxy and server configuration initialisation. */
5053 memset(&socket_proxy, 0, sizeof(socket_proxy));
5054 init_new_proxy(&socket_proxy);
5055 socket_proxy.parent = NULL;
5056 socket_proxy.last_change = now.tv_sec;
5057 socket_proxy.id = "LUA-SOCKET";
5058 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
5059 socket_proxy.maxconn = 0;
5060 socket_proxy.accept = NULL;
5061 socket_proxy.options2 |= PR_O2_INDEPSTR;
5062 socket_proxy.srv = NULL;
5063 socket_proxy.conn_retries = 0;
5064 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
5065
5066 /* Init TCP server: unchanged parameters */
5067 memset(&socket_tcp, 0, sizeof(socket_tcp));
5068 socket_tcp.next = NULL;
5069 socket_tcp.proxy = &socket_proxy;
5070 socket_tcp.obj_type = OBJ_TYPE_SERVER;
5071 LIST_INIT(&socket_tcp.actconns);
5072 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005073 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005074 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005075 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005076 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
5077 socket_tcp.last_change = 0;
5078 socket_tcp.id = "LUA-TCP-CONN";
5079 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5080 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5081 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
5082
5083 /* XXX: Copy default parameter from default server,
5084 * but the default server is not initialized.
5085 */
5086 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
5087 socket_tcp.minconn = socket_proxy.defsrv.minconn;
5088 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
5089 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
5090 socket_tcp.onerror = socket_proxy.defsrv.onerror;
5091 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5092 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
5093 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5094 socket_tcp.uweight = socket_proxy.defsrv.iweight;
5095 socket_tcp.iweight = socket_proxy.defsrv.iweight;
5096
5097 socket_tcp.check.status = HCHK_STATUS_INI;
5098 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
5099 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
5100 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
5101 socket_tcp.check.server = &socket_tcp;
5102
5103 socket_tcp.agent.status = HCHK_STATUS_INI;
5104 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
5105 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
5106 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
5107 socket_tcp.agent.server = &socket_tcp;
5108
5109 socket_tcp.xprt = &raw_sock;
5110
5111#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005112 /* Init TCP server: unchanged parameters */
5113 memset(&socket_ssl, 0, sizeof(socket_ssl));
5114 socket_ssl.next = NULL;
5115 socket_ssl.proxy = &socket_proxy;
5116 socket_ssl.obj_type = OBJ_TYPE_SERVER;
5117 LIST_INIT(&socket_ssl.actconns);
5118 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005119 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005120 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005121 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005122 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
5123 socket_ssl.last_change = 0;
5124 socket_ssl.id = "LUA-SSL-CONN";
5125 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5126 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5127 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
5128
5129 /* XXX: Copy default parameter from default server,
5130 * but the default server is not initialized.
5131 */
5132 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
5133 socket_ssl.minconn = socket_proxy.defsrv.minconn;
5134 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
5135 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5136 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5137 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5138 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5139 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5140 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5141 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5142
5143 socket_ssl.check.status = HCHK_STATUS_INI;
5144 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5145 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5146 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5147 socket_ssl.check.server = &socket_ssl;
5148
5149 socket_ssl.agent.status = HCHK_STATUS_INI;
5150 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5151 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5152 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5153 socket_ssl.agent.server = &socket_ssl;
5154
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005155 socket_ssl.use_ssl = 1;
5156 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005157
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005158 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005159 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5160 /*
5161 *
5162 * If the keyword is not known, we can search in the registered
5163 * server keywords. This is usefull to configure special SSL
5164 * features like client certificates and ssl_verify.
5165 *
5166 */
5167 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5168 if (tmp_error != 0) {
5169 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5170 abort(); /* This must be never arrives because the command line
5171 not editable by the user. */
5172 }
5173 idx += kw->skip;
5174 }
5175 }
5176
5177 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005178 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005179#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005180}