blob: 1e4d47c31e66c16c837ff2aa5ef577f6cafdc7e7 [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
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001464 /* if the connection is not estabkished, inform the stream that we want
1465 * to be notified whenever the connection completes.
1466 */
1467 if (!(c->flags & CO_FL_CONNECTED)) {
1468 si_applet_cant_get(si);
1469 si_applet_cant_put(si);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001470 return;
Thierry FOURNIER316e3192015-09-04 18:25:53 +02001471 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001472
1473 /* This function is called after the connect. */
1474 appctx->ctx.hlua.connected = 1;
1475
1476 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001477 if (channel_may_recv(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001478 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1479
1480 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001481 if (channel_is_empty(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001482 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1483}
1484
Willy Tarreau87b09662015-04-03 00:22:06 +02001485/* This function is called when the "struct stream" is destroyed.
1486 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001487 * Wake all the pending signals.
1488 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001489static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001490{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001491 /* Remove my link in the original object. */
1492 if (appctx->ctx.hlua.socket)
1493 appctx->ctx.hlua.socket->s = NULL;
1494
1495 /* Wake all the task waiting for me. */
1496 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1497 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1498}
1499
1500/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001501 * uses this object. If the stream does not exists, just quit.
1502 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001503 * pending signal can rest in the read and write lists. destroy
1504 * it.
1505 */
1506__LJMP static int hlua_socket_gc(lua_State *L)
1507{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001508 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001509 struct appctx *appctx;
1510
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001511 MAY_LJMP(check_args(L, 1, "__gc"));
1512
1513 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001514 if (!socket->s)
1515 return 0;
1516
Willy Tarreau87b09662015-04-03 00:22:06 +02001517 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001518 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001519 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001520 socket->s = NULL;
1521 appctx->ctx.hlua.socket = NULL;
1522
1523 return 0;
1524}
1525
1526/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001527 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001528 */
1529__LJMP static int hlua_socket_close(lua_State *L)
1530{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001531 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001532 struct appctx *appctx;
1533
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001534 MAY_LJMP(check_args(L, 1, "close"));
1535
1536 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001537 if (!socket->s)
1538 return 0;
1539
Willy Tarreau87b09662015-04-03 00:22:06 +02001540 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001541 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001542 appctx = objt_appctx(socket->s->si[0].end);
1543 appctx->ctx.hlua.socket = NULL;
1544 socket->s = NULL;
1545
1546 return 0;
1547}
1548
1549/* This Lua function assumes that the stack contain three parameters.
1550 * 1 - USERDATA containing a struct socket
1551 * 2 - INTEGER with values of the macro defined below
1552 * If the integer is -1, we must read at most one line.
1553 * If the integer is -2, we ust read all the data until the
1554 * end of the stream.
1555 * If the integer is positive value, we must read a number of
1556 * bytes corresponding to this value.
1557 */
1558#define HLSR_READ_LINE (-1)
1559#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001560__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001561{
1562 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1563 int wanted = lua_tointeger(L, 2);
1564 struct hlua *hlua = hlua_gethlua(L);
1565 struct appctx *appctx;
1566 int len;
1567 int nblk;
1568 char *blk1;
1569 int len1;
1570 char *blk2;
1571 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001572 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001573 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001574
1575 /* Check if this lua stack is schedulable. */
1576 if (!hlua || !hlua->task)
1577 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1578 "'frontend', 'backend' or 'task'"));
1579
1580 /* check for connection closed. If some data where read, return it. */
1581 if (!socket->s)
1582 goto connection_closed;
1583
Willy Tarreau94aa6172015-03-13 14:19:06 +01001584 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001585 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001586 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001587 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001588 if (nblk < 0) /* Connection close. */
1589 goto connection_closed;
1590 if (nblk == 0) /* No data avalaible. */
1591 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001592
1593 /* remove final \r\n. */
1594 if (nblk == 1) {
1595 if (blk1[len1-1] == '\n') {
1596 len1--;
1597 skip_at_end++;
1598 if (blk1[len1-1] == '\r') {
1599 len1--;
1600 skip_at_end++;
1601 }
1602 }
1603 }
1604 else {
1605 if (blk2[len2-1] == '\n') {
1606 len2--;
1607 skip_at_end++;
1608 if (blk2[len2-1] == '\r') {
1609 len2--;
1610 skip_at_end++;
1611 }
1612 }
1613 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001614 }
1615
1616 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001617 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001618 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001619 if (nblk < 0) /* Connection close. */
1620 goto connection_closed;
1621 if (nblk == 0) /* No data avalaible. */
1622 goto connection_empty;
1623 }
1624
1625 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001626 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001627 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001628 if (nblk < 0) /* Connection close. */
1629 goto connection_closed;
1630 if (nblk == 0) /* No data avalaible. */
1631 goto connection_empty;
1632
1633 if (len1 > wanted) {
1634 nblk = 1;
1635 len1 = wanted;
1636 } if (nblk == 2 && len1 + len2 > wanted)
1637 len2 = wanted - len1;
1638 }
1639
1640 len = len1;
1641
1642 luaL_addlstring(&socket->b, blk1, len1);
1643 if (nblk == 2) {
1644 len += len2;
1645 luaL_addlstring(&socket->b, blk2, len2);
1646 }
1647
1648 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001649 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001650
1651 /* Don't wait anything. */
Willy Tarreau828824a2015-04-19 17:20:03 +02001652 si_applet_done(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001653
1654 /* If the pattern reclaim to read all the data
1655 * in the connection, got out.
1656 */
1657 if (wanted == HLSR_READ_ALL)
1658 goto connection_empty;
1659 else if (wanted >= 0 && len < wanted)
1660 goto connection_empty;
1661
1662 /* Return result. */
1663 luaL_pushresult(&socket->b);
1664 return 1;
1665
1666connection_closed:
1667
1668 /* If the buffer containds data. */
1669 if (socket->b.n > 0) {
1670 luaL_pushresult(&socket->b);
1671 return 1;
1672 }
1673 lua_pushnil(L);
1674 lua_pushstring(L, "connection closed.");
1675 return 2;
1676
1677connection_empty:
1678
1679 appctx = objt_appctx(socket->s->si[0].end);
1680 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1681 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001682 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001683 return 0;
1684}
1685
1686/* This Lus function gets two parameters. The first one can be string
1687 * or a number. If the string is "*l", the user require one line. If
1688 * the string is "*a", the user require all the content of the stream.
1689 * If the value is a number, the user require a number of bytes equal
1690 * to the value. The default value is "*l" (a line).
1691 *
1692 * This paraeter with a variable type is converted in integer. This
1693 * integer takes this values:
1694 * -1 : read a line
1695 * -2 : read all the stream
1696 * >0 : amount if bytes.
1697 *
1698 * The second parameter is optinal. It contains a string that must be
1699 * concatenated with the read data.
1700 */
1701__LJMP static int hlua_socket_receive(struct lua_State *L)
1702{
1703 int wanted = HLSR_READ_LINE;
1704 const char *pattern;
1705 int type;
1706 char *error;
1707 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001708 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001709
1710 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1711 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1712
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001713 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001714
1715 /* check for pattern. */
1716 if (lua_gettop(L) >= 2) {
1717 type = lua_type(L, 2);
1718 if (type == LUA_TSTRING) {
1719 pattern = lua_tostring(L, 2);
1720 if (strcmp(pattern, "*a") == 0)
1721 wanted = HLSR_READ_ALL;
1722 else if (strcmp(pattern, "*l") == 0)
1723 wanted = HLSR_READ_LINE;
1724 else {
1725 wanted = strtoll(pattern, &error, 10);
1726 if (*error != '\0')
1727 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1728 }
1729 }
1730 else if (type == LUA_TNUMBER) {
1731 wanted = lua_tointeger(L, 2);
1732 if (wanted < 0)
1733 WILL_LJMP(luaL_error(L, "Unsupported size."));
1734 }
1735 }
1736
1737 /* Set pattern. */
1738 lua_pushinteger(L, wanted);
1739 lua_replace(L, 2);
1740
1741 /* init bufffer, and fiil it wih prefix. */
1742 luaL_buffinit(L, &socket->b);
1743
1744 /* Check prefix. */
1745 if (lua_gettop(L) >= 3) {
1746 if (lua_type(L, 3) != LUA_TSTRING)
1747 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1748 pattern = lua_tolstring(L, 3, &len);
1749 luaL_addlstring(&socket->b, pattern, len);
1750 }
1751
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001752 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001753}
1754
1755/* Write the Lua input string in the output buffer.
1756 * This fucntion returns a yield if no space are available.
1757 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001758static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001759{
1760 struct hlua_socket *socket;
1761 struct hlua *hlua = hlua_gethlua(L);
1762 struct appctx *appctx;
1763 size_t buf_len;
1764 const char *buf;
1765 int len;
1766 int send_len;
1767 int sent;
1768
1769 /* Check if this lua stack is schedulable. */
1770 if (!hlua || !hlua->task)
1771 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1772 "'frontend', 'backend' or 'task'"));
1773
1774 /* Get object */
1775 socket = MAY_LJMP(hlua_checksocket(L, 1));
1776 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001777 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001778
1779 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001780 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001781 lua_pushinteger(L, -1);
1782 return 1;
1783 }
1784
1785 /* Update the input buffer data. */
1786 buf += sent;
1787 send_len = buf_len - sent;
1788
1789 /* All the data are sent. */
1790 if (sent >= buf_len)
1791 return 1; /* Implicitly return the length sent. */
1792
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001793 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1794 * the request buffer if its not required.
1795 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001796 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001797 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001798 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001799 goto hlua_socket_write_yield_return;
1800 }
1801 }
1802
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001803 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001804 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001805 if (len <= 0)
1806 goto hlua_socket_write_yield_return;
1807
1808 /* send data */
1809 if (len < send_len)
1810 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001811 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001812
1813 /* "Not enough space" (-1), "Buffer too little to contain
1814 * the data" (-2) are not expected because the available length
1815 * is tested.
1816 * Other unknown error are also not expected.
1817 */
1818 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001819 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001820 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001821
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001822 MAY_LJMP(hlua_socket_close(L));
1823 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001824 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001825 return 1;
1826 }
1827
1828 /* update buffers. */
Willy Tarreau828824a2015-04-19 17:20:03 +02001829 si_applet_done(&socket->s->si[0]);
Willy Tarreau94aa6172015-03-13 14:19:06 +01001830 socket->s->req.rex = TICK_ETERNITY;
1831 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001832
1833 /* Update length sent. */
1834 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001835 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001836
1837 /* All the data buffer is sent ? */
1838 if (sent + len >= buf_len)
1839 return 1;
1840
1841hlua_socket_write_yield_return:
1842 appctx = objt_appctx(socket->s->si[0].end);
1843 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1844 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001845 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001846 return 0;
1847}
1848
1849/* This function initiate the send of data. It just check the input
1850 * parameters and push an integer in the Lua stack that contain the
1851 * amount of data writed in the buffer. This is used by the function
1852 * "hlua_socket_write_yield" that can yield.
1853 *
1854 * The Lua function gets between 3 and 4 parameters. The first one is
1855 * the associated object. The second is a string buffer. The third is
1856 * a facultative integer that represents where is the buffer position
1857 * of the start of the data that can send. The first byte is the
1858 * position "1". The default value is "1". The fourth argument is a
1859 * facultative integer that represents where is the buffer position
1860 * of the end of the data that can send. The default is the last byte.
1861 */
1862static int hlua_socket_send(struct lua_State *L)
1863{
1864 int i;
1865 int j;
1866 const char *buf;
1867 size_t buf_len;
1868
1869 /* Check number of arguments. */
1870 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1871 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1872
1873 /* Get the string. */
1874 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1875
1876 /* Get and check j. */
1877 if (lua_gettop(L) == 4) {
1878 j = MAY_LJMP(luaL_checkinteger(L, 4));
1879 if (j < 0)
1880 j = buf_len + j + 1;
1881 if (j > buf_len)
1882 j = buf_len + 1;
1883 lua_pop(L, 1);
1884 }
1885 else
1886 j = buf_len;
1887
1888 /* Get and check i. */
1889 if (lua_gettop(L) == 3) {
1890 i = MAY_LJMP(luaL_checkinteger(L, 3));
1891 if (i < 0)
1892 i = buf_len + i + 1;
1893 if (i > buf_len)
1894 i = buf_len + 1;
1895 lua_pop(L, 1);
1896 } else
1897 i = 1;
1898
1899 /* Check bth i and j. */
1900 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001901 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001902 return 1;
1903 }
1904 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001905 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001906 return 1;
1907 }
1908 if (i == 0)
1909 i = 1;
1910 if (j == 0)
1911 j = 1;
1912
1913 /* Pop the string. */
1914 lua_pop(L, 1);
1915
1916 /* Update the buffer length. */
1917 buf += i - 1;
1918 buf_len = j - i + 1;
1919 lua_pushlstring(L, buf, buf_len);
1920
1921 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001922 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001923
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001924 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001925}
1926
Willy Tarreau22b0a682015-06-17 19:43:49 +02001927#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001928__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1929{
1930 static char buffer[SOCKET_INFO_MAX_LEN];
1931 int ret;
1932 int len;
1933 char *p;
1934
1935 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1936 if (ret <= 0) {
1937 lua_pushnil(L);
1938 return 1;
1939 }
1940
1941 if (ret == AF_UNIX) {
1942 lua_pushstring(L, buffer+1);
1943 return 1;
1944 }
1945 else if (ret == AF_INET6) {
1946 buffer[0] = '[';
1947 len = strlen(buffer);
1948 buffer[len] = ']';
1949 len++;
1950 buffer[len] = ':';
1951 len++;
1952 p = buffer;
1953 }
1954 else if (ret == AF_INET) {
1955 p = buffer + 1;
1956 len = strlen(p);
1957 p[len] = ':';
1958 len++;
1959 }
1960 else {
1961 lua_pushnil(L);
1962 return 1;
1963 }
1964
1965 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1966 lua_pushnil(L);
1967 return 1;
1968 }
1969
1970 lua_pushstring(L, p);
1971 return 1;
1972}
1973
1974/* Returns information about the peer of the connection. */
1975__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1976{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001977 struct hlua_socket *socket;
1978 struct connection *conn;
1979
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001980 MAY_LJMP(check_args(L, 1, "getpeername"));
1981
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001982 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001983
1984 /* Check if the tcp object is avalaible. */
1985 if (!socket->s) {
1986 lua_pushnil(L);
1987 return 1;
1988 }
1989
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001990 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001991 if (!conn) {
1992 lua_pushnil(L);
1993 return 1;
1994 }
1995
1996 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1997 unsigned int salen = sizeof(conn->addr.to);
1998 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1999 lua_pushnil(L);
2000 return 1;
2001 }
2002 conn->flags |= CO_FL_ADDR_TO_SET;
2003 }
2004
2005 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
2006}
2007
2008/* Returns information about my connection side. */
2009static int hlua_socket_getsockname(struct lua_State *L)
2010{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002011 struct hlua_socket *socket;
2012 struct connection *conn;
2013
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002014 MAY_LJMP(check_args(L, 1, "getsockname"));
2015
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002016 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002017
2018 /* Check if the tcp object is avalaible. */
2019 if (!socket->s) {
2020 lua_pushnil(L);
2021 return 1;
2022 }
2023
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002024 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002025 if (!conn) {
2026 lua_pushnil(L);
2027 return 1;
2028 }
2029
2030 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2031 unsigned int salen = sizeof(conn->addr.from);
2032 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2033 lua_pushnil(L);
2034 return 1;
2035 }
2036 conn->flags |= CO_FL_ADDR_FROM_SET;
2037 }
2038
2039 return hlua_socket_info(L, &conn->addr.from);
2040}
2041
2042/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002043static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002044 .obj_type = OBJ_TYPE_APPLET,
2045 .name = "<LUA_TCP>",
2046 .fct = hlua_socket_handler,
2047 .release = hlua_socket_release,
2048};
2049
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002050__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002051{
2052 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2053 struct hlua *hlua = hlua_gethlua(L);
2054 struct appctx *appctx;
2055
2056 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002057 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002058 lua_pushnil(L);
2059 lua_pushstring(L, "Can't connect");
2060 return 2;
2061 }
2062
2063 appctx = objt_appctx(socket->s->si[0].end);
2064
2065 /* Check for connection established. */
2066 if (appctx->ctx.hlua.connected) {
2067 lua_pushinteger(L, 1);
2068 return 1;
2069 }
2070
2071 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2072 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002073 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002074 return 0;
2075}
2076
2077/* This function fail or initite the connection. */
2078__LJMP static int hlua_socket_connect(struct lua_State *L)
2079{
2080 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002081 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002082 const char *ip;
2083 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002084 struct hlua *hlua;
2085 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086
2087 MAY_LJMP(check_args(L, 3, "connect"));
2088
2089 /* Get args. */
2090 socket = MAY_LJMP(hlua_checksocket(L, 1));
2091 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002092 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002093
Willy Tarreau973a5422015-08-05 21:47:23 +02002094 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095 if (!conn)
2096 WILL_LJMP(luaL_error(L, "connect: internal error"));
2097
2098 /* Parse ip address. */
2099 conn->addr.to.ss_family = AF_UNSPEC;
2100 if (!str2ip2(ip, &conn->addr.to, 0))
2101 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
2102
2103 /* Set port. */
2104 if (conn->addr.to.ss_family == AF_INET)
2105 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2106 else if (conn->addr.to.ss_family == AF_INET6)
2107 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2108
2109 /* it is important not to call the wakeup function directly but to
2110 * pass through task_wakeup(), because this one knows how to apply
2111 * priorities to tasks.
2112 */
2113 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
2114
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002115 hlua = hlua_gethlua(L);
2116 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002117
2118 /* inform the stream that we want to be notified whenever the
2119 * connection completes.
2120 */
2121 si_applet_cant_get(&socket->s->si[0]);
2122 si_applet_cant_put(&socket->s->si[0]);
2123
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002124 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2125 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002126 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002127
2128 return 0;
2129}
2130
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002131#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002132__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2133{
2134 struct hlua_socket *socket;
2135
2136 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2137 socket = MAY_LJMP(hlua_checksocket(L, 1));
2138 socket->s->target = &socket_ssl.obj_type;
2139 return MAY_LJMP(hlua_socket_connect(L));
2140}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002141#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002142
2143__LJMP static int hlua_socket_setoption(struct lua_State *L)
2144{
2145 return 0;
2146}
2147
2148__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2149{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002150 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002151 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002152
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002153 MAY_LJMP(check_args(L, 2, "settimeout"));
2154
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002155 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002156 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002157
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002158 socket->s->req.rto = tmout;
2159 socket->s->req.wto = tmout;
2160 socket->s->res.rto = tmout;
2161 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002162
2163 return 0;
2164}
2165
2166__LJMP static int hlua_socket_new(lua_State *L)
2167{
2168 struct hlua_socket *socket;
2169 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002170 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002171 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002172 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002173
2174 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002175 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002176 hlua_pusherror(L, "socket: full stack");
2177 goto out_fail_conf;
2178 }
2179
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002180 /* Create the object: obj[0] = userdata. */
2181 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002183 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002184 memset(socket, 0, sizeof(*socket));
2185
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002186 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002187 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002188 hlua_pusherror(L, "socket: uninitialized pools.");
2189 goto out_fail_conf;
2190 }
2191
Willy Tarreau87b09662015-04-03 00:22:06 +02002192 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002193 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2194 lua_setmetatable(L, -2);
2195
Willy Tarreaud420a972015-04-06 00:39:18 +02002196 /* Create the applet context */
2197 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002198 if (!appctx) {
2199 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002200 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002201 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002202
Willy Tarreaud420a972015-04-06 00:39:18 +02002203 appctx->ctx.hlua.socket = socket;
2204 appctx->ctx.hlua.connected = 0;
2205 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2206 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002207
Willy Tarreaud420a972015-04-06 00:39:18 +02002208 /* Now create a session, task and stream for this applet */
2209 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2210 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002211 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002212 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002213 }
2214
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002215 task = task_new();
2216 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002217 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002218 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002219 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002220 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002221
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002222 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002223 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002224 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002225 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002226 }
2227
Willy Tarreaud420a972015-04-06 00:39:18 +02002228 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002229 socket->s = strm;
2230 strm->hlua.T = NULL;
2231 strm->hlua.Tref = LUA_REFNIL;
2232 strm->hlua.Mref = LUA_REFNIL;
2233 strm->hlua.nargs = 0;
2234 strm->hlua.flags = 0;
2235 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002236
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002237 /* Configure "right" stream interface. this "si" is used to connect
2238 * and retrieve data from the server. The connection is initialized
2239 * with the "struct server".
2240 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002241 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002242
2243 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002244 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2245 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002246
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002247 /* Update statistics counters. */
2248 socket_proxy.feconn++; /* beconn will be increased later */
2249 jobs++;
2250 totalconn++;
2251
2252 /* Return yield waiting for connection. */
2253 return 1;
2254
Willy Tarreaud420a972015-04-06 00:39:18 +02002255 out_fail_stream:
2256 task_free(task);
2257 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002258 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002259 out_fail_sess:
2260 appctx_free(appctx);
2261 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002262 WILL_LJMP(lua_error(L));
2263 return 0;
2264}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002265
2266/*
2267 *
2268 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002269 * Class Channel
2270 *
2271 *
2272 */
2273
2274/* Returns the struct hlua_channel join to the class channel in the
2275 * stack entry "ud" or throws an argument error.
2276 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002277__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002278{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002279 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002280}
2281
Willy Tarreau47860ed2015-03-10 14:07:50 +01002282/* Pushes the channel onto the top of the stack. If the stask does not have a
2283 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002284 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002285static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002286{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002287 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002288 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002289 return 0;
2290
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002291 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002292 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002293 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002294
2295 /* Pop a class sesison metatable and affect it to the userdata. */
2296 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2297 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002298 return 1;
2299}
2300
2301/* Duplicate all the data present in the input channel and put it
2302 * in a string LUA variables. Returns -1 and push a nil value in
2303 * the stack if the channel is closed and all the data are consumed,
2304 * returns 0 if no data are available, otherwise it returns the length
2305 * of the builded string.
2306 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002307static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002308{
2309 char *blk1;
2310 char *blk2;
2311 int len1;
2312 int len2;
2313 int ret;
2314 luaL_Buffer b;
2315
Willy Tarreau47860ed2015-03-10 14:07:50 +01002316 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002317 if (unlikely(ret == 0))
2318 return 0;
2319
2320 if (unlikely(ret < 0)) {
2321 lua_pushnil(L);
2322 return -1;
2323 }
2324
2325 luaL_buffinit(L, &b);
2326 luaL_addlstring(&b, blk1, len1);
2327 if (unlikely(ret == 2))
2328 luaL_addlstring(&b, blk2, len2);
2329 luaL_pushresult(&b);
2330
2331 if (unlikely(ret == 2))
2332 return len1 + len2;
2333 return len1;
2334}
2335
2336/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2337 * a yield. This function keep the data in the buffer.
2338 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002339__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002340{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002341 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002342
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002343 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2344
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002345 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002346 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002347 return 1;
2348}
2349
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002350/* Check arguments for the function "hlua_channel_dup_yield". */
2351__LJMP static int hlua_channel_dup(lua_State *L)
2352{
2353 MAY_LJMP(check_args(L, 1, "dup"));
2354 MAY_LJMP(hlua_checkchannel(L, 1));
2355 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2356}
2357
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002358/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2359 * a yield. This function consumes the data in the buffer. It returns
2360 * a string containing the data or a nil pointer if no data are available
2361 * and the channel is closed.
2362 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002363__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002364{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002365 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002366 int ret;
2367
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002368 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002369
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002370 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002371 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002372 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002373
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002374 if (unlikely(ret == -1))
2375 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002376
Willy Tarreau47860ed2015-03-10 14:07:50 +01002377 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002378 return 1;
2379}
2380
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002381/* Check arguments for the fucntion "hlua_channel_get_yield". */
2382__LJMP static int hlua_channel_get(lua_State *L)
2383{
2384 MAY_LJMP(check_args(L, 1, "get"));
2385 MAY_LJMP(hlua_checkchannel(L, 1));
2386 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2387}
2388
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002389/* This functions consumes and returns one line. If the channel is closed,
2390 * and the last data does not contains a final '\n', the data are returned
2391 * without the final '\n'. When no more data are avalaible, it returns nil
2392 * value.
2393 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002394__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002395{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002396 char *blk1;
2397 char *blk2;
2398 int len1;
2399 int len2;
2400 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002401 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002402 int ret;
2403 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002404
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002405 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2406
Willy Tarreau47860ed2015-03-10 14:07:50 +01002407 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002408 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002409 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002410
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002411 if (ret == -1) {
2412 lua_pushnil(L);
2413 return 1;
2414 }
2415
2416 luaL_buffinit(L, &b);
2417 luaL_addlstring(&b, blk1, len1);
2418 len = len1;
2419 if (unlikely(ret == 2)) {
2420 luaL_addlstring(&b, blk2, len2);
2421 len += len2;
2422 }
2423 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002424 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002425 return 1;
2426}
2427
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002428/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2429__LJMP static int hlua_channel_getline(lua_State *L)
2430{
2431 MAY_LJMP(check_args(L, 1, "getline"));
2432 MAY_LJMP(hlua_checkchannel(L, 1));
2433 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2434}
2435
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002436/* This function takes a string as input, and append it at the
2437 * input side of channel. If the data is too big, but a space
2438 * is probably available after sending some data, the function
2439 * yield. If the data is bigger than the buffer, or if the
2440 * channel is closed, it returns -1. otherwise, it returns the
2441 * amount of data writed.
2442 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002443__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002444{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002445 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002446 size_t len;
2447 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2448 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2449 int ret;
2450 int max;
2451
Willy Tarreau47860ed2015-03-10 14:07:50 +01002452 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002453 if (max > len - l)
2454 max = len - l;
2455
Willy Tarreau47860ed2015-03-10 14:07:50 +01002456 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002457 if (ret == -2 || ret == -3) {
2458 lua_pushinteger(L, -1);
2459 return 1;
2460 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002461 if (ret == -1) {
2462 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002463 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002464 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002465 l += ret;
2466 lua_pop(L, 1);
2467 lua_pushinteger(L, l);
2468
Willy Tarreau47860ed2015-03-10 14:07:50 +01002469 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2470 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002471 /* There are no space avalaible, and the output buffer is empty.
2472 * in this case, we cannot add more data, so we cannot yield,
2473 * we return the amount of copyied data.
2474 */
2475 return 1;
2476 }
2477 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002478 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002479 return 1;
2480}
2481
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002482/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002483 * of the writed string, or -1 if the channel is closed or if the
2484 * buffer size is too little for the data.
2485 */
2486__LJMP static int hlua_channel_append(lua_State *L)
2487{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002488 size_t len;
2489
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002490 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002491 MAY_LJMP(hlua_checkchannel(L, 1));
2492 MAY_LJMP(luaL_checklstring(L, 2, &len));
2493 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002494 lua_pushinteger(L, 0);
2495
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002496 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002497}
2498
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002499/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002500 * his process by cleaning the buffer. The result is a replacement
2501 * of the current data. It returns the length of the writed string,
2502 * or -1 if the channel is closed or if the buffer size is too
2503 * little for the data.
2504 */
2505__LJMP static int hlua_channel_set(lua_State *L)
2506{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002507 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002508
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002509 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002510 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002511 lua_pushinteger(L, 0);
2512
Willy Tarreau47860ed2015-03-10 14:07:50 +01002513 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002514
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002515 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002516}
2517
2518/* Append data in the output side of the buffer. This data is immediatly
2519 * sent. The fcuntion returns the ammount of data writed. If the buffer
2520 * cannot contains the data, the function yield. The function returns -1
2521 * if the channel is closed.
2522 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002523__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002524{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002525 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002526 size_t len;
2527 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2528 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2529 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002530 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002531
Willy Tarreau47860ed2015-03-10 14:07:50 +01002532 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002533 lua_pushinteger(L, -1);
2534 return 1;
2535 }
2536
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002537 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2538 * the request buffer if its not required.
2539 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002540 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002541 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002542 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002543 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002544 }
2545 }
2546
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002547 /* the writed data will be immediatly sent, so we can check
2548 * the avalaible space without taking in account the reserve.
2549 * The reserve is guaranted for the processing of incoming
2550 * data, because the buffer will be flushed.
2551 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002552 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002553
2554 /* If there are no space avalaible, and the output buffer is empty.
2555 * in this case, we cannot add more data, so we cannot yield,
2556 * we return the amount of copyied data.
2557 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002558 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002559 return 1;
2560
2561 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002562 if (max > len - l)
2563 max = len - l;
2564
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002565 /* The buffer avalaible size may be not contiguous. This test
2566 * detects a non contiguous buffer and realign it.
2567 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002568 if (bi_space_for_replace(chn->buf) < max)
2569 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002570
2571 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002572 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002573
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002574 /* buffer replace considers that the input part is filled.
2575 * so, I must forward these new data in the output part.
2576 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002577 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002578
2579 l += max;
2580 lua_pop(L, 1);
2581 lua_pushinteger(L, l);
2582
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002583 /* If there are no space avalaible, and the output buffer is empty.
2584 * in this case, we cannot add more data, so we cannot yield,
2585 * we return the amount of copyied data.
2586 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002587 max = chn->buf->size - buffer_len(chn->buf);
2588 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002589 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002590
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002591 if (l < len) {
2592 /* If we are waiting for space in the response buffer, we
2593 * must set the flag WAKERESWR. This flag required the task
2594 * wake up if any activity is detected on the response buffer.
2595 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002596 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002597 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002598 else
2599 HLUA_SET_WAKEREQWR(hlua);
2600 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002601 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002602
2603 return 1;
2604}
2605
2606/* Just a wraper of "_hlua_channel_send". This wrapper permits
2607 * yield the LUA process, and resume it without checking the
2608 * input arguments.
2609 */
2610__LJMP static int hlua_channel_send(lua_State *L)
2611{
2612 MAY_LJMP(check_args(L, 2, "send"));
2613 lua_pushinteger(L, 0);
2614
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002615 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002616}
2617
2618/* This function forward and amount of butes. The data pass from
2619 * the input side of the buffer to the output side, and can be
2620 * forwarded. This function never fails.
2621 *
2622 * The Lua function takes an amount of bytes to be forwarded in
2623 * imput. It returns the number of bytes forwarded.
2624 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002625__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002626{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002627 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002628 int len;
2629 int l;
2630 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002631 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002632
2633 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2634 len = MAY_LJMP(luaL_checkinteger(L, 2));
2635 l = MAY_LJMP(luaL_checkinteger(L, -1));
2636
2637 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002638 if (max > chn->buf->i)
2639 max = chn->buf->i;
2640 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002641 l += max;
2642
2643 lua_pop(L, 1);
2644 lua_pushinteger(L, l);
2645
2646 /* Check if it miss bytes to forward. */
2647 if (l < len) {
2648 /* The the input channel or the output channel are closed, we
2649 * must return the amount of data forwarded.
2650 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002651 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002652 return 1;
2653
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002654 /* If we are waiting for space data in the response buffer, we
2655 * must set the flag WAKERESWR. This flag required the task
2656 * wake up if any activity is detected on the response buffer.
2657 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002658 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002659 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002660 else
2661 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002662
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002663 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002664 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002665 }
2666
2667 return 1;
2668}
2669
2670/* Just check the input and prepare the stack for the previous
2671 * function "hlua_channel_forward_yield"
2672 */
2673__LJMP static int hlua_channel_forward(lua_State *L)
2674{
2675 MAY_LJMP(check_args(L, 2, "forward"));
2676 MAY_LJMP(hlua_checkchannel(L, 1));
2677 MAY_LJMP(luaL_checkinteger(L, 2));
2678
2679 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002680 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002681}
2682
2683/* Just returns the number of bytes available in the input
2684 * side of the buffer. This function never fails.
2685 */
2686__LJMP static int hlua_channel_get_in_len(lua_State *L)
2687{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002688 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002689
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002690 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002691 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002692 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002693 return 1;
2694}
2695
2696/* Just returns the number of bytes available in the output
2697 * side of the buffer. This function never fails.
2698 */
2699__LJMP static int hlua_channel_get_out_len(lua_State *L)
2700{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002701 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002702
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002703 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002704 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002705 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002706 return 1;
2707}
2708
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002709/*
2710 *
2711 *
2712 * Class Fetches
2713 *
2714 *
2715 */
2716
2717/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002718 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002719 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002720__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002721{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002722 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002723}
2724
2725/* This function creates and push in the stack a fetch object according
2726 * with a current TXN.
2727 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002728static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002729{
Willy Tarreau7073c472015-04-06 11:15:40 +02002730 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002731
2732 /* Check stack size. */
2733 if (!lua_checkstack(L, 3))
2734 return 0;
2735
2736 /* Create the object: obj[0] = userdata.
2737 * Note that the base of the Fetches object is the
2738 * transaction object.
2739 */
2740 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002741 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002742 lua_rawseti(L, -2, 0);
2743
Willy Tarreau7073c472015-04-06 11:15:40 +02002744 hsmp->s = txn->s;
2745 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002746 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002747
2748 /* Pop a class sesison metatable and affect it to the userdata. */
2749 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2750 lua_setmetatable(L, -2);
2751
2752 return 1;
2753}
2754
2755/* This function is an LUA binding. It is called with each sample-fetch.
2756 * It uses closure argument to store the associated sample-fetch. It
2757 * returns only one argument or throws an error. An error is thrown
2758 * only if an error is encountered during the argument parsing. If
2759 * the "sample-fetch" function fails, nil is returned.
2760 */
2761__LJMP static int hlua_run_sample_fetch(lua_State *L)
2762{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002763 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002764 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002765 struct arg args[ARGM_NBARGS + 1];
2766 int i;
2767 struct sample smp;
2768
2769 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002770 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002771
2772 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002773 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002774
2775 /* Get extra arguments. */
2776 for (i = 0; i < lua_gettop(L) - 1; i++) {
2777 if (i >= ARGM_NBARGS)
2778 break;
2779 hlua_lua2arg(L, i + 2, &args[i]);
2780 }
2781 args[i].type = ARGT_STOP;
2782
2783 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002784 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002785
2786 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002787 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002788 lua_pushfstring(L, "error in arguments");
2789 WILL_LJMP(lua_error(L));
2790 }
2791
2792 /* Initialise the sample. */
2793 memset(&smp, 0, sizeof(smp));
2794
2795 /* Run the sample fetch process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02002796 smp.px = hsmp->p;
2797 smp.sess = hsmp->s->sess;
2798 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002799 smp.opt = 0;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02002800 if (!f->process(args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002801 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002802 lua_pushstring(L, "");
2803 else
2804 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002805 return 1;
2806 }
2807
2808 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002809 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002810 hlua_smp2lua_str(L, &smp);
2811 else
2812 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002813 return 1;
2814}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002815
2816/*
2817 *
2818 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002819 * Class Converters
2820 *
2821 *
2822 */
2823
2824/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002825 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002826 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002827__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002828{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002829 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002830}
2831
2832/* This function creates and push in the stack a Converters object
2833 * according with a current TXN.
2834 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002835static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002836{
Willy Tarreau7073c472015-04-06 11:15:40 +02002837 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002838
2839 /* Check stack size. */
2840 if (!lua_checkstack(L, 3))
2841 return 0;
2842
2843 /* Create the object: obj[0] = userdata.
2844 * Note that the base of the Converters object is the
2845 * same than the TXN object.
2846 */
2847 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002848 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002849 lua_rawseti(L, -2, 0);
2850
Willy Tarreau7073c472015-04-06 11:15:40 +02002851 hsmp->s = txn->s;
2852 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002853 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002854
Willy Tarreau87b09662015-04-03 00:22:06 +02002855 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002856 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2857 lua_setmetatable(L, -2);
2858
2859 return 1;
2860}
2861
2862/* This function is an LUA binding. It is called with each converter.
2863 * It uses closure argument to store the associated converter. It
2864 * returns only one argument or throws an error. An error is thrown
2865 * only if an error is encountered during the argument parsing. If
2866 * the converter function function fails, nil is returned.
2867 */
2868__LJMP static int hlua_run_sample_conv(lua_State *L)
2869{
Willy Tarreauda5f1082015-04-06 11:17:13 +02002870 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002871 struct sample_conv *conv;
2872 struct arg args[ARGM_NBARGS + 1];
2873 int i;
2874 struct sample smp;
2875
2876 /* Get closure arguments. */
2877 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2878
2879 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002880 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002881
2882 /* Get extra arguments. */
2883 for (i = 0; i < lua_gettop(L) - 2; i++) {
2884 if (i >= ARGM_NBARGS)
2885 break;
2886 hlua_lua2arg(L, i + 3, &args[i]);
2887 }
2888 args[i].type = ARGT_STOP;
2889
2890 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002891 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002892
2893 /* Run the special args checker. */
2894 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2895 hlua_pusherror(L, "error in arguments");
2896 WILL_LJMP(lua_error(L));
2897 }
2898
2899 /* Initialise the sample. */
2900 if (!hlua_lua2smp(L, 2, &smp)) {
2901 hlua_pusherror(L, "error in the input argument");
2902 WILL_LJMP(lua_error(L));
2903 }
2904
2905 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002906 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002907 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002908 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002909 WILL_LJMP(lua_error(L));
2910 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002911 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
2912 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002913 hlua_pusherror(L, "error during the input argument casting");
2914 WILL_LJMP(lua_error(L));
2915 }
2916
2917 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02002918 smp.px = hsmp->p;
2919 smp.sess = hsmp->s->sess;
2920 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002921 smp.opt = 0;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02002922 if (!conv->process(args, &smp, conv->private)) {
Willy Tarreauda5f1082015-04-06 11:17:13 +02002923 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002924 lua_pushstring(L, "");
2925 else
Willy Tarreaua678b432015-08-28 10:14:59 +02002926 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002927 return 1;
2928 }
2929
2930 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002931 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002932 hlua_smp2lua_str(L, &smp);
2933 else
2934 hlua_smp2lua(L, &smp);
Willy Tarreaua678b432015-08-28 10:14:59 +02002935 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002936}
2937
2938/*
2939 *
2940 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002941 * Class HTTP
2942 *
2943 *
2944 */
2945
2946/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002947 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002948 */
2949__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
2950{
2951 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
2952}
2953
2954/* This function creates and push in the stack a HTTP object
2955 * according with a current TXN.
2956 */
2957static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
2958{
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002959 struct hlua_txn *htxn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002960
2961 /* Check stack size. */
2962 if (!lua_checkstack(L, 3))
2963 return 0;
2964
2965 /* Create the object: obj[0] = userdata.
2966 * Note that the base of the Converters object is the
2967 * same than the TXN object.
2968 */
2969 lua_newtable(L);
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002970 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002971 lua_rawseti(L, -2, 0);
2972
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002973 htxn->s = txn->s;
2974 htxn->p = txn->p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002975
Willy Tarreau87b09662015-04-03 00:22:06 +02002976 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002977 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
2978 lua_setmetatable(L, -2);
2979
2980 return 1;
2981}
2982
2983/* This function creates ans returns an array of HTTP headers.
2984 * This function does not fails. It is used as wrapper with the
2985 * 2 following functions.
2986 */
2987__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
2988{
2989 const char *cur_ptr, *cur_next, *p;
2990 int old_idx, cur_idx;
2991 struct hdr_idx_elem *cur_hdr;
2992 const char *hn, *hv;
2993 int hnl, hvl;
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01002994 int type;
2995 const char *in;
2996 char *out;
2997 int len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002998
2999 /* Create the table. */
3000 lua_newtable(L);
3001
Willy Tarreaueee5b512015-04-03 23:46:31 +02003002 if (!htxn->s->txn)
3003 return 1;
3004
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003005 /* Build array of headers. */
3006 old_idx = 0;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003007 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003008
3009 while (1) {
Willy Tarreaueee5b512015-04-03 23:46:31 +02003010 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003011 if (!cur_idx)
3012 break;
3013 old_idx = cur_idx;
3014
Willy Tarreaueee5b512015-04-03 23:46:31 +02003015 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003016 cur_ptr = cur_next;
3017 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
3018
3019 /* Now we have one full header at cur_ptr of len cur_hdr->len,
3020 * and the next header starts at cur_next. We'll check
3021 * this header in the list as well as against the default
3022 * rule.
3023 */
3024
3025 /* look for ': *'. */
3026 hn = cur_ptr;
3027 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
3028 if (p >= cur_ptr+cur_hdr->len)
3029 continue;
3030 hnl = p - hn;
3031 p++;
3032 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3033 p++;
3034 if (p >= cur_ptr+cur_hdr->len)
3035 continue;
3036 hv = p;
3037 hvl = cur_ptr+cur_hdr->len-p;
3038
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003039 /* Lowercase the key. Don't check the size of trash, it have
3040 * the size of one buffer and the input data contains in one
3041 * buffer.
3042 */
3043 out = trash.str;
3044 for (in=hn; in<hn+hnl; in++, out++)
3045 *out = tolower(*in);
3046 *out = '\0';
3047
3048 /* Check for existing entry:
3049 * assume that the table is on the top of the stack, and
3050 * push the key in the stack, the function lua_gettable()
3051 * perform the lookup.
3052 */
3053 lua_pushlstring(L, trash.str, hnl);
3054 lua_gettable(L, -2);
3055 type = lua_type(L, -1);
3056
3057 switch (type) {
3058 case LUA_TNIL:
3059 /* Table not found, create it. */
3060 lua_pop(L, 1); /* remove the nil value. */
3061 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
3062 lua_newtable(L); /* create and push empty table. */
3063 lua_pushlstring(L, hv, hvl); /* push header value. */
3064 lua_rawseti(L, -2, 0); /* index header value (pop it). */
3065 lua_rawset(L, -3); /* index new table with header name (pop the values). */
3066 break;
3067
3068 case LUA_TTABLE:
3069 /* Entry found: push the value in the table. */
3070 len = lua_rawlen(L, -1);
3071 lua_pushlstring(L, hv, hvl); /* push header value. */
3072 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
3073 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
3074 break;
3075
3076 default:
3077 /* Other cases are errors. */
3078 hlua_pusherror(L, "internal error during the parsing of headers.");
3079 WILL_LJMP(lua_error(L));
3080 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003081 }
3082
3083 return 1;
3084}
3085
3086__LJMP static int hlua_http_req_get_headers(lua_State *L)
3087{
3088 struct hlua_txn *htxn;
3089
3090 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3091 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3092
Willy Tarreaueee5b512015-04-03 23:46:31 +02003093 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003094}
3095
3096__LJMP static int hlua_http_res_get_headers(lua_State *L)
3097{
3098 struct hlua_txn *htxn;
3099
3100 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3101 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3102
Willy Tarreaueee5b512015-04-03 23:46:31 +02003103 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003104}
3105
3106/* This function replace full header, or just a value in
3107 * the request or in the response. It is a wrapper fir the
3108 * 4 following functions.
3109 */
3110__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3111 struct http_msg *msg, int action)
3112{
3113 size_t name_len;
3114 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3115 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3116 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3117 struct my_regex re;
3118
3119 if (!regex_comp(reg, &re, 1, 1, NULL))
3120 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3121
3122 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3123 regex_free(&re);
3124 return 0;
3125}
3126
3127__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3128{
3129 struct hlua_txn *htxn;
3130
3131 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3132 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3133
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003134 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003135}
3136
3137__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3138{
3139 struct hlua_txn *htxn;
3140
3141 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3142 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3143
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003144 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003145}
3146
3147__LJMP static int hlua_http_req_rep_val(lua_State *L)
3148{
3149 struct hlua_txn *htxn;
3150
3151 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3152 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3153
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003154 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003155}
3156
3157__LJMP static int hlua_http_res_rep_val(lua_State *L)
3158{
3159 struct hlua_txn *htxn;
3160
3161 MAY_LJMP(check_args(L, 4, "res_rep_val"));
3162 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3163
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003164 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003165}
3166
3167/* This function deletes all the occurences of an header.
3168 * It is a wrapper for the 2 following functions.
3169 */
3170__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3171{
3172 size_t len;
3173 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3174 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003175 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003176
3177 ctx.idx = 0;
3178 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3179 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3180 return 0;
3181}
3182
3183__LJMP static int hlua_http_req_del_hdr(lua_State *L)
3184{
3185 struct hlua_txn *htxn;
3186
3187 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3188 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3189
Willy Tarreaueee5b512015-04-03 23:46:31 +02003190 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003191}
3192
3193__LJMP static int hlua_http_res_del_hdr(lua_State *L)
3194{
3195 struct hlua_txn *htxn;
3196
3197 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3198 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3199
Willy Tarreaueee5b512015-04-03 23:46:31 +02003200 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003201}
3202
3203/* This function adds an header. It is a wrapper used by
3204 * the 2 following functions.
3205 */
3206__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3207{
3208 size_t name_len;
3209 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3210 size_t value_len;
3211 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3212 char *p;
3213
3214 /* Check length. */
3215 trash.len = value_len + name_len + 2;
3216 if (trash.len > trash.size)
3217 return 0;
3218
3219 /* Creates the header string. */
3220 p = trash.str;
3221 memcpy(p, name, name_len);
3222 p += name_len;
3223 *p = ':';
3224 p++;
3225 *p = ' ';
3226 p++;
3227 memcpy(p, value, value_len);
3228
Willy Tarreaueee5b512015-04-03 23:46:31 +02003229 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003230 trash.str, trash.len) != 0);
3231
3232 return 0;
3233}
3234
3235__LJMP static int hlua_http_req_add_hdr(lua_State *L)
3236{
3237 struct hlua_txn *htxn;
3238
3239 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3240 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3241
Willy Tarreaueee5b512015-04-03 23:46:31 +02003242 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003243}
3244
3245__LJMP static int hlua_http_res_add_hdr(lua_State *L)
3246{
3247 struct hlua_txn *htxn;
3248
3249 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3250 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3251
Willy Tarreaueee5b512015-04-03 23:46:31 +02003252 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003253}
3254
3255static int hlua_http_req_set_hdr(lua_State *L)
3256{
3257 struct hlua_txn *htxn;
3258
3259 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3260 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3261
Willy Tarreaueee5b512015-04-03 23:46:31 +02003262 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3263 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003264}
3265
3266static int hlua_http_res_set_hdr(lua_State *L)
3267{
3268 struct hlua_txn *htxn;
3269
3270 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3271 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3272
Willy Tarreaueee5b512015-04-03 23:46:31 +02003273 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3274 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003275}
3276
3277/* This function set the method. */
3278static int hlua_http_req_set_meth(lua_State *L)
3279{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003280 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003281 size_t name_len;
3282 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003283
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003284 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003285 return 1;
3286}
3287
3288/* This function set the method. */
3289static int hlua_http_req_set_path(lua_State *L)
3290{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003291 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003292 size_t name_len;
3293 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003294 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003295 return 1;
3296}
3297
3298/* This function set the query-string. */
3299static int hlua_http_req_set_query(lua_State *L)
3300{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003301 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003302 size_t name_len;
3303 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003304
3305 /* Check length. */
3306 if (name_len > trash.size - 1) {
3307 lua_pushboolean(L, 0);
3308 return 1;
3309 }
3310
3311 /* Add the mark question as prefix. */
3312 chunk_reset(&trash);
3313 trash.str[trash.len++] = '?';
3314 memcpy(trash.str + trash.len, name, name_len);
3315 trash.len += name_len;
3316
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003317 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003318 return 1;
3319}
3320
3321/* This function set the uri. */
3322static int hlua_http_req_set_uri(lua_State *L)
3323{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003324 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003325 size_t name_len;
3326 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003327
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003328 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003329 return 1;
3330}
3331
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02003332/* This function set the response code. */
3333static int hlua_http_res_set_status(lua_State *L)
3334{
3335 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3336 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
3337
3338 http_set_status(code, htxn->s);
3339 return 0;
3340}
3341
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003342/*
3343 *
3344 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003345 * Class TXN
3346 *
3347 *
3348 */
3349
3350/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003351 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003352 */
3353__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3354{
3355 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3356}
3357
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02003358__LJMP static int hlua_set_var(lua_State *L)
3359{
3360 struct hlua_txn *htxn;
3361 const char *name;
3362 size_t len;
3363 struct sample smp;
3364
3365 MAY_LJMP(check_args(L, 3, "set_var"));
3366
3367 /* It is useles to retrieve the stream, but this function
3368 * runs only in a stream context.
3369 */
3370 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3371 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3372
3373 /* Converts the third argument in a sample. */
3374 hlua_lua2smp(L, 3, &smp);
3375
3376 /* Store the sample in a variable. */
3377 vars_set_by_name(name, len, htxn->s, &smp);
3378 return 0;
3379}
3380
3381__LJMP static int hlua_get_var(lua_State *L)
3382{
3383 struct hlua_txn *htxn;
3384 const char *name;
3385 size_t len;
3386 struct sample smp;
3387
3388 MAY_LJMP(check_args(L, 2, "get_var"));
3389
3390 /* It is useles to retrieve the stream, but this function
3391 * runs only in a stream context.
3392 */
3393 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3394 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3395
3396 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
3397 lua_pushnil(L);
3398 return 1;
3399 }
3400
3401 return hlua_smp2lua(L, &smp);
3402}
3403
Willy Tarreau59551662015-03-10 14:23:13 +01003404__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003405{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003406 struct hlua *hlua;
3407
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003408 MAY_LJMP(check_args(L, 2, "set_priv"));
3409
Willy Tarreau87b09662015-04-03 00:22:06 +02003410 /* It is useles to retrieve the stream, but this function
3411 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003412 */
3413 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003414 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003415
3416 /* Remove previous value. */
3417 if (hlua->Mref != -1)
3418 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3419
3420 /* Get and store new value. */
3421 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3422 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3423
3424 return 0;
3425}
3426
Willy Tarreau59551662015-03-10 14:23:13 +01003427__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003428{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003429 struct hlua *hlua;
3430
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003431 MAY_LJMP(check_args(L, 1, "get_priv"));
3432
Willy Tarreau87b09662015-04-03 00:22:06 +02003433 /* It is useles to retrieve the stream, but this function
3434 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003435 */
3436 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003437 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003438
3439 /* Push configuration index in the stack. */
3440 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3441
3442 return 1;
3443}
3444
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003445/* Create stack entry containing a class TXN. This function
3446 * return 0 if the stack does not contains free slots,
3447 * otherwise it returns 1.
3448 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003449static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003450{
Willy Tarreaude491382015-04-06 11:04:28 +02003451 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003452
3453 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003454 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003455 return 0;
3456
3457 /* NOTE: The allocation never fails. The failure
3458 * throw an error, and the function never returns.
3459 * if the throw is not avalaible, the process is aborted.
3460 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003461 /* Create the object: obj[0] = userdata. */
3462 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02003463 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003464 lua_rawseti(L, -2, 0);
3465
Willy Tarreaude491382015-04-06 11:04:28 +02003466 htxn->s = s;
3467 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003468
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003469 /* Create the "f" field that contains a list of fetches. */
3470 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02003471 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003472 return 0;
3473 lua_settable(L, -3);
3474
3475 /* Create the "sf" field that contains a list of stringsafe fetches. */
3476 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02003477 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003478 return 0;
3479 lua_settable(L, -3);
3480
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003481 /* Create the "c" field that contains a list of converters. */
3482 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02003483 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003484 return 0;
3485 lua_settable(L, -3);
3486
3487 /* Create the "sc" field that contains a list of stringsafe converters. */
3488 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02003489 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003490 return 0;
3491 lua_settable(L, -3);
3492
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003493 /* Create the "req" field that contains the request channel object. */
3494 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003495 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003496 return 0;
3497 lua_settable(L, -3);
3498
3499 /* Create the "res" field that contains the response channel object. */
3500 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003501 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003502 return 0;
3503 lua_settable(L, -3);
3504
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003505 /* Creates the HTTP object is the current proxy allows http. */
3506 lua_pushstring(L, "http");
3507 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02003508 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003509 return 0;
3510 }
3511 else
3512 lua_pushnil(L);
3513 lua_settable(L, -3);
3514
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003515 /* Pop a class sesison metatable and affect it to the userdata. */
3516 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3517 lua_setmetatable(L, -2);
3518
3519 return 1;
3520}
3521
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003522__LJMP static int hlua_txn_deflog(lua_State *L)
3523{
3524 const char *msg;
3525 struct hlua_txn *htxn;
3526
3527 MAY_LJMP(check_args(L, 2, "deflog"));
3528 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3529 msg = MAY_LJMP(luaL_checkstring(L, 2));
3530
3531 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3532 return 0;
3533}
3534
3535__LJMP static int hlua_txn_log(lua_State *L)
3536{
3537 int level;
3538 const char *msg;
3539 struct hlua_txn *htxn;
3540
3541 MAY_LJMP(check_args(L, 3, "log"));
3542 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3543 level = MAY_LJMP(luaL_checkinteger(L, 2));
3544 msg = MAY_LJMP(luaL_checkstring(L, 3));
3545
3546 if (level < 0 || level >= NB_LOG_LEVELS)
3547 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3548
3549 hlua_sendlog(htxn->s->be, level, msg);
3550 return 0;
3551}
3552
3553__LJMP static int hlua_txn_log_debug(lua_State *L)
3554{
3555 const char *msg;
3556 struct hlua_txn *htxn;
3557
3558 MAY_LJMP(check_args(L, 2, "Debug"));
3559 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3560 msg = MAY_LJMP(luaL_checkstring(L, 2));
3561 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3562 return 0;
3563}
3564
3565__LJMP static int hlua_txn_log_info(lua_State *L)
3566{
3567 const char *msg;
3568 struct hlua_txn *htxn;
3569
3570 MAY_LJMP(check_args(L, 2, "Info"));
3571 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3572 msg = MAY_LJMP(luaL_checkstring(L, 2));
3573 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3574 return 0;
3575}
3576
3577__LJMP static int hlua_txn_log_warning(lua_State *L)
3578{
3579 const char *msg;
3580 struct hlua_txn *htxn;
3581
3582 MAY_LJMP(check_args(L, 2, "Warning"));
3583 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3584 msg = MAY_LJMP(luaL_checkstring(L, 2));
3585 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3586 return 0;
3587}
3588
3589__LJMP static int hlua_txn_log_alert(lua_State *L)
3590{
3591 const char *msg;
3592 struct hlua_txn *htxn;
3593
3594 MAY_LJMP(check_args(L, 2, "Alert"));
3595 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3596 msg = MAY_LJMP(luaL_checkstring(L, 2));
3597 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3598 return 0;
3599}
3600
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003601__LJMP static int hlua_txn_set_loglevel(lua_State *L)
3602{
3603 struct hlua_txn *htxn;
3604 int ll;
3605
3606 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3607 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3608 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3609
3610 if (ll < 0 || ll > 7)
3611 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3612
3613 htxn->s->logs.level = ll;
3614 return 0;
3615}
3616
3617__LJMP static int hlua_txn_set_tos(lua_State *L)
3618{
3619 struct hlua_txn *htxn;
3620 struct connection *cli_conn;
3621 int tos;
3622
3623 MAY_LJMP(check_args(L, 2, "set_tos"));
3624 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3625 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3626
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003627 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003628 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3629
3630 return 0;
3631}
3632
3633__LJMP static int hlua_txn_set_mark(lua_State *L)
3634{
3635#ifdef SO_MARK
3636 struct hlua_txn *htxn;
3637 struct connection *cli_conn;
3638 int mark;
3639
3640 MAY_LJMP(check_args(L, 2, "set_mark"));
3641 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3642 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3643
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003644 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02003645 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003646#endif
3647 return 0;
3648}
3649
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003650/* This function is an Lua binding that send pending data
3651 * to the client, and close the stream interface.
3652 */
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02003653__LJMP static int hlua_txn_done(lua_State *L)
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003654{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003655 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01003656 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003657
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003658 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003659 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003660
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003661 ic = &htxn->s->req;
3662 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01003663
Willy Tarreau630ef452015-08-28 10:06:15 +02003664 if (htxn->s->txn) {
3665 /* HTTP mode, let's stay in sync with the stream */
3666 bi_fast_delete(ic->buf, htxn->s->txn->req.sov);
3667 htxn->s->txn->req.next -= htxn->s->txn->req.sov;
3668 htxn->s->txn->req.sov = 0;
3669 ic->analysers &= AN_REQ_HTTP_XFER_BODY;
3670 oc->analysers = AN_RES_HTTP_XFER_BODY;
3671 htxn->s->txn->req.msg_state = HTTP_MSG_CLOSED;
3672 htxn->s->txn->rsp.msg_state = HTTP_MSG_DONE;
3673
3674 /* Trim any possible response */
3675 oc->buf->i = 0;
3676 htxn->s->txn->rsp.next = htxn->s->txn->rsp.sov = 0;
3677
3678 /* Note that if we want to support keep-alive, we need
3679 * to bypass the close/shutr_now calls below, but that
3680 * may only be done if the HTTP request was already
3681 * processed and the connection header is known (ie
3682 * not during TCP rules).
3683 */
3684 }
3685
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003686 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01003687 channel_abort(ic);
3688 channel_auto_close(ic);
3689 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003690
3691 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01003692 channel_auto_read(oc);
3693 channel_auto_close(oc);
3694 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003695
Willy Tarreau0458b082015-08-28 09:40:04 +02003696 ic->analysers = 0;
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02003697
3698 WILL_LJMP(hlua_done(L));
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003699 return 0;
3700}
3701
3702__LJMP static int hlua_log(lua_State *L)
3703{
3704 int level;
3705 const char *msg;
3706
3707 MAY_LJMP(check_args(L, 2, "log"));
3708 level = MAY_LJMP(luaL_checkinteger(L, 1));
3709 msg = MAY_LJMP(luaL_checkstring(L, 2));
3710
3711 if (level < 0 || level >= NB_LOG_LEVELS)
3712 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3713
3714 hlua_sendlog(NULL, level, msg);
3715 return 0;
3716}
3717
3718__LJMP static int hlua_log_debug(lua_State *L)
3719{
3720 const char *msg;
3721
3722 MAY_LJMP(check_args(L, 1, "debug"));
3723 msg = MAY_LJMP(luaL_checkstring(L, 1));
3724 hlua_sendlog(NULL, LOG_DEBUG, msg);
3725 return 0;
3726}
3727
3728__LJMP static int hlua_log_info(lua_State *L)
3729{
3730 const char *msg;
3731
3732 MAY_LJMP(check_args(L, 1, "info"));
3733 msg = MAY_LJMP(luaL_checkstring(L, 1));
3734 hlua_sendlog(NULL, LOG_INFO, msg);
3735 return 0;
3736}
3737
3738__LJMP static int hlua_log_warning(lua_State *L)
3739{
3740 const char *msg;
3741
3742 MAY_LJMP(check_args(L, 1, "warning"));
3743 msg = MAY_LJMP(luaL_checkstring(L, 1));
3744 hlua_sendlog(NULL, LOG_WARNING, msg);
3745 return 0;
3746}
3747
3748__LJMP static int hlua_log_alert(lua_State *L)
3749{
3750 const char *msg;
3751
3752 MAY_LJMP(check_args(L, 1, "alert"));
3753 msg = MAY_LJMP(luaL_checkstring(L, 1));
3754 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003755 return 0;
3756}
3757
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003758__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003759{
3760 int wakeup_ms = lua_tointeger(L, -1);
3761 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003762 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003763 return 0;
3764}
3765
3766__LJMP static int hlua_sleep(lua_State *L)
3767{
3768 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003769 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003770
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003771 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003772
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003773 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003774 wakeup_ms = tick_add(now_ms, delay);
3775 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003776
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003777 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3778 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003779}
3780
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003781__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003782{
3783 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003784 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003785
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003786 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003787
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003788 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003789 wakeup_ms = tick_add(now_ms, delay);
3790 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003791
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003792 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3793 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003794}
3795
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003796/* This functionis an LUA binding. it permits to give back
3797 * the hand at the HAProxy scheduler. It is used when the
3798 * LUA processing consumes a lot of time.
3799 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003800__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003801{
3802 return 0;
3803}
3804
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003805__LJMP static int hlua_yield(lua_State *L)
3806{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003807 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3808 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003809}
3810
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003811/* This function change the nice of the currently executed
3812 * task. It is used set low or high priority at the current
3813 * task.
3814 */
Willy Tarreau59551662015-03-10 14:23:13 +01003815__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003816{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003817 struct hlua *hlua;
3818 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003819
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003820 MAY_LJMP(check_args(L, 1, "set_nice"));
3821 hlua = hlua_gethlua(L);
3822 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003823
3824 /* If he task is not set, I'm in a start mode. */
3825 if (!hlua || !hlua->task)
3826 return 0;
3827
3828 if (nice < -1024)
3829 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003830 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003831 nice = 1024;
3832
3833 hlua->task->nice = nice;
3834 return 0;
3835}
3836
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003837/* This function is used as a calback of a task. It is called by the
3838 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3839 * return an E_AGAIN signal, the emmiter of this signal must set a
3840 * signal to wake the task.
3841 */
3842static struct task *hlua_process_task(struct task *task)
3843{
3844 struct hlua *hlua = task->context;
3845 enum hlua_exec status;
3846
3847 /* We need to remove the task from the wait queue before executing
3848 * the Lua code because we don't know if it needs to wait for
3849 * another timer or not in the case of E_AGAIN.
3850 */
3851 task_delete(task);
3852
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003853 /* If it is the first call to the task, we must initialize the
3854 * execution timeouts.
3855 */
3856 if (!HLUA_IS_RUNNING(hlua))
Camilo Lopez685c0142015-08-02 19:07:28 -04003857 hlua->expire = tick_add_ifset(now_ms, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003858
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003859 /* Execute the Lua code. */
3860 status = hlua_ctx_resume(hlua, 1);
3861
3862 switch (status) {
3863 /* finished or yield */
3864 case HLUA_E_OK:
3865 hlua_ctx_destroy(hlua);
3866 task_delete(task);
3867 task_free(task);
3868 break;
3869
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003870 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3871 if (hlua->wake_time != TICK_ETERNITY)
3872 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003873 break;
3874
3875 /* finished with error. */
3876 case HLUA_E_ERRMSG:
3877 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3878 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3879 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3880 hlua_ctx_destroy(hlua);
3881 task_delete(task);
3882 task_free(task);
3883 break;
3884
3885 case HLUA_E_ERR:
3886 default:
3887 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3888 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3889 Alert("Lua task: unknown error.\n");
3890 hlua_ctx_destroy(hlua);
3891 task_delete(task);
3892 task_free(task);
3893 break;
3894 }
3895 return NULL;
3896}
3897
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003898/* This function is an LUA binding that register LUA function to be
3899 * executed after the HAProxy configuration parsing and before the
3900 * HAProxy scheduler starts. This function expect only one LUA
3901 * argument that is a function. This function returns nothing, but
3902 * throws if an error is encountered.
3903 */
3904__LJMP static int hlua_register_init(lua_State *L)
3905{
3906 struct hlua_init_function *init;
3907 int ref;
3908
3909 MAY_LJMP(check_args(L, 1, "register_init"));
3910
3911 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3912
3913 init = malloc(sizeof(*init));
3914 if (!init)
3915 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3916
3917 init->function_ref = ref;
3918 LIST_ADDQ(&hlua_init_functions, &init->l);
3919 return 0;
3920}
3921
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003922/* This functio is an LUA binding. It permits to register a task
3923 * executed in parallel of the main HAroxy activity. The task is
3924 * created and it is set in the HAProxy scheduler. It can be called
3925 * from the "init" section, "post init" or during the runtime.
3926 *
3927 * Lua prototype:
3928 *
3929 * <none> core.register_task(<function>)
3930 */
3931static int hlua_register_task(lua_State *L)
3932{
3933 struct hlua *hlua;
3934 struct task *task;
3935 int ref;
3936
3937 MAY_LJMP(check_args(L, 1, "register_task"));
3938
3939 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3940
3941 hlua = malloc(sizeof(*hlua));
3942 if (!hlua)
3943 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3944
3945 task = task_new();
3946 task->context = hlua;
3947 task->process = hlua_process_task;
3948
3949 if (!hlua_ctx_init(hlua, task))
3950 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3951
3952 /* Restore the function in the stack. */
3953 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3954 hlua->nargs = 0;
3955
3956 /* Schedule task. */
3957 task_schedule(task, now_ms);
3958
3959 return 0;
3960}
3961
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003962/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3963 * doesn't allow "yield" functions because the HAProxy engine cannot
3964 * resume converters.
3965 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003966static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003967{
3968 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003969 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003970
Willy Tarreau87b09662015-04-03 00:22:06 +02003971 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003972 * Lua context can be not initialized. This behavior
3973 * permits to save performances because a systematic
3974 * Lua initialization cause 5% performances loss.
3975 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003976 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
3977 send_log(stream->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003978 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3979 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3980 return 0;
3981 }
3982
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003983 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003984 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003985 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003986 if (!lua_checkstack(stream->hlua.T, 1)) {
3987 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003988 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3989 Alert("Lua converter '%s': full stack.\n", fcn->name);
3990 return 0;
3991 }
3992
3993 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003994 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003995
3996 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003997 if (!lua_checkstack(stream->hlua.T, 1)) {
3998 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003999 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4000 Alert("Lua converter '%s': full stack.\n", fcn->name);
4001 return 0;
4002 }
Willy Tarreau87b09662015-04-03 00:22:06 +02004003 hlua_smp2lua(stream->hlua.T, smp);
4004 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004005
4006 /* push keywords in the stack. */
4007 if (arg_p) {
4008 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02004009 if (!lua_checkstack(stream->hlua.T, 1)) {
4010 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004011 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4012 Alert("Lua converter '%s': full stack.\n", fcn->name);
4013 return 0;
4014 }
Willy Tarreau87b09662015-04-03 00:22:06 +02004015 hlua_arg2lua(stream->hlua.T, arg_p);
4016 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004017 }
4018 }
4019
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004020 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004021 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004022
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004023 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004024 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004025 }
4026
4027 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004028 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004029 /* finished. */
4030 case HLUA_E_OK:
4031 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004032 hlua_lua2smp(stream->hlua.T, -1, smp);
4033 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004034 return 1;
4035
4036 /* yield. */
4037 case HLUA_E_AGAIN:
Willy Tarreau87b09662015-04-03 00:22:06 +02004038 send_log(stream->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004039 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4040 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
4041 return 0;
4042
4043 /* finished with error. */
4044 case HLUA_E_ERRMSG:
4045 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004046 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 +01004047 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Willy Tarreau87b09662015-04-03 00:22:06 +02004048 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
4049 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004050 return 0;
4051
4052 case HLUA_E_ERR:
4053 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004054 send_log(stream->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004055 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4056 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
4057
4058 default:
4059 return 0;
4060 }
4061}
4062
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004063/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
4064 * doesn't allow "yield" functions because the HAProxy engine cannot
4065 * resume sample-fetches.
4066 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004067static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
4068 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004069{
4070 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004071 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004072
Willy Tarreau87b09662015-04-03 00:22:06 +02004073 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004074 * Lua context can be not initialized. This behavior
4075 * permits to save performances because a systematic
4076 * Lua initialization cause 5% performances loss.
4077 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004078 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
4079 send_log(stream->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004080 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4081 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
4082 return 0;
4083 }
4084
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004085 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004086 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004087 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004088 if (!lua_checkstack(stream->hlua.T, 2)) {
4089 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004090 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4091 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4092 return 0;
4093 }
4094
4095 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004096 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004097
4098 /* push arguments in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004099 if (!hlua_txn_new(stream->hlua.T, stream, smp->px)) {
4100 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004101 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4102 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4103 return 0;
4104 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004105 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004106
4107 /* push keywords in the stack. */
4108 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
4109 /* Check stack available size. */
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 if (!lua_checkstack(stream->hlua.T, 1)) {
4117 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004118 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4119 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4120 return 0;
4121 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004122 hlua_arg2lua(stream->hlua.T, arg_p);
4123 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004124 }
4125
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004126 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004127 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004128
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004129 /* Set the currently running flag. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004130 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004131 }
4132
4133 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004134 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004135 /* finished. */
4136 case HLUA_E_OK:
4137 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004138 hlua_lua2smp(stream->hlua.T, -1, smp);
4139 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004140
4141 /* Set the end of execution flag. */
4142 smp->flags &= ~SMP_F_MAY_CHANGE;
4143 return 1;
4144
4145 /* yield. */
4146 case HLUA_E_AGAIN:
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004147 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004148 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4149 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
4150 return 0;
4151
4152 /* finished with error. */
4153 case HLUA_E_ERRMSG:
4154 /* Display log. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004155 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 +01004156 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004157 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
4158 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004159 return 0;
4160
4161 case HLUA_E_ERR:
4162 /* Display log. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004163 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004164 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4165 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
4166
4167 default:
4168 return 0;
4169 }
4170}
4171
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004172/* This function is an LUA binding used for registering
4173 * "sample-conv" functions. It expects a converter name used
4174 * in the haproxy configuration file, and an LUA function.
4175 */
4176__LJMP static int hlua_register_converters(lua_State *L)
4177{
4178 struct sample_conv_kw_list *sck;
4179 const char *name;
4180 int ref;
4181 int len;
4182 struct hlua_function *fcn;
4183
4184 MAY_LJMP(check_args(L, 2, "register_converters"));
4185
4186 /* First argument : converter name. */
4187 name = MAY_LJMP(luaL_checkstring(L, 1));
4188
4189 /* Second argument : lua function. */
4190 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4191
4192 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004193 sck = malloc(sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004194 if (!sck)
4195 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4196 fcn = malloc(sizeof(*fcn));
4197 if (!fcn)
4198 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4199
4200 /* Fill fcn. */
4201 fcn->name = strdup(name);
4202 if (!fcn->name)
4203 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4204 fcn->function_ref = ref;
4205
4206 /* List head */
4207 sck->list.n = sck->list.p = NULL;
4208
4209 /* converter keyword. */
4210 len = strlen("lua.") + strlen(name) + 1;
4211 sck->kw[0].kw = malloc(len);
4212 if (!sck->kw[0].kw)
4213 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4214
4215 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4216 sck->kw[0].process = hlua_sample_conv_wrapper;
4217 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4218 sck->kw[0].val_args = NULL;
4219 sck->kw[0].in_type = SMP_T_STR;
4220 sck->kw[0].out_type = SMP_T_STR;
4221 sck->kw[0].private = fcn;
4222
4223 /* End of array. */
4224 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
4225
4226 /* Register this new converter */
4227 sample_register_convs(sck);
4228
4229 return 0;
4230}
4231
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004232/* This fucntion is an LUA binding used for registering
4233 * "sample-fetch" functions. It expects a converter name used
4234 * in the haproxy configuration file, and an LUA function.
4235 */
4236__LJMP static int hlua_register_fetches(lua_State *L)
4237{
4238 const char *name;
4239 int ref;
4240 int len;
4241 struct sample_fetch_kw_list *sfk;
4242 struct hlua_function *fcn;
4243
4244 MAY_LJMP(check_args(L, 2, "register_fetches"));
4245
4246 /* First argument : sample-fetch name. */
4247 name = MAY_LJMP(luaL_checkstring(L, 1));
4248
4249 /* Second argument : lua function. */
4250 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4251
4252 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004253 sfk = malloc(sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004254 if (!sfk)
4255 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4256 fcn = malloc(sizeof(*fcn));
4257 if (!fcn)
4258 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4259
4260 /* Fill fcn. */
4261 fcn->name = strdup(name);
4262 if (!fcn->name)
4263 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4264 fcn->function_ref = ref;
4265
4266 /* List head */
4267 sfk->list.n = sfk->list.p = NULL;
4268
4269 /* sample-fetch keyword. */
4270 len = strlen("lua.") + strlen(name) + 1;
4271 sfk->kw[0].kw = malloc(len);
4272 if (!sfk->kw[0].kw)
4273 return luaL_error(L, "lua out of memory error.");
4274
4275 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4276 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4277 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4278 sfk->kw[0].val_args = NULL;
4279 sfk->kw[0].out_type = SMP_T_STR;
4280 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4281 sfk->kw[0].val = 0;
4282 sfk->kw[0].private = fcn;
4283
4284 /* End of array. */
4285 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
4286
4287 /* Register this new fetch. */
4288 sample_register_fetches(sfk);
4289
4290 return 0;
4291}
4292
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004293/* This function is a wrapper to execute each LUA function declared
4294 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004295 * return ACT_RET_CONT if the processing is finished (with or without
4296 * error) and return ACT_RET_YIELD if the function must be called again
4297 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004298 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004299static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
4300 struct session *sess, struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004301{
4302 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004303 unsigned int analyzer;
4304
4305 switch (rule->from) {
4306 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; break;
4307 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; break;
4308 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; break;
4309 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; break;
4310 default:
4311 send_log(px, LOG_ERR, "Lua: internal error while execute action.");
4312 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4313 Alert("Lua: internal error while execute action.\n");
4314 return ACT_RET_CONT;
4315 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004316
Willy Tarreau87b09662015-04-03 00:22:06 +02004317 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004318 * Lua context can be not initialized. This behavior
4319 * permits to save performances because a systematic
4320 * Lua initialization cause 5% performances loss.
4321 */
4322 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004323 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.",
4324 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004325 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004326 Alert("Lua action '%s': can't initialize Lua context.\n",
4327 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004328 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004329 }
4330
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004331 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004332 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004333 /* Check stack available size. */
4334 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004335 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4336 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004337 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004338 Alert("Lua function '%s': full stack.\n",
4339 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004340 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004341 }
4342
4343 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004344 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004345
Willy Tarreau87b09662015-04-03 00:22:06 +02004346 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004347 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004348 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4349 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004350 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004351 Alert("Lua function '%s': full stack.\n",
4352 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004353 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004354 }
4355 s->hlua.nargs = 1;
4356
4357 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004358 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004359 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004360 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4361 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004362 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004363 Alert("Lua function '%s': full stack.\n",
4364 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004365 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004366 }
4367 lua_pushstring(s->hlua.T, *arg);
4368 s->hlua.nargs++;
4369 }
4370
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004371 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004372 s->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004373
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004374 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004375 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004376 }
4377
4378 /* Execute the function. */
4379 switch (hlua_ctx_resume(&s->hlua, 1)) {
4380 /* finished. */
4381 case HLUA_E_OK:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004382 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004383
4384 /* yield. */
4385 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004386 /* Set timeout in the required channel. */
4387 if (s->hlua.wake_time != TICK_ETERNITY) {
4388 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004389 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004390 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004391 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004392 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004393 /* Some actions can be wake up when a "write" event
4394 * is detected on a response channel. This is useful
4395 * only for actions targetted on the requests.
4396 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004397 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004398 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01004399 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004400 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004401 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004402 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004403 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004404 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004405
4406 /* finished with error. */
4407 case HLUA_E_ERRMSG:
4408 /* Display log. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004409 send_log(px, LOG_ERR, "Lua function '%s': %s.",
4410 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004411 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004412 Alert("Lua function '%s': %s.\n",
4413 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004414 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004415 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004416
4417 case HLUA_E_ERR:
4418 /* Display log. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004419 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.",
4420 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004421 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004422 Alert("Lua function '%s' return an unknown error.\n",
4423 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004424
4425 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004426 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004427 }
4428}
4429
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004430/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
4431 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004432 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004433static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4434 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004435{
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004436 /* Memory for the rule. */
4437 rule->arg.hlua_rule = malloc(sizeof(*rule->arg.hlua_rule));
4438 if (!rule->arg.hlua_rule) {
4439 memprintf(err, "out of memory error");
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 /* The requiered arg is a function name. */
4444 if (!args[*cur_arg]) {
4445 memprintf(err, "expect Lua function name");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004446 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004447 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004448
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004449 /* Lookup for the symbol, and check if it is a function. */
4450 lua_getglobal(gL.T, args[*cur_arg]);
4451 if (lua_isnil(gL.T, -1)) {
4452 lua_pop(gL.T, 1);
4453 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004454 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004455 }
4456 if (!lua_isfunction(gL.T, -1)) {
4457 lua_pop(gL.T, 1);
4458 memprintf(err, "'%s' is not a function", args[*cur_arg]);
4459 return ACT_RET_PRS_ERR;
4460 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004461
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004462 /* Reference the Lua function and store the reference. */
4463 rule->arg.hlua_rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
4464 rule->arg.hlua_rule->fcn.name = strdup(args[*cur_arg]);
4465 if (!rule->arg.hlua_rule->fcn.name) {
4466 memprintf(err, "out of memory error.");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004467 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004468 }
4469 (*cur_arg)++;
4470
4471 /* TODO: later accept arguments. */
4472 rule->arg.hlua_rule->args = NULL;
4473
Thierry FOURNIER42148732015-09-02 17:17:33 +02004474 rule->action = ACT_CUSTOM;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004475 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004476 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004477}
4478
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004479static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4480 struct proxy *defpx, const char *file, int line,
4481 char **err, unsigned int *timeout)
4482{
4483 const char *error;
4484
4485 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4486 if (error && *error != '\0') {
4487 memprintf(err, "%s: invalid timeout", args[0]);
4488 return -1;
4489 }
4490 return 0;
4491}
4492
4493static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4494 struct proxy *defpx, const char *file, int line,
4495 char **err)
4496{
4497 return hlua_read_timeout(args, section_type, curpx, defpx,
4498 file, line, err, &hlua_timeout_session);
4499}
4500
4501static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4502 struct proxy *defpx, const char *file, int line,
4503 char **err)
4504{
4505 return hlua_read_timeout(args, section_type, curpx, defpx,
4506 file, line, err, &hlua_timeout_task);
4507}
4508
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004509static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4510 struct proxy *defpx, const char *file, int line,
4511 char **err)
4512{
4513 char *error;
4514
4515 hlua_nb_instruction = strtoll(args[1], &error, 10);
4516 if (*error != '\0') {
4517 memprintf(err, "%s: invalid number", args[0]);
4518 return -1;
4519 }
4520 return 0;
4521}
4522
Willy Tarreau32f61e22015-03-18 17:54:59 +01004523static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4524 struct proxy *defpx, const char *file, int line,
4525 char **err)
4526{
4527 char *error;
4528
4529 if (*(args[1]) == 0) {
4530 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4531 return -1;
4532 }
4533 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4534 if (*error != '\0') {
4535 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4536 return -1;
4537 }
4538 return 0;
4539}
4540
4541
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004542/* This function is called by the main configuration key "lua-load". It loads and
4543 * execute an lua file during the parsing of the HAProxy configuration file. It is
4544 * the main lua entry point.
4545 *
4546 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4547 * occured, otherwise it returns 0.
4548 *
4549 * In some error case, LUA set an error message in top of the stack. This function
4550 * returns this error message in the HAProxy logs and pop it from the stack.
4551 */
4552static int hlua_load(char **args, int section_type, struct proxy *curpx,
4553 struct proxy *defpx, const char *file, int line,
4554 char **err)
4555{
4556 int error;
4557
4558 /* Just load and compile the file. */
4559 error = luaL_loadfile(gL.T, args[1]);
4560 if (error) {
4561 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4562 lua_pop(gL.T, 1);
4563 return -1;
4564 }
4565
4566 /* If no syntax error where detected, execute the code. */
4567 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4568 switch (error) {
4569 case LUA_OK:
4570 break;
4571 case LUA_ERRRUN:
4572 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4573 lua_pop(gL.T, 1);
4574 return -1;
4575 case LUA_ERRMEM:
4576 memprintf(err, "lua out of memory error\n");
4577 return -1;
4578 case LUA_ERRERR:
4579 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4580 lua_pop(gL.T, 1);
4581 return -1;
4582 case LUA_ERRGCMM:
4583 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4584 lua_pop(gL.T, 1);
4585 return -1;
4586 default:
4587 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4588 lua_pop(gL.T, 1);
4589 return -1;
4590 }
4591
4592 return 0;
4593}
4594
4595/* configuration keywords declaration */
4596static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004597 { CFG_GLOBAL, "lua-load", hlua_load },
4598 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4599 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004600 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01004601 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004602 { 0, NULL, NULL },
4603}};
4604
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004605static struct action_kw_list http_req_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004606 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004607 { NULL, NULL }
4608}};
4609
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004610static struct action_kw_list http_res_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004611 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004612 { NULL, NULL }
4613}};
4614
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004615static struct action_kw_list tcp_req_cont_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004616 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004617 { NULL, NULL }
4618}};
4619
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004620static struct action_kw_list tcp_res_cont_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004621 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004622 { NULL, NULL }
4623}};
4624
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004625int hlua_post_init()
4626{
4627 struct hlua_init_function *init;
4628 const char *msg;
4629 enum hlua_exec ret;
4630
4631 list_for_each_entry(init, &hlua_init_functions, l) {
4632 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4633 ret = hlua_ctx_resume(&gL, 0);
4634 switch (ret) {
4635 case HLUA_E_OK:
4636 lua_pop(gL.T, -1);
4637 return 1;
4638 case HLUA_E_AGAIN:
4639 Alert("lua init: yield not allowed.\n");
4640 return 0;
4641 case HLUA_E_ERRMSG:
4642 msg = lua_tostring(gL.T, -1);
4643 Alert("lua init: %s.\n", msg);
4644 return 0;
4645 case HLUA_E_ERR:
4646 default:
4647 Alert("lua init: unknown runtime error.\n");
4648 return 0;
4649 }
4650 }
4651 return 1;
4652}
4653
Willy Tarreau32f61e22015-03-18 17:54:59 +01004654/* The memory allocator used by the Lua stack. <ud> is a pointer to the
4655 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4656 * is the previously allocated size or the kind of object in case of a new
4657 * allocation. <nsize> is the requested new size.
4658 */
4659static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4660{
4661 struct hlua_mem_allocator *zone = ud;
4662
4663 if (nsize == 0) {
4664 /* it's a free */
4665 if (ptr)
4666 zone->allocated -= osize;
4667 free(ptr);
4668 return NULL;
4669 }
4670
4671 if (!ptr) {
4672 /* it's a new allocation */
4673 if (zone->limit && zone->allocated + nsize > zone->limit)
4674 return NULL;
4675
4676 ptr = malloc(nsize);
4677 if (ptr)
4678 zone->allocated += nsize;
4679 return ptr;
4680 }
4681
4682 /* it's a realloc */
4683 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4684 return NULL;
4685
4686 ptr = realloc(ptr, nsize);
4687 if (ptr)
4688 zone->allocated += nsize - osize;
4689 return ptr;
4690}
4691
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004692void hlua_init(void)
4693{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004694 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004695 int idx;
4696 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004697 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004698 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004699#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004700 struct srv_kw *kw;
4701 int tmp_error;
4702 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01004703 char *args[] = { /* SSL client configuration. */
4704 "ssl",
4705 "verify",
4706 "none",
4707 "force-sslv3",
4708 NULL
4709 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004710#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004711
Willy Tarreau87b09662015-04-03 00:22:06 +02004712 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004713 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4714
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004715 /* Register configuration keywords. */
4716 cfg_register_keywords(&cfg_kws);
4717
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004718 /* Register custom HTTP rules. */
4719 http_req_keywords_register(&http_req_kws);
4720 http_res_keywords_register(&http_res_kws);
4721 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
4722 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
4723
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004724 /* Init main lua stack. */
4725 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004726 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004727 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004728 gL.T = luaL_newstate();
4729 hlua_sethlua(&gL);
4730 gL.Tref = LUA_REFNIL;
4731 gL.task = NULL;
4732
Willy Tarreau32f61e22015-03-18 17:54:59 +01004733 /* change the memory allocators to track memory usage */
4734 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4735
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004736 /* Initialise lua. */
4737 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004738
4739 /*
4740 *
4741 * Create "core" object.
4742 *
4743 */
4744
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004745 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004746 lua_newtable(gL.T);
4747
4748 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004749 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004750 hlua_class_const_int(gL.T, log_levels[i], i);
4751
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004752 /* Register special functions. */
4753 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004754 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004755 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004756 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004757 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004758 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004759 hlua_class_function(gL.T, "sleep", hlua_sleep);
4760 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004761 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4762 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4763 hlua_class_function(gL.T, "set_map", hlua_set_map);
4764 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004765 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004766 hlua_class_function(gL.T, "log", hlua_log);
4767 hlua_class_function(gL.T, "Debug", hlua_log_debug);
4768 hlua_class_function(gL.T, "Info", hlua_log_info);
4769 hlua_class_function(gL.T, "Warning", hlua_log_warning);
4770 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02004771 hlua_class_function(gL.T, "done", hlua_done);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004772
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004773 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004774
4775 /*
4776 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02004777 * Register class Map
4778 *
4779 */
4780
4781 /* This table entry is the object "Map" base. */
4782 lua_newtable(gL.T);
4783
4784 /* register pattern types. */
4785 for (i=0; i<PAT_MATCH_NUM; i++)
4786 hlua_class_const_int(gL.T, pat_match_names[i], i);
4787
4788 /* register constructor. */
4789 hlua_class_function(gL.T, "new", hlua_map_new);
4790
4791 /* Create and fill the metatable. */
4792 lua_newtable(gL.T);
4793
4794 /* Create and fille the __index entry. */
4795 lua_pushstring(gL.T, "__index");
4796 lua_newtable(gL.T);
4797
4798 /* Register . */
4799 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
4800 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
4801
4802 lua_settable(gL.T, -3);
4803
4804 /* Register previous table in the registry with reference and named entry. */
4805 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4806 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4807 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
4808 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4809
4810 /* Assign the metatable to the mai Map object. */
4811 lua_setmetatable(gL.T, -2);
4812
4813 /* Set a name to the table. */
4814 lua_setglobal(gL.T, "Map");
4815
4816 /*
4817 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004818 * Register class Channel
4819 *
4820 */
4821
4822 /* Create and fill the metatable. */
4823 lua_newtable(gL.T);
4824
4825 /* Create and fille the __index entry. */
4826 lua_pushstring(gL.T, "__index");
4827 lua_newtable(gL.T);
4828
4829 /* Register . */
4830 hlua_class_function(gL.T, "get", hlua_channel_get);
4831 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4832 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4833 hlua_class_function(gL.T, "set", hlua_channel_set);
4834 hlua_class_function(gL.T, "append", hlua_channel_append);
4835 hlua_class_function(gL.T, "send", hlua_channel_send);
4836 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4837 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4838 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4839
4840 lua_settable(gL.T, -3);
4841
4842 /* Register previous table in the registry with reference and named entry. */
4843 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4844 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4845 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4846
4847 /*
4848 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004849 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004850 *
4851 */
4852
4853 /* Create and fill the metatable. */
4854 lua_newtable(gL.T);
4855
4856 /* Create and fille the __index entry. */
4857 lua_pushstring(gL.T, "__index");
4858 lua_newtable(gL.T);
4859
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004860 /* Browse existing fetches and create the associated
4861 * object method.
4862 */
4863 sf = NULL;
4864 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4865
4866 /* Dont register the keywork if the arguments check function are
4867 * not safe during the runtime.
4868 */
4869 if ((sf->val_args != NULL) &&
4870 (sf->val_args != val_payload_lv) &&
4871 (sf->val_args != val_hdr))
4872 continue;
4873
4874 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4875 * by an underscore.
4876 */
4877 strncpy(trash.str, sf->kw, trash.size);
4878 trash.str[trash.size - 1] = '\0';
4879 for (p = trash.str; *p; p++)
4880 if (*p == '.' || *p == '-' || *p == '+')
4881 *p = '_';
4882
4883 /* Register the function. */
4884 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01004885 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004886 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4887 lua_settable(gL.T, -3);
4888 }
4889
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004890 lua_settable(gL.T, -3);
4891
4892 /* Register previous table in the registry with reference and named entry. */
4893 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4894 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4895 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4896
4897 /*
4898 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004899 * Register class Converters
4900 *
4901 */
4902
4903 /* Create and fill the metatable. */
4904 lua_newtable(gL.T);
4905
4906 /* Create and fill the __index entry. */
4907 lua_pushstring(gL.T, "__index");
4908 lua_newtable(gL.T);
4909
4910 /* Browse existing converters and create the associated
4911 * object method.
4912 */
4913 sc = NULL;
4914 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4915 /* Dont register the keywork if the arguments check function are
4916 * not safe during the runtime.
4917 */
4918 if (sc->val_args != NULL)
4919 continue;
4920
4921 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4922 * by an underscore.
4923 */
4924 strncpy(trash.str, sc->kw, trash.size);
4925 trash.str[trash.size - 1] = '\0';
4926 for (p = trash.str; *p; p++)
4927 if (*p == '.' || *p == '-' || *p == '+')
4928 *p = '_';
4929
4930 /* Register the function. */
4931 lua_pushstring(gL.T, trash.str);
4932 lua_pushlightuserdata(gL.T, sc);
4933 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4934 lua_settable(gL.T, -3);
4935 }
4936
4937 lua_settable(gL.T, -3);
4938
4939 /* Register previous table in the registry with reference and named entry. */
4940 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4941 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4942 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4943
4944 /*
4945 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004946 * Register class HTTP
4947 *
4948 */
4949
4950 /* Create and fill the metatable. */
4951 lua_newtable(gL.T);
4952
4953 /* Create and fille the __index entry. */
4954 lua_pushstring(gL.T, "__index");
4955 lua_newtable(gL.T);
4956
4957 /* Register Lua functions. */
4958 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
4959 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
4960 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
4961 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
4962 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
4963 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
4964 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
4965 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
4966 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
4967 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
4968
4969 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
4970 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
4971 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
4972 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
4973 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
4974 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004975 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004976
4977 lua_settable(gL.T, -3);
4978
4979 /* Register previous table in the registry with reference and named entry. */
4980 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4981 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
4982 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4983
4984 /*
4985 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004986 * Register class TXN
4987 *
4988 */
4989
4990 /* Create and fill the metatable. */
4991 lua_newtable(gL.T);
4992
4993 /* Create and fille the __index entry. */
4994 lua_pushstring(gL.T, "__index");
4995 lua_newtable(gL.T);
4996
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004997 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004998 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4999 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02005000 hlua_class_function(gL.T, "set_var", hlua_set_var);
5001 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER4bb375c2015-08-26 08:42:21 +02005002 hlua_class_function(gL.T, "done", hlua_txn_done);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01005003 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
5004 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
5005 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01005006 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
5007 hlua_class_function(gL.T, "log", hlua_txn_log);
5008 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
5009 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
5010 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
5011 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01005012
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01005013 lua_settable(gL.T, -3);
5014
5015 /* Register previous table in the registry with reference and named entry. */
5016 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5017 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
5018 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005019
5020 /*
5021 *
5022 * Register class Socket
5023 *
5024 */
5025
5026 /* Create and fill the metatable. */
5027 lua_newtable(gL.T);
5028
5029 /* Create and fille the __index entry. */
5030 lua_pushstring(gL.T, "__index");
5031 lua_newtable(gL.T);
5032
Baptiste Assmann84bb4932015-03-02 21:40:06 +01005033#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005034 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01005035#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005036 hlua_class_function(gL.T, "connect", hlua_socket_connect);
5037 hlua_class_function(gL.T, "send", hlua_socket_send);
5038 hlua_class_function(gL.T, "receive", hlua_socket_receive);
5039 hlua_class_function(gL.T, "close", hlua_socket_close);
5040 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
5041 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
5042 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
5043 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
5044
5045 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5046
5047 /* Register the garbage collector entry. */
5048 lua_pushstring(gL.T, "__gc");
5049 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
5050 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5051
5052 /* Register previous table in the registry with reference and named entry. */
5053 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5054 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5055 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
5056 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
5057
5058 /* Proxy and server configuration initialisation. */
5059 memset(&socket_proxy, 0, sizeof(socket_proxy));
5060 init_new_proxy(&socket_proxy);
5061 socket_proxy.parent = NULL;
5062 socket_proxy.last_change = now.tv_sec;
5063 socket_proxy.id = "LUA-SOCKET";
5064 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
5065 socket_proxy.maxconn = 0;
5066 socket_proxy.accept = NULL;
5067 socket_proxy.options2 |= PR_O2_INDEPSTR;
5068 socket_proxy.srv = NULL;
5069 socket_proxy.conn_retries = 0;
5070 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
5071
5072 /* Init TCP server: unchanged parameters */
5073 memset(&socket_tcp, 0, sizeof(socket_tcp));
5074 socket_tcp.next = NULL;
5075 socket_tcp.proxy = &socket_proxy;
5076 socket_tcp.obj_type = OBJ_TYPE_SERVER;
5077 LIST_INIT(&socket_tcp.actconns);
5078 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005079 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005080 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005081 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005082 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
5083 socket_tcp.last_change = 0;
5084 socket_tcp.id = "LUA-TCP-CONN";
5085 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5086 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5087 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
5088
5089 /* XXX: Copy default parameter from default server,
5090 * but the default server is not initialized.
5091 */
5092 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
5093 socket_tcp.minconn = socket_proxy.defsrv.minconn;
5094 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
5095 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
5096 socket_tcp.onerror = socket_proxy.defsrv.onerror;
5097 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5098 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
5099 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5100 socket_tcp.uweight = socket_proxy.defsrv.iweight;
5101 socket_tcp.iweight = socket_proxy.defsrv.iweight;
5102
5103 socket_tcp.check.status = HCHK_STATUS_INI;
5104 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
5105 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
5106 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
5107 socket_tcp.check.server = &socket_tcp;
5108
5109 socket_tcp.agent.status = HCHK_STATUS_INI;
5110 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
5111 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
5112 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
5113 socket_tcp.agent.server = &socket_tcp;
5114
5115 socket_tcp.xprt = &raw_sock;
5116
5117#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005118 /* Init TCP server: unchanged parameters */
5119 memset(&socket_ssl, 0, sizeof(socket_ssl));
5120 socket_ssl.next = NULL;
5121 socket_ssl.proxy = &socket_proxy;
5122 socket_ssl.obj_type = OBJ_TYPE_SERVER;
5123 LIST_INIT(&socket_ssl.actconns);
5124 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005125 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005126 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005127 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005128 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
5129 socket_ssl.last_change = 0;
5130 socket_ssl.id = "LUA-SSL-CONN";
5131 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5132 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5133 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
5134
5135 /* XXX: Copy default parameter from default server,
5136 * but the default server is not initialized.
5137 */
5138 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
5139 socket_ssl.minconn = socket_proxy.defsrv.minconn;
5140 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
5141 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5142 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5143 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5144 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5145 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5146 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5147 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5148
5149 socket_ssl.check.status = HCHK_STATUS_INI;
5150 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5151 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5152 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5153 socket_ssl.check.server = &socket_ssl;
5154
5155 socket_ssl.agent.status = HCHK_STATUS_INI;
5156 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5157 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5158 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5159 socket_ssl.agent.server = &socket_ssl;
5160
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005161 socket_ssl.use_ssl = 1;
5162 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005163
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005164 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005165 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5166 /*
5167 *
5168 * If the keyword is not known, we can search in the registered
5169 * server keywords. This is usefull to configure special SSL
5170 * features like client certificates and ssl_verify.
5171 *
5172 */
5173 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5174 if (tmp_error != 0) {
5175 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5176 abort(); /* This must be never arrives because the command line
5177 not editable by the user. */
5178 }
5179 idx += kw->skip;
5180 }
5181 }
5182
5183 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005184 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005185#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005186}