blob: 7669f96e53fd47c4569606b4c4c4c4d957cc7795 [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))) {
762 get_localtime(date.tv_sec, &tm);
763 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
764 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;
1003 break;
1004 }
1005
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001006 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001007 if (!lua_checkstack(lua->T, 1)) {
1008 ret = HLUA_E_ERR;
1009 break;
1010 }
1011 msg = lua_tostring(lua->T, -1);
1012 lua_settop(lua->T, 0); /* Empty the stack. */
1013 lua_pop(lua->T, 1);
1014 if (msg)
1015 lua_pushfstring(lua->T, "runtime error: %s", msg);
1016 else
1017 lua_pushfstring(lua->T, "unknown runtime error");
1018 ret = HLUA_E_ERRMSG;
1019 break;
1020
1021 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001022 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001023 lua_settop(lua->T, 0); /* Empty the stack. */
1024 if (!lua_checkstack(lua->T, 1)) {
1025 ret = HLUA_E_ERR;
1026 break;
1027 }
1028 lua_pushfstring(lua->T, "out of memory error");
1029 ret = HLUA_E_ERRMSG;
1030 break;
1031
1032 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001033 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001034 if (!lua_checkstack(lua->T, 1)) {
1035 ret = HLUA_E_ERR;
1036 break;
1037 }
1038 msg = lua_tostring(lua->T, -1);
1039 lua_settop(lua->T, 0); /* Empty the stack. */
1040 lua_pop(lua->T, 1);
1041 if (msg)
1042 lua_pushfstring(lua->T, "message handler error: %s", msg);
1043 else
1044 lua_pushfstring(lua->T, "message handler error");
1045 ret = HLUA_E_ERRMSG;
1046 break;
1047
1048 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001049 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001050 lua_settop(lua->T, 0); /* Empty the stack. */
1051 if (!lua_checkstack(lua->T, 1)) {
1052 ret = HLUA_E_ERR;
1053 break;
1054 }
1055 lua_pushfstring(lua->T, "unknonwn error");
1056 ret = HLUA_E_ERRMSG;
1057 break;
1058 }
1059
1060 switch (ret) {
1061 case HLUA_E_AGAIN:
1062 break;
1063
1064 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001065 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001066 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001067 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001068 break;
1069
1070 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001071 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001072 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001073 hlua_ctx_renew(lua, 0);
1074 break;
1075
1076 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001077 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001078 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001079 break;
1080 }
1081
1082 return ret;
1083}
1084
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02001085/* This function exit the current code. */
1086__LJMP static int hlua_done(lua_State *L)
1087{
1088 struct hlua *hlua = hlua_gethlua(L);
1089
1090 hlua->flags |= HLUA_EXIT;
1091 WILL_LJMP(lua_error(L));
1092
1093 return 0;
1094}
1095
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001096/* This function is an LUA binding. It provides a function
1097 * for deleting ACL from a referenced ACL file.
1098 */
1099__LJMP static int hlua_del_acl(lua_State *L)
1100{
1101 const char *name;
1102 const char *key;
1103 struct pat_ref *ref;
1104
1105 MAY_LJMP(check_args(L, 2, "del_acl"));
1106
1107 name = MAY_LJMP(luaL_checkstring(L, 1));
1108 key = MAY_LJMP(luaL_checkstring(L, 2));
1109
1110 ref = pat_ref_lookup(name);
1111 if (!ref)
1112 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1113
1114 pat_ref_delete(ref, key);
1115 return 0;
1116}
1117
1118/* This function is an LUA binding. It provides a function
1119 * for deleting map entry from a referenced map file.
1120 */
1121static int hlua_del_map(lua_State *L)
1122{
1123 const char *name;
1124 const char *key;
1125 struct pat_ref *ref;
1126
1127 MAY_LJMP(check_args(L, 2, "del_map"));
1128
1129 name = MAY_LJMP(luaL_checkstring(L, 1));
1130 key = MAY_LJMP(luaL_checkstring(L, 2));
1131
1132 ref = pat_ref_lookup(name);
1133 if (!ref)
1134 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1135
1136 pat_ref_delete(ref, key);
1137 return 0;
1138}
1139
1140/* This function is an LUA binding. It provides a function
1141 * for adding ACL pattern from a referenced ACL file.
1142 */
1143static int hlua_add_acl(lua_State *L)
1144{
1145 const char *name;
1146 const char *key;
1147 struct pat_ref *ref;
1148
1149 MAY_LJMP(check_args(L, 2, "add_acl"));
1150
1151 name = MAY_LJMP(luaL_checkstring(L, 1));
1152 key = MAY_LJMP(luaL_checkstring(L, 2));
1153
1154 ref = pat_ref_lookup(name);
1155 if (!ref)
1156 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1157
1158 if (pat_ref_find_elt(ref, key) == NULL)
1159 pat_ref_add(ref, key, NULL, NULL);
1160 return 0;
1161}
1162
1163/* This function is an LUA binding. It provides a function
1164 * for setting map pattern and sample from a referenced map
1165 * file.
1166 */
1167static int hlua_set_map(lua_State *L)
1168{
1169 const char *name;
1170 const char *key;
1171 const char *value;
1172 struct pat_ref *ref;
1173
1174 MAY_LJMP(check_args(L, 3, "set_map"));
1175
1176 name = MAY_LJMP(luaL_checkstring(L, 1));
1177 key = MAY_LJMP(luaL_checkstring(L, 2));
1178 value = MAY_LJMP(luaL_checkstring(L, 3));
1179
1180 ref = pat_ref_lookup(name);
1181 if (!ref)
1182 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1183
1184 if (pat_ref_find_elt(ref, key) != NULL)
1185 pat_ref_set(ref, key, value, NULL);
1186 else
1187 pat_ref_add(ref, key, value, NULL);
1188 return 0;
1189}
1190
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001191/* A class is a lot of memory that contain data. This data can be a table,
1192 * an integer or user data. This data is associated with a metatable. This
1193 * metatable have an original version registred in the global context with
1194 * the name of the object (_G[<name>] = <metable> ).
1195 *
1196 * A metable is a table that modify the standard behavior of a standard
1197 * access to the associated data. The entries of this new metatable are
1198 * defined as is:
1199 *
1200 * http://lua-users.org/wiki/MetatableEvents
1201 *
1202 * __index
1203 *
1204 * we access an absent field in a table, the result is nil. This is
1205 * true, but it is not the whole truth. Actually, such access triggers
1206 * the interpreter to look for an __index metamethod: If there is no
1207 * such method, as usually happens, then the access results in nil;
1208 * otherwise, the metamethod will provide the result.
1209 *
1210 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1211 * the key does not appear in the table, but the metatable has an __index
1212 * property:
1213 *
1214 * - if the value is a function, the function is called, passing in the
1215 * table and the key; the return value of that function is returned as
1216 * the result.
1217 *
1218 * - if the value is another table, the value of the key in that table is
1219 * asked for and returned (and if it doesn't exist in that table, but that
1220 * table's metatable has an __index property, then it continues on up)
1221 *
1222 * - Use "rawget(myTable,key)" to skip this metamethod.
1223 *
1224 * http://www.lua.org/pil/13.4.1.html
1225 *
1226 * __newindex
1227 *
1228 * Like __index, but control property assignment.
1229 *
1230 * __mode - Control weak references. A string value with one or both
1231 * of the characters 'k' and 'v' which specifies that the the
1232 * keys and/or values in the table are weak references.
1233 *
1234 * __call - Treat a table like a function. When a table is followed by
1235 * parenthesis such as "myTable( 'foo' )" and the metatable has
1236 * a __call key pointing to a function, that function is invoked
1237 * (passing any specified arguments) and the return value is
1238 * returned.
1239 *
1240 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1241 * called, if the metatable for myTable has a __metatable
1242 * key, the value of that key is returned instead of the
1243 * actual metatable.
1244 *
1245 * __tostring - Control string representation. When the builtin
1246 * "tostring( myTable )" function is called, if the metatable
1247 * for myTable has a __tostring property set to a function,
1248 * that function is invoked (passing myTable to it) and the
1249 * return value is used as the string representation.
1250 *
1251 * __len - Control table length. When the table length is requested using
1252 * the length operator ( '#' ), if the metatable for myTable has
1253 * a __len key pointing to a function, that function is invoked
1254 * (passing myTable to it) and the return value used as the value
1255 * of "#myTable".
1256 *
1257 * __gc - Userdata finalizer code. When userdata is set to be garbage
1258 * collected, if the metatable has a __gc field pointing to a
1259 * function, that function is first invoked, passing the userdata
1260 * to it. The __gc metamethod is not called for tables.
1261 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1262 *
1263 * Special metamethods for redefining standard operators:
1264 * http://www.lua.org/pil/13.1.html
1265 *
1266 * __add "+"
1267 * __sub "-"
1268 * __mul "*"
1269 * __div "/"
1270 * __unm "!"
1271 * __pow "^"
1272 * __concat ".."
1273 *
1274 * Special methods for redfining standar relations
1275 * http://www.lua.org/pil/13.2.html
1276 *
1277 * __eq "=="
1278 * __lt "<"
1279 * __le "<="
1280 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001281
1282/*
1283 *
1284 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001285 * Class Map
1286 *
1287 *
1288 */
1289
1290/* Returns a struct hlua_map if the stack entry "ud" is
1291 * a class session, otherwise it throws an error.
1292 */
1293__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1294{
1295 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1296}
1297
1298/* This function is the map constructor. It don't need
1299 * the class Map object. It creates and return a new Map
1300 * object. It must be called only during "body" or "init"
1301 * context because it process some filesystem accesses.
1302 */
1303__LJMP static int hlua_map_new(struct lua_State *L)
1304{
1305 const char *fn;
1306 int match = PAT_MATCH_STR;
1307 struct sample_conv conv;
1308 const char *file = "";
1309 int line = 0;
1310 lua_Debug ar;
1311 char *err = NULL;
1312 struct arg args[2];
1313
1314 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1315 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1316
1317 fn = MAY_LJMP(luaL_checkstring(L, 1));
1318
1319 if (lua_gettop(L) >= 2) {
1320 match = MAY_LJMP(luaL_checkinteger(L, 2));
1321 if (match < 0 || match >= PAT_MATCH_NUM)
1322 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1323 }
1324
1325 /* Get Lua filename and line number. */
1326 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1327 lua_getinfo(L, "Sl", &ar); /* get info about it */
1328 if (ar.currentline > 0) { /* is there info? */
1329 file = ar.short_src;
1330 line = ar.currentline;
1331 }
1332 }
1333
1334 /* fill fake sample_conv struct. */
1335 conv.kw = ""; /* unused. */
1336 conv.process = NULL; /* unused. */
1337 conv.arg_mask = 0; /* unused. */
1338 conv.val_args = NULL; /* unused. */
1339 conv.out_type = SMP_T_STR;
1340 conv.private = (void *)(long)match;
1341 switch (match) {
1342 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1343 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1344 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1345 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1346 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1347 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1348 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001349 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001350 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1351 default:
1352 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1353 }
1354
1355 /* fill fake args. */
1356 args[0].type = ARGT_STR;
1357 args[0].data.str.str = (char *)fn;
1358 args[1].type = ARGT_STOP;
1359
1360 /* load the map. */
1361 if (!sample_load_map(args, &conv, file, line, &err)) {
1362 /* error case: we cant use luaL_error because we must
1363 * free the err variable.
1364 */
1365 luaL_where(L, 1);
1366 lua_pushfstring(L, "'new': %s.", err);
1367 lua_concat(L, 2);
1368 free(err);
1369 WILL_LJMP(lua_error(L));
1370 }
1371
1372 /* create the lua object. */
1373 lua_newtable(L);
1374 lua_pushlightuserdata(L, args[0].data.map);
1375 lua_rawseti(L, -2, 0);
1376
1377 /* Pop a class Map metatable and affect it to the userdata. */
1378 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1379 lua_setmetatable(L, -2);
1380
1381
1382 return 1;
1383}
1384
1385__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1386{
1387 struct map_descriptor *desc;
1388 struct pattern *pat;
1389 struct sample smp;
1390
1391 MAY_LJMP(check_args(L, 2, "lookup"));
1392 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001393 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001394 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001395 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001396 }
1397 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001398 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001399 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001400 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 +02001401 }
1402
1403 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001404 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001405 if (str)
1406 lua_pushstring(L, "");
1407 else
1408 lua_pushnil(L);
1409 return 1;
1410 }
1411
1412 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001413 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001414 return 1;
1415}
1416
1417__LJMP static int hlua_map_lookup(struct lua_State *L)
1418{
1419 return _hlua_map_lookup(L, 0);
1420}
1421
1422__LJMP static int hlua_map_slookup(struct lua_State *L)
1423{
1424 return _hlua_map_lookup(L, 1);
1425}
1426
1427/*
1428 *
1429 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001430 * Class Socket
1431 *
1432 *
1433 */
1434
1435__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1436{
1437 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1438}
1439
1440/* This function is the handler called for each I/O on the established
1441 * connection. It is used for notify space avalaible to send or data
1442 * received.
1443 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001444static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001445{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001446 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001447 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001448
Willy Tarreau87b09662015-04-03 00:22:06 +02001449 /* Wakeup the main stream if the client connection is closed. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001450 if (!c || channel_output_closed(si_ic(si)) || channel_input_closed(si_oc(si))) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001451 if (appctx->ctx.hlua.socket) {
1452 appctx->ctx.hlua.socket->s = NULL;
1453 appctx->ctx.hlua.socket = NULL;
1454 }
1455 si_shutw(si);
1456 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001457 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001458 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1459 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001460 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001461 }
1462
1463 if (!(c->flags & CO_FL_CONNECTED))
Willy Tarreaud4da1962015-04-20 01:31:23 +02001464 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001465
1466 /* This function is called after the connect. */
1467 appctx->ctx.hlua.connected = 1;
1468
1469 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001470 if (channel_may_recv(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001471 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1472
1473 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001474 if (channel_is_empty(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001475 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1476}
1477
Willy Tarreau87b09662015-04-03 00:22:06 +02001478/* This function is called when the "struct stream" is destroyed.
1479 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001480 * Wake all the pending signals.
1481 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001482static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001483{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001484 /* Remove my link in the original object. */
1485 if (appctx->ctx.hlua.socket)
1486 appctx->ctx.hlua.socket->s = NULL;
1487
1488 /* Wake all the task waiting for me. */
1489 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1490 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1491}
1492
1493/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001494 * uses this object. If the stream does not exists, just quit.
1495 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001496 * pending signal can rest in the read and write lists. destroy
1497 * it.
1498 */
1499__LJMP static int hlua_socket_gc(lua_State *L)
1500{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001501 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001502 struct appctx *appctx;
1503
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001504 MAY_LJMP(check_args(L, 1, "__gc"));
1505
1506 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001507 if (!socket->s)
1508 return 0;
1509
Willy Tarreau87b09662015-04-03 00:22:06 +02001510 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001511 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001512 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001513 socket->s = NULL;
1514 appctx->ctx.hlua.socket = NULL;
1515
1516 return 0;
1517}
1518
1519/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001520 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001521 */
1522__LJMP static int hlua_socket_close(lua_State *L)
1523{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001524 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001525 struct appctx *appctx;
1526
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001527 MAY_LJMP(check_args(L, 1, "close"));
1528
1529 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001530 if (!socket->s)
1531 return 0;
1532
Willy Tarreau87b09662015-04-03 00:22:06 +02001533 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001534 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001535 appctx = objt_appctx(socket->s->si[0].end);
1536 appctx->ctx.hlua.socket = NULL;
1537 socket->s = NULL;
1538
1539 return 0;
1540}
1541
1542/* This Lua function assumes that the stack contain three parameters.
1543 * 1 - USERDATA containing a struct socket
1544 * 2 - INTEGER with values of the macro defined below
1545 * If the integer is -1, we must read at most one line.
1546 * If the integer is -2, we ust read all the data until the
1547 * end of the stream.
1548 * If the integer is positive value, we must read a number of
1549 * bytes corresponding to this value.
1550 */
1551#define HLSR_READ_LINE (-1)
1552#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001553__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001554{
1555 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1556 int wanted = lua_tointeger(L, 2);
1557 struct hlua *hlua = hlua_gethlua(L);
1558 struct appctx *appctx;
1559 int len;
1560 int nblk;
1561 char *blk1;
1562 int len1;
1563 char *blk2;
1564 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001565 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001566 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001567
1568 /* Check if this lua stack is schedulable. */
1569 if (!hlua || !hlua->task)
1570 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1571 "'frontend', 'backend' or 'task'"));
1572
1573 /* check for connection closed. If some data where read, return it. */
1574 if (!socket->s)
1575 goto connection_closed;
1576
Willy Tarreau94aa6172015-03-13 14:19:06 +01001577 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001578 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001579 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001580 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001581 if (nblk < 0) /* Connection close. */
1582 goto connection_closed;
1583 if (nblk == 0) /* No data avalaible. */
1584 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001585
1586 /* remove final \r\n. */
1587 if (nblk == 1) {
1588 if (blk1[len1-1] == '\n') {
1589 len1--;
1590 skip_at_end++;
1591 if (blk1[len1-1] == '\r') {
1592 len1--;
1593 skip_at_end++;
1594 }
1595 }
1596 }
1597 else {
1598 if (blk2[len2-1] == '\n') {
1599 len2--;
1600 skip_at_end++;
1601 if (blk2[len2-1] == '\r') {
1602 len2--;
1603 skip_at_end++;
1604 }
1605 }
1606 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001607 }
1608
1609 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001610 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001611 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001612 if (nblk < 0) /* Connection close. */
1613 goto connection_closed;
1614 if (nblk == 0) /* No data avalaible. */
1615 goto connection_empty;
1616 }
1617
1618 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001619 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001620 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001621 if (nblk < 0) /* Connection close. */
1622 goto connection_closed;
1623 if (nblk == 0) /* No data avalaible. */
1624 goto connection_empty;
1625
1626 if (len1 > wanted) {
1627 nblk = 1;
1628 len1 = wanted;
1629 } if (nblk == 2 && len1 + len2 > wanted)
1630 len2 = wanted - len1;
1631 }
1632
1633 len = len1;
1634
1635 luaL_addlstring(&socket->b, blk1, len1);
1636 if (nblk == 2) {
1637 len += len2;
1638 luaL_addlstring(&socket->b, blk2, len2);
1639 }
1640
1641 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001642 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001643
1644 /* Don't wait anything. */
Willy Tarreau828824a2015-04-19 17:20:03 +02001645 si_applet_done(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001646
1647 /* If the pattern reclaim to read all the data
1648 * in the connection, got out.
1649 */
1650 if (wanted == HLSR_READ_ALL)
1651 goto connection_empty;
1652 else if (wanted >= 0 && len < wanted)
1653 goto connection_empty;
1654
1655 /* Return result. */
1656 luaL_pushresult(&socket->b);
1657 return 1;
1658
1659connection_closed:
1660
1661 /* If the buffer containds data. */
1662 if (socket->b.n > 0) {
1663 luaL_pushresult(&socket->b);
1664 return 1;
1665 }
1666 lua_pushnil(L);
1667 lua_pushstring(L, "connection closed.");
1668 return 2;
1669
1670connection_empty:
1671
1672 appctx = objt_appctx(socket->s->si[0].end);
1673 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1674 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001675 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001676 return 0;
1677}
1678
1679/* This Lus function gets two parameters. The first one can be string
1680 * or a number. If the string is "*l", the user require one line. If
1681 * the string is "*a", the user require all the content of the stream.
1682 * If the value is a number, the user require a number of bytes equal
1683 * to the value. The default value is "*l" (a line).
1684 *
1685 * This paraeter with a variable type is converted in integer. This
1686 * integer takes this values:
1687 * -1 : read a line
1688 * -2 : read all the stream
1689 * >0 : amount if bytes.
1690 *
1691 * The second parameter is optinal. It contains a string that must be
1692 * concatenated with the read data.
1693 */
1694__LJMP static int hlua_socket_receive(struct lua_State *L)
1695{
1696 int wanted = HLSR_READ_LINE;
1697 const char *pattern;
1698 int type;
1699 char *error;
1700 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001701 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001702
1703 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1704 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1705
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001706 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001707
1708 /* check for pattern. */
1709 if (lua_gettop(L) >= 2) {
1710 type = lua_type(L, 2);
1711 if (type == LUA_TSTRING) {
1712 pattern = lua_tostring(L, 2);
1713 if (strcmp(pattern, "*a") == 0)
1714 wanted = HLSR_READ_ALL;
1715 else if (strcmp(pattern, "*l") == 0)
1716 wanted = HLSR_READ_LINE;
1717 else {
1718 wanted = strtoll(pattern, &error, 10);
1719 if (*error != '\0')
1720 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1721 }
1722 }
1723 else if (type == LUA_TNUMBER) {
1724 wanted = lua_tointeger(L, 2);
1725 if (wanted < 0)
1726 WILL_LJMP(luaL_error(L, "Unsupported size."));
1727 }
1728 }
1729
1730 /* Set pattern. */
1731 lua_pushinteger(L, wanted);
1732 lua_replace(L, 2);
1733
1734 /* init bufffer, and fiil it wih prefix. */
1735 luaL_buffinit(L, &socket->b);
1736
1737 /* Check prefix. */
1738 if (lua_gettop(L) >= 3) {
1739 if (lua_type(L, 3) != LUA_TSTRING)
1740 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1741 pattern = lua_tolstring(L, 3, &len);
1742 luaL_addlstring(&socket->b, pattern, len);
1743 }
1744
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001745 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001746}
1747
1748/* Write the Lua input string in the output buffer.
1749 * This fucntion returns a yield if no space are available.
1750 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001751static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001752{
1753 struct hlua_socket *socket;
1754 struct hlua *hlua = hlua_gethlua(L);
1755 struct appctx *appctx;
1756 size_t buf_len;
1757 const char *buf;
1758 int len;
1759 int send_len;
1760 int sent;
1761
1762 /* Check if this lua stack is schedulable. */
1763 if (!hlua || !hlua->task)
1764 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1765 "'frontend', 'backend' or 'task'"));
1766
1767 /* Get object */
1768 socket = MAY_LJMP(hlua_checksocket(L, 1));
1769 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001770 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001771
1772 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001773 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001774 lua_pushinteger(L, -1);
1775 return 1;
1776 }
1777
1778 /* Update the input buffer data. */
1779 buf += sent;
1780 send_len = buf_len - sent;
1781
1782 /* All the data are sent. */
1783 if (sent >= buf_len)
1784 return 1; /* Implicitly return the length sent. */
1785
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001786 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1787 * the request buffer if its not required.
1788 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001789 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001790 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001791 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001792 goto hlua_socket_write_yield_return;
1793 }
1794 }
1795
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001796 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001797 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001798 if (len <= 0)
1799 goto hlua_socket_write_yield_return;
1800
1801 /* send data */
1802 if (len < send_len)
1803 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001804 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001805
1806 /* "Not enough space" (-1), "Buffer too little to contain
1807 * the data" (-2) are not expected because the available length
1808 * is tested.
1809 * Other unknown error are also not expected.
1810 */
1811 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001812 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001813 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001814
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001815 MAY_LJMP(hlua_socket_close(L));
1816 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001817 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001818 return 1;
1819 }
1820
1821 /* update buffers. */
Willy Tarreau828824a2015-04-19 17:20:03 +02001822 si_applet_done(&socket->s->si[0]);
Willy Tarreau94aa6172015-03-13 14:19:06 +01001823 socket->s->req.rex = TICK_ETERNITY;
1824 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001825
1826 /* Update length sent. */
1827 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001828 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001829
1830 /* All the data buffer is sent ? */
1831 if (sent + len >= buf_len)
1832 return 1;
1833
1834hlua_socket_write_yield_return:
1835 appctx = objt_appctx(socket->s->si[0].end);
1836 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1837 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001838 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001839 return 0;
1840}
1841
1842/* This function initiate the send of data. It just check the input
1843 * parameters and push an integer in the Lua stack that contain the
1844 * amount of data writed in the buffer. This is used by the function
1845 * "hlua_socket_write_yield" that can yield.
1846 *
1847 * The Lua function gets between 3 and 4 parameters. The first one is
1848 * the associated object. The second is a string buffer. The third is
1849 * a facultative integer that represents where is the buffer position
1850 * of the start of the data that can send. The first byte is the
1851 * position "1". The default value is "1". The fourth argument is a
1852 * facultative integer that represents where is the buffer position
1853 * of the end of the data that can send. The default is the last byte.
1854 */
1855static int hlua_socket_send(struct lua_State *L)
1856{
1857 int i;
1858 int j;
1859 const char *buf;
1860 size_t buf_len;
1861
1862 /* Check number of arguments. */
1863 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1864 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1865
1866 /* Get the string. */
1867 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1868
1869 /* Get and check j. */
1870 if (lua_gettop(L) == 4) {
1871 j = MAY_LJMP(luaL_checkinteger(L, 4));
1872 if (j < 0)
1873 j = buf_len + j + 1;
1874 if (j > buf_len)
1875 j = buf_len + 1;
1876 lua_pop(L, 1);
1877 }
1878 else
1879 j = buf_len;
1880
1881 /* Get and check i. */
1882 if (lua_gettop(L) == 3) {
1883 i = MAY_LJMP(luaL_checkinteger(L, 3));
1884 if (i < 0)
1885 i = buf_len + i + 1;
1886 if (i > buf_len)
1887 i = buf_len + 1;
1888 lua_pop(L, 1);
1889 } else
1890 i = 1;
1891
1892 /* Check bth i and j. */
1893 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001894 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001895 return 1;
1896 }
1897 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001898 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001899 return 1;
1900 }
1901 if (i == 0)
1902 i = 1;
1903 if (j == 0)
1904 j = 1;
1905
1906 /* Pop the string. */
1907 lua_pop(L, 1);
1908
1909 /* Update the buffer length. */
1910 buf += i - 1;
1911 buf_len = j - i + 1;
1912 lua_pushlstring(L, buf, buf_len);
1913
1914 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001915 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001916
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001917 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001918}
1919
Willy Tarreau22b0a682015-06-17 19:43:49 +02001920#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001921__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1922{
1923 static char buffer[SOCKET_INFO_MAX_LEN];
1924 int ret;
1925 int len;
1926 char *p;
1927
1928 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1929 if (ret <= 0) {
1930 lua_pushnil(L);
1931 return 1;
1932 }
1933
1934 if (ret == AF_UNIX) {
1935 lua_pushstring(L, buffer+1);
1936 return 1;
1937 }
1938 else if (ret == AF_INET6) {
1939 buffer[0] = '[';
1940 len = strlen(buffer);
1941 buffer[len] = ']';
1942 len++;
1943 buffer[len] = ':';
1944 len++;
1945 p = buffer;
1946 }
1947 else if (ret == AF_INET) {
1948 p = buffer + 1;
1949 len = strlen(p);
1950 p[len] = ':';
1951 len++;
1952 }
1953 else {
1954 lua_pushnil(L);
1955 return 1;
1956 }
1957
1958 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1959 lua_pushnil(L);
1960 return 1;
1961 }
1962
1963 lua_pushstring(L, p);
1964 return 1;
1965}
1966
1967/* Returns information about the peer of the connection. */
1968__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1969{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001970 struct hlua_socket *socket;
1971 struct connection *conn;
1972
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001973 MAY_LJMP(check_args(L, 1, "getpeername"));
1974
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001975 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001976
1977 /* Check if the tcp object is avalaible. */
1978 if (!socket->s) {
1979 lua_pushnil(L);
1980 return 1;
1981 }
1982
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001983 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001984 if (!conn) {
1985 lua_pushnil(L);
1986 return 1;
1987 }
1988
1989 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1990 unsigned int salen = sizeof(conn->addr.to);
1991 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1992 lua_pushnil(L);
1993 return 1;
1994 }
1995 conn->flags |= CO_FL_ADDR_TO_SET;
1996 }
1997
1998 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1999}
2000
2001/* Returns information about my connection side. */
2002static int hlua_socket_getsockname(struct lua_State *L)
2003{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002004 struct hlua_socket *socket;
2005 struct connection *conn;
2006
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002007 MAY_LJMP(check_args(L, 1, "getsockname"));
2008
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002009 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002010
2011 /* Check if the tcp object is avalaible. */
2012 if (!socket->s) {
2013 lua_pushnil(L);
2014 return 1;
2015 }
2016
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002017 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002018 if (!conn) {
2019 lua_pushnil(L);
2020 return 1;
2021 }
2022
2023 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2024 unsigned int salen = sizeof(conn->addr.from);
2025 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2026 lua_pushnil(L);
2027 return 1;
2028 }
2029 conn->flags |= CO_FL_ADDR_FROM_SET;
2030 }
2031
2032 return hlua_socket_info(L, &conn->addr.from);
2033}
2034
2035/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002036static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002037 .obj_type = OBJ_TYPE_APPLET,
2038 .name = "<LUA_TCP>",
2039 .fct = hlua_socket_handler,
2040 .release = hlua_socket_release,
2041};
2042
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002043__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002044{
2045 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2046 struct hlua *hlua = hlua_gethlua(L);
2047 struct appctx *appctx;
2048
2049 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002050 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002051 lua_pushnil(L);
2052 lua_pushstring(L, "Can't connect");
2053 return 2;
2054 }
2055
2056 appctx = objt_appctx(socket->s->si[0].end);
2057
2058 /* Check for connection established. */
2059 if (appctx->ctx.hlua.connected) {
2060 lua_pushinteger(L, 1);
2061 return 1;
2062 }
2063
2064 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2065 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002066 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002067 return 0;
2068}
2069
2070/* This function fail or initite the connection. */
2071__LJMP static int hlua_socket_connect(struct lua_State *L)
2072{
2073 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002074 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002075 const char *ip;
2076 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002077 struct hlua *hlua;
2078 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002079
2080 MAY_LJMP(check_args(L, 3, "connect"));
2081
2082 /* Get args. */
2083 socket = MAY_LJMP(hlua_checksocket(L, 1));
2084 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002085 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002086
Willy Tarreau973a5422015-08-05 21:47:23 +02002087 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002088 if (!conn)
2089 WILL_LJMP(luaL_error(L, "connect: internal error"));
2090
2091 /* Parse ip address. */
2092 conn->addr.to.ss_family = AF_UNSPEC;
2093 if (!str2ip2(ip, &conn->addr.to, 0))
2094 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
2095
2096 /* Set port. */
2097 if (conn->addr.to.ss_family == AF_INET)
2098 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2099 else if (conn->addr.to.ss_family == AF_INET6)
2100 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2101
2102 /* it is important not to call the wakeup function directly but to
2103 * pass through task_wakeup(), because this one knows how to apply
2104 * priorities to tasks.
2105 */
2106 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
2107
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002108 hlua = hlua_gethlua(L);
2109 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaubdc97a82015-08-24 15:42:28 +02002110
2111 /* inform the stream that we want to be notified whenever the
2112 * connection completes.
2113 */
2114 si_applet_cant_get(&socket->s->si[0]);
2115 si_applet_cant_put(&socket->s->si[0]);
2116
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002117 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2118 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002119 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002120
2121 return 0;
2122}
2123
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002124#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002125__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2126{
2127 struct hlua_socket *socket;
2128
2129 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2130 socket = MAY_LJMP(hlua_checksocket(L, 1));
2131 socket->s->target = &socket_ssl.obj_type;
2132 return MAY_LJMP(hlua_socket_connect(L));
2133}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002134#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002135
2136__LJMP static int hlua_socket_setoption(struct lua_State *L)
2137{
2138 return 0;
2139}
2140
2141__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2142{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002143 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002144 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002145
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002146 MAY_LJMP(check_args(L, 2, "settimeout"));
2147
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002148 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002149 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002150
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002151 socket->s->req.rto = tmout;
2152 socket->s->req.wto = tmout;
2153 socket->s->res.rto = tmout;
2154 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002155
2156 return 0;
2157}
2158
2159__LJMP static int hlua_socket_new(lua_State *L)
2160{
2161 struct hlua_socket *socket;
2162 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002163 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002164 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002165 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002166
2167 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002168 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002169 hlua_pusherror(L, "socket: full stack");
2170 goto out_fail_conf;
2171 }
2172
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002173 /* Create the object: obj[0] = userdata. */
2174 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002175 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002176 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002177 memset(socket, 0, sizeof(*socket));
2178
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002179 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002180 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002181 hlua_pusherror(L, "socket: uninitialized pools.");
2182 goto out_fail_conf;
2183 }
2184
Willy Tarreau87b09662015-04-03 00:22:06 +02002185 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002186 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2187 lua_setmetatable(L, -2);
2188
Willy Tarreaud420a972015-04-06 00:39:18 +02002189 /* Create the applet context */
2190 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002191 if (!appctx) {
2192 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002193 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002194 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002195
Willy Tarreaud420a972015-04-06 00:39:18 +02002196 appctx->ctx.hlua.socket = socket;
2197 appctx->ctx.hlua.connected = 0;
2198 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2199 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002200
Willy Tarreaud420a972015-04-06 00:39:18 +02002201 /* Now create a session, task and stream for this applet */
2202 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2203 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002204 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002205 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002206 }
2207
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002208 task = task_new();
2209 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002210 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002211 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002212 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002213 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002214
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002215 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002216 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002217 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002218 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002219 }
2220
Willy Tarreaud420a972015-04-06 00:39:18 +02002221 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002222 socket->s = strm;
2223 strm->hlua.T = NULL;
2224 strm->hlua.Tref = LUA_REFNIL;
2225 strm->hlua.Mref = LUA_REFNIL;
2226 strm->hlua.nargs = 0;
2227 strm->hlua.flags = 0;
2228 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002229
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002230 /* Configure "right" stream interface. this "si" is used to connect
2231 * and retrieve data from the server. The connection is initialized
2232 * with the "struct server".
2233 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002234 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002235
2236 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002237 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2238 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002239
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002240 /* Update statistics counters. */
2241 socket_proxy.feconn++; /* beconn will be increased later */
2242 jobs++;
2243 totalconn++;
2244
2245 /* Return yield waiting for connection. */
2246 return 1;
2247
Willy Tarreaud420a972015-04-06 00:39:18 +02002248 out_fail_stream:
2249 task_free(task);
2250 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002251 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002252 out_fail_sess:
2253 appctx_free(appctx);
2254 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002255 WILL_LJMP(lua_error(L));
2256 return 0;
2257}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002258
2259/*
2260 *
2261 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002262 * Class Channel
2263 *
2264 *
2265 */
2266
2267/* Returns the struct hlua_channel join to the class channel in the
2268 * stack entry "ud" or throws an argument error.
2269 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002270__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002271{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002272 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002273}
2274
Willy Tarreau47860ed2015-03-10 14:07:50 +01002275/* Pushes the channel onto the top of the stack. If the stask does not have a
2276 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002277 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002278static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002279{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002280 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002281 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002282 return 0;
2283
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002284 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002285 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002286 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002287
2288 /* Pop a class sesison metatable and affect it to the userdata. */
2289 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2290 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002291 return 1;
2292}
2293
2294/* Duplicate all the data present in the input channel and put it
2295 * in a string LUA variables. Returns -1 and push a nil value in
2296 * the stack if the channel is closed and all the data are consumed,
2297 * returns 0 if no data are available, otherwise it returns the length
2298 * of the builded string.
2299 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002300static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002301{
2302 char *blk1;
2303 char *blk2;
2304 int len1;
2305 int len2;
2306 int ret;
2307 luaL_Buffer b;
2308
Willy Tarreau47860ed2015-03-10 14:07:50 +01002309 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002310 if (unlikely(ret == 0))
2311 return 0;
2312
2313 if (unlikely(ret < 0)) {
2314 lua_pushnil(L);
2315 return -1;
2316 }
2317
2318 luaL_buffinit(L, &b);
2319 luaL_addlstring(&b, blk1, len1);
2320 if (unlikely(ret == 2))
2321 luaL_addlstring(&b, blk2, len2);
2322 luaL_pushresult(&b);
2323
2324 if (unlikely(ret == 2))
2325 return len1 + len2;
2326 return len1;
2327}
2328
2329/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2330 * a yield. This function keep the data in the buffer.
2331 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002332__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002333{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002334 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002335
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002336 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2337
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002338 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002339 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002340 return 1;
2341}
2342
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002343/* Check arguments for the function "hlua_channel_dup_yield". */
2344__LJMP static int hlua_channel_dup(lua_State *L)
2345{
2346 MAY_LJMP(check_args(L, 1, "dup"));
2347 MAY_LJMP(hlua_checkchannel(L, 1));
2348 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2349}
2350
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002351/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2352 * a yield. This function consumes the data in the buffer. It returns
2353 * a string containing the data or a nil pointer if no data are available
2354 * and the channel is closed.
2355 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002356__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002357{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002358 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002359 int ret;
2360
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002361 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002362
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002363 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002364 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002365 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002366
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002367 if (unlikely(ret == -1))
2368 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002369
Willy Tarreau47860ed2015-03-10 14:07:50 +01002370 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002371 return 1;
2372}
2373
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002374/* Check arguments for the fucntion "hlua_channel_get_yield". */
2375__LJMP static int hlua_channel_get(lua_State *L)
2376{
2377 MAY_LJMP(check_args(L, 1, "get"));
2378 MAY_LJMP(hlua_checkchannel(L, 1));
2379 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2380}
2381
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002382/* This functions consumes and returns one line. If the channel is closed,
2383 * and the last data does not contains a final '\n', the data are returned
2384 * without the final '\n'. When no more data are avalaible, it returns nil
2385 * value.
2386 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002387__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002388{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002389 char *blk1;
2390 char *blk2;
2391 int len1;
2392 int len2;
2393 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002394 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002395 int ret;
2396 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002397
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002398 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2399
Willy Tarreau47860ed2015-03-10 14:07:50 +01002400 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002401 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002402 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002403
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002404 if (ret == -1) {
2405 lua_pushnil(L);
2406 return 1;
2407 }
2408
2409 luaL_buffinit(L, &b);
2410 luaL_addlstring(&b, blk1, len1);
2411 len = len1;
2412 if (unlikely(ret == 2)) {
2413 luaL_addlstring(&b, blk2, len2);
2414 len += len2;
2415 }
2416 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002417 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002418 return 1;
2419}
2420
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002421/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2422__LJMP static int hlua_channel_getline(lua_State *L)
2423{
2424 MAY_LJMP(check_args(L, 1, "getline"));
2425 MAY_LJMP(hlua_checkchannel(L, 1));
2426 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2427}
2428
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002429/* This function takes a string as input, and append it at the
2430 * input side of channel. If the data is too big, but a space
2431 * is probably available after sending some data, the function
2432 * yield. If the data is bigger than the buffer, or if the
2433 * channel is closed, it returns -1. otherwise, it returns the
2434 * amount of data writed.
2435 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002436__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002437{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002438 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002439 size_t len;
2440 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2441 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2442 int ret;
2443 int max;
2444
Willy Tarreau47860ed2015-03-10 14:07:50 +01002445 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002446 if (max > len - l)
2447 max = len - l;
2448
Willy Tarreau47860ed2015-03-10 14:07:50 +01002449 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002450 if (ret == -2 || ret == -3) {
2451 lua_pushinteger(L, -1);
2452 return 1;
2453 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002454 if (ret == -1) {
2455 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002456 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002457 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002458 l += ret;
2459 lua_pop(L, 1);
2460 lua_pushinteger(L, l);
2461
Willy Tarreau47860ed2015-03-10 14:07:50 +01002462 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2463 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002464 /* There are no space avalaible, and the output buffer is empty.
2465 * in this case, we cannot add more data, so we cannot yield,
2466 * we return the amount of copyied data.
2467 */
2468 return 1;
2469 }
2470 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002471 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002472 return 1;
2473}
2474
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002475/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002476 * of the writed string, or -1 if the channel is closed or if the
2477 * buffer size is too little for the data.
2478 */
2479__LJMP static int hlua_channel_append(lua_State *L)
2480{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002481 size_t len;
2482
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002483 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002484 MAY_LJMP(hlua_checkchannel(L, 1));
2485 MAY_LJMP(luaL_checklstring(L, 2, &len));
2486 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002487 lua_pushinteger(L, 0);
2488
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002489 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002490}
2491
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002492/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002493 * his process by cleaning the buffer. The result is a replacement
2494 * of the current data. It returns the length of the writed string,
2495 * or -1 if the channel is closed or if the buffer size is too
2496 * little for the data.
2497 */
2498__LJMP static int hlua_channel_set(lua_State *L)
2499{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002500 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002501
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002502 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002503 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002504 lua_pushinteger(L, 0);
2505
Willy Tarreau47860ed2015-03-10 14:07:50 +01002506 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002507
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002508 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002509}
2510
2511/* Append data in the output side of the buffer. This data is immediatly
2512 * sent. The fcuntion returns the ammount of data writed. If the buffer
2513 * cannot contains the data, the function yield. The function returns -1
2514 * if the channel is closed.
2515 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002516__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002517{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002518 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002519 size_t len;
2520 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2521 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2522 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002523 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002524
Willy Tarreau47860ed2015-03-10 14:07:50 +01002525 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002526 lua_pushinteger(L, -1);
2527 return 1;
2528 }
2529
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002530 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2531 * the request buffer if its not required.
2532 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002533 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002534 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002535 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002536 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002537 }
2538 }
2539
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002540 /* the writed data will be immediatly sent, so we can check
2541 * the avalaible space without taking in account the reserve.
2542 * The reserve is guaranted for the processing of incoming
2543 * data, because the buffer will be flushed.
2544 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002545 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002546
2547 /* If there are no space avalaible, and the output buffer is empty.
2548 * in this case, we cannot add more data, so we cannot yield,
2549 * we return the amount of copyied data.
2550 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002551 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002552 return 1;
2553
2554 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002555 if (max > len - l)
2556 max = len - l;
2557
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002558 /* The buffer avalaible size may be not contiguous. This test
2559 * detects a non contiguous buffer and realign it.
2560 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002561 if (bi_space_for_replace(chn->buf) < max)
2562 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002563
2564 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002565 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002566
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002567 /* buffer replace considers that the input part is filled.
2568 * so, I must forward these new data in the output part.
2569 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002570 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002571
2572 l += max;
2573 lua_pop(L, 1);
2574 lua_pushinteger(L, l);
2575
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002576 /* If there are no space avalaible, and the output buffer is empty.
2577 * in this case, we cannot add more data, so we cannot yield,
2578 * we return the amount of copyied data.
2579 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002580 max = chn->buf->size - buffer_len(chn->buf);
2581 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002582 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002583
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002584 if (l < len) {
2585 /* If we are waiting for space in the response buffer, we
2586 * must set the flag WAKERESWR. This flag required the task
2587 * wake up if any activity is detected on the response buffer.
2588 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002589 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002590 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002591 else
2592 HLUA_SET_WAKEREQWR(hlua);
2593 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002594 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002595
2596 return 1;
2597}
2598
2599/* Just a wraper of "_hlua_channel_send". This wrapper permits
2600 * yield the LUA process, and resume it without checking the
2601 * input arguments.
2602 */
2603__LJMP static int hlua_channel_send(lua_State *L)
2604{
2605 MAY_LJMP(check_args(L, 2, "send"));
2606 lua_pushinteger(L, 0);
2607
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002608 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002609}
2610
2611/* This function forward and amount of butes. The data pass from
2612 * the input side of the buffer to the output side, and can be
2613 * forwarded. This function never fails.
2614 *
2615 * The Lua function takes an amount of bytes to be forwarded in
2616 * imput. It returns the number of bytes forwarded.
2617 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002618__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002619{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002620 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002621 int len;
2622 int l;
2623 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002624 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002625
2626 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2627 len = MAY_LJMP(luaL_checkinteger(L, 2));
2628 l = MAY_LJMP(luaL_checkinteger(L, -1));
2629
2630 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002631 if (max > chn->buf->i)
2632 max = chn->buf->i;
2633 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002634 l += max;
2635
2636 lua_pop(L, 1);
2637 lua_pushinteger(L, l);
2638
2639 /* Check if it miss bytes to forward. */
2640 if (l < len) {
2641 /* The the input channel or the output channel are closed, we
2642 * must return the amount of data forwarded.
2643 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002644 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002645 return 1;
2646
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002647 /* If we are waiting for space data in the response buffer, we
2648 * must set the flag WAKERESWR. This flag required the task
2649 * wake up if any activity is detected on the response buffer.
2650 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002651 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002652 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002653 else
2654 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002655
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002656 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002657 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002658 }
2659
2660 return 1;
2661}
2662
2663/* Just check the input and prepare the stack for the previous
2664 * function "hlua_channel_forward_yield"
2665 */
2666__LJMP static int hlua_channel_forward(lua_State *L)
2667{
2668 MAY_LJMP(check_args(L, 2, "forward"));
2669 MAY_LJMP(hlua_checkchannel(L, 1));
2670 MAY_LJMP(luaL_checkinteger(L, 2));
2671
2672 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002673 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002674}
2675
2676/* Just returns the number of bytes available in the input
2677 * side of the buffer. This function never fails.
2678 */
2679__LJMP static int hlua_channel_get_in_len(lua_State *L)
2680{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002681 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002682
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002683 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002684 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002685 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002686 return 1;
2687}
2688
2689/* Just returns the number of bytes available in the output
2690 * side of the buffer. This function never fails.
2691 */
2692__LJMP static int hlua_channel_get_out_len(lua_State *L)
2693{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002694 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002695
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002696 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002697 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002698 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002699 return 1;
2700}
2701
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002702/*
2703 *
2704 *
2705 * Class Fetches
2706 *
2707 *
2708 */
2709
2710/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002711 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002712 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002713__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002714{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002715 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002716}
2717
2718/* This function creates and push in the stack a fetch object according
2719 * with a current TXN.
2720 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002721static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002722{
Willy Tarreau7073c472015-04-06 11:15:40 +02002723 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002724
2725 /* Check stack size. */
2726 if (!lua_checkstack(L, 3))
2727 return 0;
2728
2729 /* Create the object: obj[0] = userdata.
2730 * Note that the base of the Fetches object is the
2731 * transaction object.
2732 */
2733 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002734 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002735 lua_rawseti(L, -2, 0);
2736
Willy Tarreau7073c472015-04-06 11:15:40 +02002737 hsmp->s = txn->s;
2738 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002739 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002740
2741 /* Pop a class sesison metatable and affect it to the userdata. */
2742 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2743 lua_setmetatable(L, -2);
2744
2745 return 1;
2746}
2747
2748/* This function is an LUA binding. It is called with each sample-fetch.
2749 * It uses closure argument to store the associated sample-fetch. It
2750 * returns only one argument or throws an error. An error is thrown
2751 * only if an error is encountered during the argument parsing. If
2752 * the "sample-fetch" function fails, nil is returned.
2753 */
2754__LJMP static int hlua_run_sample_fetch(lua_State *L)
2755{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002756 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002757 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002758 struct arg args[ARGM_NBARGS + 1];
2759 int i;
2760 struct sample smp;
2761
2762 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002763 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002764
2765 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002766 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002767
2768 /* Get extra arguments. */
2769 for (i = 0; i < lua_gettop(L) - 1; i++) {
2770 if (i >= ARGM_NBARGS)
2771 break;
2772 hlua_lua2arg(L, i + 2, &args[i]);
2773 }
2774 args[i].type = ARGT_STOP;
2775
2776 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002777 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002778
2779 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002780 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002781 lua_pushfstring(L, "error in arguments");
2782 WILL_LJMP(lua_error(L));
2783 }
2784
2785 /* Initialise the sample. */
2786 memset(&smp, 0, sizeof(smp));
2787
2788 /* Run the sample fetch process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02002789 smp.px = hsmp->p;
2790 smp.sess = hsmp->s->sess;
2791 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002792 smp.opt = 0;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02002793 if (!f->process(args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002794 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002795 lua_pushstring(L, "");
2796 else
2797 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002798 return 1;
2799 }
2800
2801 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002802 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002803 hlua_smp2lua_str(L, &smp);
2804 else
2805 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002806 return 1;
2807}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002808
2809/*
2810 *
2811 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002812 * Class Converters
2813 *
2814 *
2815 */
2816
2817/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002818 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002819 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002820__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002821{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002822 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002823}
2824
2825/* This function creates and push in the stack a Converters object
2826 * according with a current TXN.
2827 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002828static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002829{
Willy Tarreau7073c472015-04-06 11:15:40 +02002830 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002831
2832 /* Check stack size. */
2833 if (!lua_checkstack(L, 3))
2834 return 0;
2835
2836 /* Create the object: obj[0] = userdata.
2837 * Note that the base of the Converters object is the
2838 * same than the TXN object.
2839 */
2840 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002841 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002842 lua_rawseti(L, -2, 0);
2843
Willy Tarreau7073c472015-04-06 11:15:40 +02002844 hsmp->s = txn->s;
2845 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002846 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002847
Willy Tarreau87b09662015-04-03 00:22:06 +02002848 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002849 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2850 lua_setmetatable(L, -2);
2851
2852 return 1;
2853}
2854
2855/* This function is an LUA binding. It is called with each converter.
2856 * It uses closure argument to store the associated converter. It
2857 * returns only one argument or throws an error. An error is thrown
2858 * only if an error is encountered during the argument parsing. If
2859 * the converter function function fails, nil is returned.
2860 */
2861__LJMP static int hlua_run_sample_conv(lua_State *L)
2862{
Willy Tarreauda5f1082015-04-06 11:17:13 +02002863 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002864 struct sample_conv *conv;
2865 struct arg args[ARGM_NBARGS + 1];
2866 int i;
2867 struct sample smp;
2868
2869 /* Get closure arguments. */
2870 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2871
2872 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002873 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002874
2875 /* Get extra arguments. */
2876 for (i = 0; i < lua_gettop(L) - 2; i++) {
2877 if (i >= ARGM_NBARGS)
2878 break;
2879 hlua_lua2arg(L, i + 3, &args[i]);
2880 }
2881 args[i].type = ARGT_STOP;
2882
2883 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002884 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002885
2886 /* Run the special args checker. */
2887 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2888 hlua_pusherror(L, "error in arguments");
2889 WILL_LJMP(lua_error(L));
2890 }
2891
2892 /* Initialise the sample. */
2893 if (!hlua_lua2smp(L, 2, &smp)) {
2894 hlua_pusherror(L, "error in the input argument");
2895 WILL_LJMP(lua_error(L));
2896 }
2897
2898 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002899 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002900 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002901 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002902 WILL_LJMP(lua_error(L));
2903 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002904 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
2905 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002906 hlua_pusherror(L, "error during the input argument casting");
2907 WILL_LJMP(lua_error(L));
2908 }
2909
2910 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02002911 smp.px = hsmp->p;
2912 smp.sess = hsmp->s->sess;
2913 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002914 smp.opt = 0;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02002915 if (!conv->process(args, &smp, conv->private)) {
Willy Tarreauda5f1082015-04-06 11:17:13 +02002916 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002917 lua_pushstring(L, "");
2918 else
2919 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002920 return 1;
2921 }
2922
2923 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002924 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002925 hlua_smp2lua_str(L, &smp);
2926 else
2927 hlua_smp2lua(L, &smp);
2928 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002929}
2930
2931/*
2932 *
2933 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002934 * Class HTTP
2935 *
2936 *
2937 */
2938
2939/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002940 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002941 */
2942__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
2943{
2944 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
2945}
2946
2947/* This function creates and push in the stack a HTTP object
2948 * according with a current TXN.
2949 */
2950static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
2951{
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002952 struct hlua_txn *htxn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002953
2954 /* Check stack size. */
2955 if (!lua_checkstack(L, 3))
2956 return 0;
2957
2958 /* Create the object: obj[0] = userdata.
2959 * Note that the base of the Converters object is the
2960 * same than the TXN object.
2961 */
2962 lua_newtable(L);
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002963 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002964 lua_rawseti(L, -2, 0);
2965
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002966 htxn->s = txn->s;
2967 htxn->p = txn->p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002968
Willy Tarreau87b09662015-04-03 00:22:06 +02002969 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002970 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
2971 lua_setmetatable(L, -2);
2972
2973 return 1;
2974}
2975
2976/* This function creates ans returns an array of HTTP headers.
2977 * This function does not fails. It is used as wrapper with the
2978 * 2 following functions.
2979 */
2980__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
2981{
2982 const char *cur_ptr, *cur_next, *p;
2983 int old_idx, cur_idx;
2984 struct hdr_idx_elem *cur_hdr;
2985 const char *hn, *hv;
2986 int hnl, hvl;
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01002987 int type;
2988 const char *in;
2989 char *out;
2990 int len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002991
2992 /* Create the table. */
2993 lua_newtable(L);
2994
Willy Tarreaueee5b512015-04-03 23:46:31 +02002995 if (!htxn->s->txn)
2996 return 1;
2997
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002998 /* Build array of headers. */
2999 old_idx = 0;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003000 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003001
3002 while (1) {
Willy Tarreaueee5b512015-04-03 23:46:31 +02003003 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003004 if (!cur_idx)
3005 break;
3006 old_idx = cur_idx;
3007
Willy Tarreaueee5b512015-04-03 23:46:31 +02003008 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003009 cur_ptr = cur_next;
3010 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
3011
3012 /* Now we have one full header at cur_ptr of len cur_hdr->len,
3013 * and the next header starts at cur_next. We'll check
3014 * this header in the list as well as against the default
3015 * rule.
3016 */
3017
3018 /* look for ': *'. */
3019 hn = cur_ptr;
3020 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
3021 if (p >= cur_ptr+cur_hdr->len)
3022 continue;
3023 hnl = p - hn;
3024 p++;
3025 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
3026 p++;
3027 if (p >= cur_ptr+cur_hdr->len)
3028 continue;
3029 hv = p;
3030 hvl = cur_ptr+cur_hdr->len-p;
3031
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003032 /* Lowercase the key. Don't check the size of trash, it have
3033 * the size of one buffer and the input data contains in one
3034 * buffer.
3035 */
3036 out = trash.str;
3037 for (in=hn; in<hn+hnl; in++, out++)
3038 *out = tolower(*in);
3039 *out = '\0';
3040
3041 /* Check for existing entry:
3042 * assume that the table is on the top of the stack, and
3043 * push the key in the stack, the function lua_gettable()
3044 * perform the lookup.
3045 */
3046 lua_pushlstring(L, trash.str, hnl);
3047 lua_gettable(L, -2);
3048 type = lua_type(L, -1);
3049
3050 switch (type) {
3051 case LUA_TNIL:
3052 /* Table not found, create it. */
3053 lua_pop(L, 1); /* remove the nil value. */
3054 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
3055 lua_newtable(L); /* create and push empty table. */
3056 lua_pushlstring(L, hv, hvl); /* push header value. */
3057 lua_rawseti(L, -2, 0); /* index header value (pop it). */
3058 lua_rawset(L, -3); /* index new table with header name (pop the values). */
3059 break;
3060
3061 case LUA_TTABLE:
3062 /* Entry found: push the value in the table. */
3063 len = lua_rawlen(L, -1);
3064 lua_pushlstring(L, hv, hvl); /* push header value. */
3065 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
3066 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
3067 break;
3068
3069 default:
3070 /* Other cases are errors. */
3071 hlua_pusherror(L, "internal error during the parsing of headers.");
3072 WILL_LJMP(lua_error(L));
3073 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003074 }
3075
3076 return 1;
3077}
3078
3079__LJMP static int hlua_http_req_get_headers(lua_State *L)
3080{
3081 struct hlua_txn *htxn;
3082
3083 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3084 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3085
Willy Tarreaueee5b512015-04-03 23:46:31 +02003086 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003087}
3088
3089__LJMP static int hlua_http_res_get_headers(lua_State *L)
3090{
3091 struct hlua_txn *htxn;
3092
3093 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3094 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3095
Willy Tarreaueee5b512015-04-03 23:46:31 +02003096 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003097}
3098
3099/* This function replace full header, or just a value in
3100 * the request or in the response. It is a wrapper fir the
3101 * 4 following functions.
3102 */
3103__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3104 struct http_msg *msg, int action)
3105{
3106 size_t name_len;
3107 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3108 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3109 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3110 struct my_regex re;
3111
3112 if (!regex_comp(reg, &re, 1, 1, NULL))
3113 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3114
3115 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3116 regex_free(&re);
3117 return 0;
3118}
3119
3120__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3121{
3122 struct hlua_txn *htxn;
3123
3124 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3125 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3126
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003127 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003128}
3129
3130__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3131{
3132 struct hlua_txn *htxn;
3133
3134 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3135 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3136
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003137 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003138}
3139
3140__LJMP static int hlua_http_req_rep_val(lua_State *L)
3141{
3142 struct hlua_txn *htxn;
3143
3144 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3145 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3146
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003147 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003148}
3149
3150__LJMP static int hlua_http_res_rep_val(lua_State *L)
3151{
3152 struct hlua_txn *htxn;
3153
3154 MAY_LJMP(check_args(L, 4, "res_rep_val"));
3155 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3156
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003157 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003158}
3159
3160/* This function deletes all the occurences of an header.
3161 * It is a wrapper for the 2 following functions.
3162 */
3163__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3164{
3165 size_t len;
3166 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3167 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003168 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003169
3170 ctx.idx = 0;
3171 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3172 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3173 return 0;
3174}
3175
3176__LJMP static int hlua_http_req_del_hdr(lua_State *L)
3177{
3178 struct hlua_txn *htxn;
3179
3180 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3181 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3182
Willy Tarreaueee5b512015-04-03 23:46:31 +02003183 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003184}
3185
3186__LJMP static int hlua_http_res_del_hdr(lua_State *L)
3187{
3188 struct hlua_txn *htxn;
3189
3190 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3191 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3192
Willy Tarreaueee5b512015-04-03 23:46:31 +02003193 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003194}
3195
3196/* This function adds an header. It is a wrapper used by
3197 * the 2 following functions.
3198 */
3199__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3200{
3201 size_t name_len;
3202 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3203 size_t value_len;
3204 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3205 char *p;
3206
3207 /* Check length. */
3208 trash.len = value_len + name_len + 2;
3209 if (trash.len > trash.size)
3210 return 0;
3211
3212 /* Creates the header string. */
3213 p = trash.str;
3214 memcpy(p, name, name_len);
3215 p += name_len;
3216 *p = ':';
3217 p++;
3218 *p = ' ';
3219 p++;
3220 memcpy(p, value, value_len);
3221
Willy Tarreaueee5b512015-04-03 23:46:31 +02003222 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003223 trash.str, trash.len) != 0);
3224
3225 return 0;
3226}
3227
3228__LJMP static int hlua_http_req_add_hdr(lua_State *L)
3229{
3230 struct hlua_txn *htxn;
3231
3232 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3233 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3234
Willy Tarreaueee5b512015-04-03 23:46:31 +02003235 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003236}
3237
3238__LJMP static int hlua_http_res_add_hdr(lua_State *L)
3239{
3240 struct hlua_txn *htxn;
3241
3242 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3243 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3244
Willy Tarreaueee5b512015-04-03 23:46:31 +02003245 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003246}
3247
3248static int hlua_http_req_set_hdr(lua_State *L)
3249{
3250 struct hlua_txn *htxn;
3251
3252 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3253 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3254
Willy Tarreaueee5b512015-04-03 23:46:31 +02003255 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3256 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003257}
3258
3259static int hlua_http_res_set_hdr(lua_State *L)
3260{
3261 struct hlua_txn *htxn;
3262
3263 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3264 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3265
Willy Tarreaueee5b512015-04-03 23:46:31 +02003266 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3267 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003268}
3269
3270/* This function set the method. */
3271static int hlua_http_req_set_meth(lua_State *L)
3272{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003273 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003274 size_t name_len;
3275 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003276
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003277 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003278 return 1;
3279}
3280
3281/* This function set the method. */
3282static int hlua_http_req_set_path(lua_State *L)
3283{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003284 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003285 size_t name_len;
3286 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003287 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003288 return 1;
3289}
3290
3291/* This function set the query-string. */
3292static int hlua_http_req_set_query(lua_State *L)
3293{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003294 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003295 size_t name_len;
3296 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003297
3298 /* Check length. */
3299 if (name_len > trash.size - 1) {
3300 lua_pushboolean(L, 0);
3301 return 1;
3302 }
3303
3304 /* Add the mark question as prefix. */
3305 chunk_reset(&trash);
3306 trash.str[trash.len++] = '?';
3307 memcpy(trash.str + trash.len, name, name_len);
3308 trash.len += name_len;
3309
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003310 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003311 return 1;
3312}
3313
3314/* This function set the uri. */
3315static int hlua_http_req_set_uri(lua_State *L)
3316{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003317 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003318 size_t name_len;
3319 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003320
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003321 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003322 return 1;
3323}
3324
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02003325/* This function set the response code. */
3326static int hlua_http_res_set_status(lua_State *L)
3327{
3328 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3329 unsigned int code = MAY_LJMP(luaL_checkinteger(L, 2));
3330
3331 http_set_status(code, htxn->s);
3332 return 0;
3333}
3334
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003335/*
3336 *
3337 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003338 * Class TXN
3339 *
3340 *
3341 */
3342
3343/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003344 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003345 */
3346__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3347{
3348 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3349}
3350
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02003351__LJMP static int hlua_set_var(lua_State *L)
3352{
3353 struct hlua_txn *htxn;
3354 const char *name;
3355 size_t len;
3356 struct sample smp;
3357
3358 MAY_LJMP(check_args(L, 3, "set_var"));
3359
3360 /* It is useles to retrieve the stream, but this function
3361 * runs only in a stream context.
3362 */
3363 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3364 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3365
3366 /* Converts the third argument in a sample. */
3367 hlua_lua2smp(L, 3, &smp);
3368
3369 /* Store the sample in a variable. */
3370 vars_set_by_name(name, len, htxn->s, &smp);
3371 return 0;
3372}
3373
3374__LJMP static int hlua_get_var(lua_State *L)
3375{
3376 struct hlua_txn *htxn;
3377 const char *name;
3378 size_t len;
3379 struct sample smp;
3380
3381 MAY_LJMP(check_args(L, 2, "get_var"));
3382
3383 /* It is useles to retrieve the stream, but this function
3384 * runs only in a stream context.
3385 */
3386 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3387 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3388
3389 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
3390 lua_pushnil(L);
3391 return 1;
3392 }
3393
3394 return hlua_smp2lua(L, &smp);
3395}
3396
Willy Tarreau59551662015-03-10 14:23:13 +01003397__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003398{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003399 struct hlua *hlua;
3400
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003401 MAY_LJMP(check_args(L, 2, "set_priv"));
3402
Willy Tarreau87b09662015-04-03 00:22:06 +02003403 /* It is useles to retrieve the stream, but this function
3404 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003405 */
3406 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003407 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003408
3409 /* Remove previous value. */
3410 if (hlua->Mref != -1)
3411 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3412
3413 /* Get and store new value. */
3414 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3415 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3416
3417 return 0;
3418}
3419
Willy Tarreau59551662015-03-10 14:23:13 +01003420__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003421{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003422 struct hlua *hlua;
3423
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003424 MAY_LJMP(check_args(L, 1, "get_priv"));
3425
Willy Tarreau87b09662015-04-03 00:22:06 +02003426 /* It is useles to retrieve the stream, but this function
3427 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003428 */
3429 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003430 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003431
3432 /* Push configuration index in the stack. */
3433 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3434
3435 return 1;
3436}
3437
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003438/* Create stack entry containing a class TXN. This function
3439 * return 0 if the stack does not contains free slots,
3440 * otherwise it returns 1.
3441 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003442static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003443{
Willy Tarreaude491382015-04-06 11:04:28 +02003444 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003445
3446 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003447 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003448 return 0;
3449
3450 /* NOTE: The allocation never fails. The failure
3451 * throw an error, and the function never returns.
3452 * if the throw is not avalaible, the process is aborted.
3453 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003454 /* Create the object: obj[0] = userdata. */
3455 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02003456 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003457 lua_rawseti(L, -2, 0);
3458
Willy Tarreaude491382015-04-06 11:04:28 +02003459 htxn->s = s;
3460 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003461
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003462 /* Create the "f" field that contains a list of fetches. */
3463 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02003464 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003465 return 0;
3466 lua_settable(L, -3);
3467
3468 /* Create the "sf" field that contains a list of stringsafe fetches. */
3469 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02003470 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003471 return 0;
3472 lua_settable(L, -3);
3473
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003474 /* Create the "c" field that contains a list of converters. */
3475 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02003476 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003477 return 0;
3478 lua_settable(L, -3);
3479
3480 /* Create the "sc" field that contains a list of stringsafe converters. */
3481 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02003482 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003483 return 0;
3484 lua_settable(L, -3);
3485
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003486 /* Create the "req" field that contains the request channel object. */
3487 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003488 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003489 return 0;
3490 lua_settable(L, -3);
3491
3492 /* Create the "res" field that contains the response channel object. */
3493 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003494 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003495 return 0;
3496 lua_settable(L, -3);
3497
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003498 /* Creates the HTTP object is the current proxy allows http. */
3499 lua_pushstring(L, "http");
3500 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02003501 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003502 return 0;
3503 }
3504 else
3505 lua_pushnil(L);
3506 lua_settable(L, -3);
3507
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003508 /* Pop a class sesison metatable and affect it to the userdata. */
3509 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3510 lua_setmetatable(L, -2);
3511
3512 return 1;
3513}
3514
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003515__LJMP static int hlua_txn_deflog(lua_State *L)
3516{
3517 const char *msg;
3518 struct hlua_txn *htxn;
3519
3520 MAY_LJMP(check_args(L, 2, "deflog"));
3521 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3522 msg = MAY_LJMP(luaL_checkstring(L, 2));
3523
3524 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3525 return 0;
3526}
3527
3528__LJMP static int hlua_txn_log(lua_State *L)
3529{
3530 int level;
3531 const char *msg;
3532 struct hlua_txn *htxn;
3533
3534 MAY_LJMP(check_args(L, 3, "log"));
3535 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3536 level = MAY_LJMP(luaL_checkinteger(L, 2));
3537 msg = MAY_LJMP(luaL_checkstring(L, 3));
3538
3539 if (level < 0 || level >= NB_LOG_LEVELS)
3540 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3541
3542 hlua_sendlog(htxn->s->be, level, msg);
3543 return 0;
3544}
3545
3546__LJMP static int hlua_txn_log_debug(lua_State *L)
3547{
3548 const char *msg;
3549 struct hlua_txn *htxn;
3550
3551 MAY_LJMP(check_args(L, 2, "Debug"));
3552 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3553 msg = MAY_LJMP(luaL_checkstring(L, 2));
3554 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3555 return 0;
3556}
3557
3558__LJMP static int hlua_txn_log_info(lua_State *L)
3559{
3560 const char *msg;
3561 struct hlua_txn *htxn;
3562
3563 MAY_LJMP(check_args(L, 2, "Info"));
3564 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3565 msg = MAY_LJMP(luaL_checkstring(L, 2));
3566 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3567 return 0;
3568}
3569
3570__LJMP static int hlua_txn_log_warning(lua_State *L)
3571{
3572 const char *msg;
3573 struct hlua_txn *htxn;
3574
3575 MAY_LJMP(check_args(L, 2, "Warning"));
3576 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3577 msg = MAY_LJMP(luaL_checkstring(L, 2));
3578 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3579 return 0;
3580}
3581
3582__LJMP static int hlua_txn_log_alert(lua_State *L)
3583{
3584 const char *msg;
3585 struct hlua_txn *htxn;
3586
3587 MAY_LJMP(check_args(L, 2, "Alert"));
3588 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3589 msg = MAY_LJMP(luaL_checkstring(L, 2));
3590 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3591 return 0;
3592}
3593
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003594__LJMP static int hlua_txn_set_loglevel(lua_State *L)
3595{
3596 struct hlua_txn *htxn;
3597 int ll;
3598
3599 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3600 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3601 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3602
3603 if (ll < 0 || ll > 7)
3604 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3605
3606 htxn->s->logs.level = ll;
3607 return 0;
3608}
3609
3610__LJMP static int hlua_txn_set_tos(lua_State *L)
3611{
3612 struct hlua_txn *htxn;
3613 struct connection *cli_conn;
3614 int tos;
3615
3616 MAY_LJMP(check_args(L, 2, "set_tos"));
3617 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3618 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3619
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003620 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003621 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3622
3623 return 0;
3624}
3625
3626__LJMP static int hlua_txn_set_mark(lua_State *L)
3627{
3628#ifdef SO_MARK
3629 struct hlua_txn *htxn;
3630 struct connection *cli_conn;
3631 int mark;
3632
3633 MAY_LJMP(check_args(L, 2, "set_mark"));
3634 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3635 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3636
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003637 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02003638 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003639#endif
3640 return 0;
3641}
3642
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003643/* This function is an Lua binding that send pending data
3644 * to the client, and close the stream interface.
3645 */
3646__LJMP static int hlua_txn_close(lua_State *L)
3647{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003648 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01003649 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003650
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003651 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003652 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003653
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003654 ic = &htxn->s->req;
3655 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01003656
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003657 channel_auto_read(ic);
Willy Tarreau81389672015-03-10 12:03:52 +01003658 channel_abort(ic);
3659 channel_auto_close(ic);
3660 channel_erase(ic);
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003661
3662 oc->wex = tick_add_ifset(now_ms, oc->wto);
Willy Tarreau81389672015-03-10 12:03:52 +01003663 channel_auto_read(oc);
3664 channel_auto_close(oc);
3665 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003666
Thierry FOURNIER10ec2142015-08-24 17:23:45 +02003667 htxn->s->txn->req.chn->analysers = 0;
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003668 return 0;
3669}
3670
3671__LJMP static int hlua_log(lua_State *L)
3672{
3673 int level;
3674 const char *msg;
3675
3676 MAY_LJMP(check_args(L, 2, "log"));
3677 level = MAY_LJMP(luaL_checkinteger(L, 1));
3678 msg = MAY_LJMP(luaL_checkstring(L, 2));
3679
3680 if (level < 0 || level >= NB_LOG_LEVELS)
3681 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3682
3683 hlua_sendlog(NULL, level, msg);
3684 return 0;
3685}
3686
3687__LJMP static int hlua_log_debug(lua_State *L)
3688{
3689 const char *msg;
3690
3691 MAY_LJMP(check_args(L, 1, "debug"));
3692 msg = MAY_LJMP(luaL_checkstring(L, 1));
3693 hlua_sendlog(NULL, LOG_DEBUG, msg);
3694 return 0;
3695}
3696
3697__LJMP static int hlua_log_info(lua_State *L)
3698{
3699 const char *msg;
3700
3701 MAY_LJMP(check_args(L, 1, "info"));
3702 msg = MAY_LJMP(luaL_checkstring(L, 1));
3703 hlua_sendlog(NULL, LOG_INFO, msg);
3704 return 0;
3705}
3706
3707__LJMP static int hlua_log_warning(lua_State *L)
3708{
3709 const char *msg;
3710
3711 MAY_LJMP(check_args(L, 1, "warning"));
3712 msg = MAY_LJMP(luaL_checkstring(L, 1));
3713 hlua_sendlog(NULL, LOG_WARNING, msg);
3714 return 0;
3715}
3716
3717__LJMP static int hlua_log_alert(lua_State *L)
3718{
3719 const char *msg;
3720
3721 MAY_LJMP(check_args(L, 1, "alert"));
3722 msg = MAY_LJMP(luaL_checkstring(L, 1));
3723 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003724 return 0;
3725}
3726
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003727__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003728{
3729 int wakeup_ms = lua_tointeger(L, -1);
3730 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003731 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003732 return 0;
3733}
3734
3735__LJMP static int hlua_sleep(lua_State *L)
3736{
3737 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003738 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003739
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003740 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003741
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003742 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003743 wakeup_ms = tick_add(now_ms, delay);
3744 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003745
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003746 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3747 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003748}
3749
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003750__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003751{
3752 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003753 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003754
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003755 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003756
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003757 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003758 wakeup_ms = tick_add(now_ms, delay);
3759 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003760
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003761 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3762 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003763}
3764
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003765/* This functionis an LUA binding. it permits to give back
3766 * the hand at the HAProxy scheduler. It is used when the
3767 * LUA processing consumes a lot of time.
3768 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003769__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003770{
3771 return 0;
3772}
3773
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003774__LJMP static int hlua_yield(lua_State *L)
3775{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003776 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3777 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003778}
3779
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003780/* This function change the nice of the currently executed
3781 * task. It is used set low or high priority at the current
3782 * task.
3783 */
Willy Tarreau59551662015-03-10 14:23:13 +01003784__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003785{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003786 struct hlua *hlua;
3787 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003788
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003789 MAY_LJMP(check_args(L, 1, "set_nice"));
3790 hlua = hlua_gethlua(L);
3791 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003792
3793 /* If he task is not set, I'm in a start mode. */
3794 if (!hlua || !hlua->task)
3795 return 0;
3796
3797 if (nice < -1024)
3798 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003799 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003800 nice = 1024;
3801
3802 hlua->task->nice = nice;
3803 return 0;
3804}
3805
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003806/* This function is used as a calback of a task. It is called by the
3807 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3808 * return an E_AGAIN signal, the emmiter of this signal must set a
3809 * signal to wake the task.
3810 */
3811static struct task *hlua_process_task(struct task *task)
3812{
3813 struct hlua *hlua = task->context;
3814 enum hlua_exec status;
3815
3816 /* We need to remove the task from the wait queue before executing
3817 * the Lua code because we don't know if it needs to wait for
3818 * another timer or not in the case of E_AGAIN.
3819 */
3820 task_delete(task);
3821
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003822 /* If it is the first call to the task, we must initialize the
3823 * execution timeouts.
3824 */
3825 if (!HLUA_IS_RUNNING(hlua))
Camilo Lopez685c0142015-08-02 19:07:28 -04003826 hlua->expire = tick_add_ifset(now_ms, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003827
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003828 /* Execute the Lua code. */
3829 status = hlua_ctx_resume(hlua, 1);
3830
3831 switch (status) {
3832 /* finished or yield */
3833 case HLUA_E_OK:
3834 hlua_ctx_destroy(hlua);
3835 task_delete(task);
3836 task_free(task);
3837 break;
3838
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003839 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3840 if (hlua->wake_time != TICK_ETERNITY)
3841 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003842 break;
3843
3844 /* finished with error. */
3845 case HLUA_E_ERRMSG:
3846 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3847 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3848 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3849 hlua_ctx_destroy(hlua);
3850 task_delete(task);
3851 task_free(task);
3852 break;
3853
3854 case HLUA_E_ERR:
3855 default:
3856 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3857 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3858 Alert("Lua task: unknown error.\n");
3859 hlua_ctx_destroy(hlua);
3860 task_delete(task);
3861 task_free(task);
3862 break;
3863 }
3864 return NULL;
3865}
3866
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003867/* This function is an LUA binding that register LUA function to be
3868 * executed after the HAProxy configuration parsing and before the
3869 * HAProxy scheduler starts. This function expect only one LUA
3870 * argument that is a function. This function returns nothing, but
3871 * throws if an error is encountered.
3872 */
3873__LJMP static int hlua_register_init(lua_State *L)
3874{
3875 struct hlua_init_function *init;
3876 int ref;
3877
3878 MAY_LJMP(check_args(L, 1, "register_init"));
3879
3880 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3881
3882 init = malloc(sizeof(*init));
3883 if (!init)
3884 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3885
3886 init->function_ref = ref;
3887 LIST_ADDQ(&hlua_init_functions, &init->l);
3888 return 0;
3889}
3890
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003891/* This functio is an LUA binding. It permits to register a task
3892 * executed in parallel of the main HAroxy activity. The task is
3893 * created and it is set in the HAProxy scheduler. It can be called
3894 * from the "init" section, "post init" or during the runtime.
3895 *
3896 * Lua prototype:
3897 *
3898 * <none> core.register_task(<function>)
3899 */
3900static int hlua_register_task(lua_State *L)
3901{
3902 struct hlua *hlua;
3903 struct task *task;
3904 int ref;
3905
3906 MAY_LJMP(check_args(L, 1, "register_task"));
3907
3908 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3909
3910 hlua = malloc(sizeof(*hlua));
3911 if (!hlua)
3912 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3913
3914 task = task_new();
3915 task->context = hlua;
3916 task->process = hlua_process_task;
3917
3918 if (!hlua_ctx_init(hlua, task))
3919 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3920
3921 /* Restore the function in the stack. */
3922 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3923 hlua->nargs = 0;
3924
3925 /* Schedule task. */
3926 task_schedule(task, now_ms);
3927
3928 return 0;
3929}
3930
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003931/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3932 * doesn't allow "yield" functions because the HAProxy engine cannot
3933 * resume converters.
3934 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003935static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003936{
3937 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003938 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003939
Willy Tarreau87b09662015-04-03 00:22:06 +02003940 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003941 * Lua context can be not initialized. This behavior
3942 * permits to save performances because a systematic
3943 * Lua initialization cause 5% performances loss.
3944 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003945 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
3946 send_log(stream->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003947 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3948 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3949 return 0;
3950 }
3951
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003952 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003953 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003954 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003955 if (!lua_checkstack(stream->hlua.T, 1)) {
3956 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003957 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3958 Alert("Lua converter '%s': full stack.\n", fcn->name);
3959 return 0;
3960 }
3961
3962 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003963 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003964
3965 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003966 if (!lua_checkstack(stream->hlua.T, 1)) {
3967 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003968 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3969 Alert("Lua converter '%s': full stack.\n", fcn->name);
3970 return 0;
3971 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003972 hlua_smp2lua(stream->hlua.T, smp);
3973 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003974
3975 /* push keywords in the stack. */
3976 if (arg_p) {
3977 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02003978 if (!lua_checkstack(stream->hlua.T, 1)) {
3979 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003980 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3981 Alert("Lua converter '%s': full stack.\n", fcn->name);
3982 return 0;
3983 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003984 hlua_arg2lua(stream->hlua.T, arg_p);
3985 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003986 }
3987 }
3988
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003989 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02003990 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003991
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003992 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003993 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003994 }
3995
3996 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003997 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003998 /* finished. */
3999 case HLUA_E_OK:
4000 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004001 hlua_lua2smp(stream->hlua.T, -1, smp);
4002 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004003 return 1;
4004
4005 /* yield. */
4006 case HLUA_E_AGAIN:
Willy Tarreau87b09662015-04-03 00:22:06 +02004007 send_log(stream->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004008 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4009 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
4010 return 0;
4011
4012 /* finished with error. */
4013 case HLUA_E_ERRMSG:
4014 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004015 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 +01004016 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Willy Tarreau87b09662015-04-03 00:22:06 +02004017 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
4018 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004019 return 0;
4020
4021 case HLUA_E_ERR:
4022 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02004023 send_log(stream->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004024 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4025 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
4026
4027 default:
4028 return 0;
4029 }
4030}
4031
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004032/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
4033 * doesn't allow "yield" functions because the HAProxy engine cannot
4034 * resume sample-fetches.
4035 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02004036static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
4037 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004038{
4039 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004040 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004041
Willy Tarreau87b09662015-04-03 00:22:06 +02004042 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004043 * Lua context can be not initialized. This behavior
4044 * permits to save performances because a systematic
4045 * Lua initialization cause 5% performances loss.
4046 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004047 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
4048 send_log(stream->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004049 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4050 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
4051 return 0;
4052 }
4053
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004054 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004055 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004056 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004057 if (!lua_checkstack(stream->hlua.T, 2)) {
4058 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004059 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4060 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4061 return 0;
4062 }
4063
4064 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004065 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004066
4067 /* push arguments in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004068 if (!hlua_txn_new(stream->hlua.T, stream, smp->px)) {
4069 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004070 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4071 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4072 return 0;
4073 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004074 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004075
4076 /* push keywords in the stack. */
4077 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
4078 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004079 if (!lua_checkstack(stream->hlua.T, 1)) {
4080 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004081 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4082 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4083 return 0;
4084 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004085 if (!lua_checkstack(stream->hlua.T, 1)) {
4086 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004087 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4088 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4089 return 0;
4090 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004091 hlua_arg2lua(stream->hlua.T, arg_p);
4092 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004093 }
4094
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004095 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004096 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004097
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004098 /* Set the currently running flag. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004099 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004100 }
4101
4102 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004103 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004104 /* finished. */
4105 case HLUA_E_OK:
4106 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004107 hlua_lua2smp(stream->hlua.T, -1, smp);
4108 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004109
4110 /* Set the end of execution flag. */
4111 smp->flags &= ~SMP_F_MAY_CHANGE;
4112 return 1;
4113
4114 /* yield. */
4115 case HLUA_E_AGAIN:
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004116 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004117 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4118 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
4119 return 0;
4120
4121 /* finished with error. */
4122 case HLUA_E_ERRMSG:
4123 /* Display log. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004124 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 +01004125 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004126 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
4127 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004128 return 0;
4129
4130 case HLUA_E_ERR:
4131 /* Display log. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004132 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004133 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4134 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
4135
4136 default:
4137 return 0;
4138 }
4139}
4140
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004141/* This function is an LUA binding used for registering
4142 * "sample-conv" functions. It expects a converter name used
4143 * in the haproxy configuration file, and an LUA function.
4144 */
4145__LJMP static int hlua_register_converters(lua_State *L)
4146{
4147 struct sample_conv_kw_list *sck;
4148 const char *name;
4149 int ref;
4150 int len;
4151 struct hlua_function *fcn;
4152
4153 MAY_LJMP(check_args(L, 2, "register_converters"));
4154
4155 /* First argument : converter name. */
4156 name = MAY_LJMP(luaL_checkstring(L, 1));
4157
4158 /* Second argument : lua function. */
4159 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4160
4161 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004162 sck = malloc(sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004163 if (!sck)
4164 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4165 fcn = malloc(sizeof(*fcn));
4166 if (!fcn)
4167 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4168
4169 /* Fill fcn. */
4170 fcn->name = strdup(name);
4171 if (!fcn->name)
4172 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4173 fcn->function_ref = ref;
4174
4175 /* List head */
4176 sck->list.n = sck->list.p = NULL;
4177
4178 /* converter keyword. */
4179 len = strlen("lua.") + strlen(name) + 1;
4180 sck->kw[0].kw = malloc(len);
4181 if (!sck->kw[0].kw)
4182 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4183
4184 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4185 sck->kw[0].process = hlua_sample_conv_wrapper;
4186 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4187 sck->kw[0].val_args = NULL;
4188 sck->kw[0].in_type = SMP_T_STR;
4189 sck->kw[0].out_type = SMP_T_STR;
4190 sck->kw[0].private = fcn;
4191
4192 /* End of array. */
4193 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
4194
4195 /* Register this new converter */
4196 sample_register_convs(sck);
4197
4198 return 0;
4199}
4200
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004201/* This fucntion is an LUA binding used for registering
4202 * "sample-fetch" functions. It expects a converter name used
4203 * in the haproxy configuration file, and an LUA function.
4204 */
4205__LJMP static int hlua_register_fetches(lua_State *L)
4206{
4207 const char *name;
4208 int ref;
4209 int len;
4210 struct sample_fetch_kw_list *sfk;
4211 struct hlua_function *fcn;
4212
4213 MAY_LJMP(check_args(L, 2, "register_fetches"));
4214
4215 /* First argument : sample-fetch name. */
4216 name = MAY_LJMP(luaL_checkstring(L, 1));
4217
4218 /* Second argument : lua function. */
4219 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4220
4221 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004222 sfk = malloc(sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004223 if (!sfk)
4224 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4225 fcn = malloc(sizeof(*fcn));
4226 if (!fcn)
4227 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4228
4229 /* Fill fcn. */
4230 fcn->name = strdup(name);
4231 if (!fcn->name)
4232 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4233 fcn->function_ref = ref;
4234
4235 /* List head */
4236 sfk->list.n = sfk->list.p = NULL;
4237
4238 /* sample-fetch keyword. */
4239 len = strlen("lua.") + strlen(name) + 1;
4240 sfk->kw[0].kw = malloc(len);
4241 if (!sfk->kw[0].kw)
4242 return luaL_error(L, "lua out of memory error.");
4243
4244 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4245 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4246 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4247 sfk->kw[0].val_args = NULL;
4248 sfk->kw[0].out_type = SMP_T_STR;
4249 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4250 sfk->kw[0].val = 0;
4251 sfk->kw[0].private = fcn;
4252
4253 /* End of array. */
4254 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
4255
4256 /* Register this new fetch. */
4257 sample_register_fetches(sfk);
4258
4259 return 0;
4260}
4261
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004262/* This function is a wrapper to execute each LUA function declared
4263 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004264 * return ACT_RET_CONT if the processing is finished (with or without
4265 * error) and return ACT_RET_YIELD if the function must be called again
4266 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004267 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004268static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
4269 struct session *sess, struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004270{
4271 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004272 unsigned int analyzer;
4273
4274 switch (rule->from) {
4275 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; break;
4276 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; break;
4277 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; break;
4278 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; break;
4279 default:
4280 send_log(px, LOG_ERR, "Lua: internal error while execute action.");
4281 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4282 Alert("Lua: internal error while execute action.\n");
4283 return ACT_RET_CONT;
4284 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004285
Willy Tarreau87b09662015-04-03 00:22:06 +02004286 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004287 * Lua context can be not initialized. This behavior
4288 * permits to save performances because a systematic
4289 * Lua initialization cause 5% performances loss.
4290 */
4291 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004292 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.",
4293 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004294 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004295 Alert("Lua action '%s': can't initialize Lua context.\n",
4296 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004297 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004298 }
4299
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004300 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004301 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004302 /* Check stack available size. */
4303 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004304 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4305 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004306 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004307 Alert("Lua function '%s': full stack.\n",
4308 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004309 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004310 }
4311
4312 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004313 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004314
Willy Tarreau87b09662015-04-03 00:22:06 +02004315 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004316 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004317 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4318 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004319 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004320 Alert("Lua function '%s': full stack.\n",
4321 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004322 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004323 }
4324 s->hlua.nargs = 1;
4325
4326 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004327 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004328 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004329 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4330 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004331 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004332 Alert("Lua function '%s': full stack.\n",
4333 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004334 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004335 }
4336 lua_pushstring(s->hlua.T, *arg);
4337 s->hlua.nargs++;
4338 }
4339
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004340 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004341 s->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004342
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004343 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004344 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004345 }
4346
4347 /* Execute the function. */
4348 switch (hlua_ctx_resume(&s->hlua, 1)) {
4349 /* finished. */
4350 case HLUA_E_OK:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004351 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004352
4353 /* yield. */
4354 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004355 /* Set timeout in the required channel. */
4356 if (s->hlua.wake_time != TICK_ETERNITY) {
4357 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004358 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004359 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004360 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004361 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004362 /* Some actions can be wake up when a "write" event
4363 * is detected on a response channel. This is useful
4364 * only for actions targetted on the requests.
4365 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004366 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004367 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01004368 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004369 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004370 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004371 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004372 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004373 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004374
4375 /* finished with error. */
4376 case HLUA_E_ERRMSG:
4377 /* Display log. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004378 send_log(px, LOG_ERR, "Lua function '%s': %s.",
4379 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004380 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004381 Alert("Lua function '%s': %s.\n",
4382 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004383 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004384 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004385
4386 case HLUA_E_ERR:
4387 /* Display log. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004388 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.",
4389 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004390 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004391 Alert("Lua function '%s' return an unknown error.\n",
4392 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004393
4394 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004395 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004396 }
4397}
4398
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004399/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
4400 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004401 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004402static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4403 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004404{
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004405 /* Memory for the rule. */
4406 rule->arg.hlua_rule = malloc(sizeof(*rule->arg.hlua_rule));
4407 if (!rule->arg.hlua_rule) {
4408 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004409 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004410 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004411
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004412 /* The requiered arg is a function name. */
4413 if (!args[*cur_arg]) {
4414 memprintf(err, "expect Lua function name");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004415 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004416 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004417
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004418 /* Lookup for the symbol, and check if it is a function. */
4419 lua_getglobal(gL.T, args[*cur_arg]);
4420 if (lua_isnil(gL.T, -1)) {
4421 lua_pop(gL.T, 1);
4422 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004423 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004424 }
4425 if (!lua_isfunction(gL.T, -1)) {
4426 lua_pop(gL.T, 1);
4427 memprintf(err, "'%s' is not a function", args[*cur_arg]);
4428 return ACT_RET_PRS_ERR;
4429 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004430
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004431 /* Reference the Lua function and store the reference. */
4432 rule->arg.hlua_rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
4433 rule->arg.hlua_rule->fcn.name = strdup(args[*cur_arg]);
4434 if (!rule->arg.hlua_rule->fcn.name) {
4435 memprintf(err, "out of memory error.");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004436 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004437 }
4438 (*cur_arg)++;
4439
4440 /* TODO: later accept arguments. */
4441 rule->arg.hlua_rule->args = NULL;
4442
Thierry FOURNIER91f6ba02015-08-06 08:30:11 +02004443 rule->action = ACT_ACTION_CONT;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004444 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004445 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004446}
4447
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004448static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4449 struct proxy *defpx, const char *file, int line,
4450 char **err, unsigned int *timeout)
4451{
4452 const char *error;
4453
4454 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4455 if (error && *error != '\0') {
4456 memprintf(err, "%s: invalid timeout", args[0]);
4457 return -1;
4458 }
4459 return 0;
4460}
4461
4462static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4463 struct proxy *defpx, const char *file, int line,
4464 char **err)
4465{
4466 return hlua_read_timeout(args, section_type, curpx, defpx,
4467 file, line, err, &hlua_timeout_session);
4468}
4469
4470static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4471 struct proxy *defpx, const char *file, int line,
4472 char **err)
4473{
4474 return hlua_read_timeout(args, section_type, curpx, defpx,
4475 file, line, err, &hlua_timeout_task);
4476}
4477
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004478static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4479 struct proxy *defpx, const char *file, int line,
4480 char **err)
4481{
4482 char *error;
4483
4484 hlua_nb_instruction = strtoll(args[1], &error, 10);
4485 if (*error != '\0') {
4486 memprintf(err, "%s: invalid number", args[0]);
4487 return -1;
4488 }
4489 return 0;
4490}
4491
Willy Tarreau32f61e22015-03-18 17:54:59 +01004492static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4493 struct proxy *defpx, const char *file, int line,
4494 char **err)
4495{
4496 char *error;
4497
4498 if (*(args[1]) == 0) {
4499 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4500 return -1;
4501 }
4502 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4503 if (*error != '\0') {
4504 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4505 return -1;
4506 }
4507 return 0;
4508}
4509
4510
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004511/* This function is called by the main configuration key "lua-load". It loads and
4512 * execute an lua file during the parsing of the HAProxy configuration file. It is
4513 * the main lua entry point.
4514 *
4515 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4516 * occured, otherwise it returns 0.
4517 *
4518 * In some error case, LUA set an error message in top of the stack. This function
4519 * returns this error message in the HAProxy logs and pop it from the stack.
4520 */
4521static int hlua_load(char **args, int section_type, struct proxy *curpx,
4522 struct proxy *defpx, const char *file, int line,
4523 char **err)
4524{
4525 int error;
4526
4527 /* Just load and compile the file. */
4528 error = luaL_loadfile(gL.T, args[1]);
4529 if (error) {
4530 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4531 lua_pop(gL.T, 1);
4532 return -1;
4533 }
4534
4535 /* If no syntax error where detected, execute the code. */
4536 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4537 switch (error) {
4538 case LUA_OK:
4539 break;
4540 case LUA_ERRRUN:
4541 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4542 lua_pop(gL.T, 1);
4543 return -1;
4544 case LUA_ERRMEM:
4545 memprintf(err, "lua out of memory error\n");
4546 return -1;
4547 case LUA_ERRERR:
4548 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4549 lua_pop(gL.T, 1);
4550 return -1;
4551 case LUA_ERRGCMM:
4552 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4553 lua_pop(gL.T, 1);
4554 return -1;
4555 default:
4556 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4557 lua_pop(gL.T, 1);
4558 return -1;
4559 }
4560
4561 return 0;
4562}
4563
4564/* configuration keywords declaration */
4565static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004566 { CFG_GLOBAL, "lua-load", hlua_load },
4567 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4568 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004569 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01004570 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004571 { 0, NULL, NULL },
4572}};
4573
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004574static struct action_kw_list http_req_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004575 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004576 { NULL, NULL }
4577}};
4578
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004579static struct action_kw_list http_res_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004580 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004581 { NULL, NULL }
4582}};
4583
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004584static struct action_kw_list tcp_req_cont_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004585 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004586 { NULL, NULL }
4587}};
4588
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004589static struct action_kw_list tcp_res_cont_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004590 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004591 { NULL, NULL }
4592}};
4593
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004594int hlua_post_init()
4595{
4596 struct hlua_init_function *init;
4597 const char *msg;
4598 enum hlua_exec ret;
4599
4600 list_for_each_entry(init, &hlua_init_functions, l) {
4601 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4602 ret = hlua_ctx_resume(&gL, 0);
4603 switch (ret) {
4604 case HLUA_E_OK:
4605 lua_pop(gL.T, -1);
4606 return 1;
4607 case HLUA_E_AGAIN:
4608 Alert("lua init: yield not allowed.\n");
4609 return 0;
4610 case HLUA_E_ERRMSG:
4611 msg = lua_tostring(gL.T, -1);
4612 Alert("lua init: %s.\n", msg);
4613 return 0;
4614 case HLUA_E_ERR:
4615 default:
4616 Alert("lua init: unknown runtime error.\n");
4617 return 0;
4618 }
4619 }
4620 return 1;
4621}
4622
Willy Tarreau32f61e22015-03-18 17:54:59 +01004623/* The memory allocator used by the Lua stack. <ud> is a pointer to the
4624 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4625 * is the previously allocated size or the kind of object in case of a new
4626 * allocation. <nsize> is the requested new size.
4627 */
4628static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4629{
4630 struct hlua_mem_allocator *zone = ud;
4631
4632 if (nsize == 0) {
4633 /* it's a free */
4634 if (ptr)
4635 zone->allocated -= osize;
4636 free(ptr);
4637 return NULL;
4638 }
4639
4640 if (!ptr) {
4641 /* it's a new allocation */
4642 if (zone->limit && zone->allocated + nsize > zone->limit)
4643 return NULL;
4644
4645 ptr = malloc(nsize);
4646 if (ptr)
4647 zone->allocated += nsize;
4648 return ptr;
4649 }
4650
4651 /* it's a realloc */
4652 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4653 return NULL;
4654
4655 ptr = realloc(ptr, nsize);
4656 if (ptr)
4657 zone->allocated += nsize - osize;
4658 return ptr;
4659}
4660
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004661void hlua_init(void)
4662{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004663 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004664 int idx;
4665 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004666 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004667 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004668#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004669 struct srv_kw *kw;
4670 int tmp_error;
4671 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01004672 char *args[] = { /* SSL client configuration. */
4673 "ssl",
4674 "verify",
4675 "none",
4676 "force-sslv3",
4677 NULL
4678 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004679#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004680
Willy Tarreau87b09662015-04-03 00:22:06 +02004681 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004682 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4683
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004684 /* Register configuration keywords. */
4685 cfg_register_keywords(&cfg_kws);
4686
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004687 /* Register custom HTTP rules. */
4688 http_req_keywords_register(&http_req_kws);
4689 http_res_keywords_register(&http_res_kws);
4690 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
4691 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
4692
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004693 /* Init main lua stack. */
4694 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004695 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004696 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004697 gL.T = luaL_newstate();
4698 hlua_sethlua(&gL);
4699 gL.Tref = LUA_REFNIL;
4700 gL.task = NULL;
4701
Willy Tarreau32f61e22015-03-18 17:54:59 +01004702 /* change the memory allocators to track memory usage */
4703 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4704
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004705 /* Initialise lua. */
4706 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004707
4708 /*
4709 *
4710 * Create "core" object.
4711 *
4712 */
4713
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004714 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004715 lua_newtable(gL.T);
4716
4717 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004718 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004719 hlua_class_const_int(gL.T, log_levels[i], i);
4720
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004721 /* Register special functions. */
4722 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004723 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004724 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004725 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004726 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004727 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004728 hlua_class_function(gL.T, "sleep", hlua_sleep);
4729 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004730 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4731 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4732 hlua_class_function(gL.T, "set_map", hlua_set_map);
4733 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004734 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004735 hlua_class_function(gL.T, "log", hlua_log);
4736 hlua_class_function(gL.T, "Debug", hlua_log_debug);
4737 hlua_class_function(gL.T, "Info", hlua_log_info);
4738 hlua_class_function(gL.T, "Warning", hlua_log_warning);
4739 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIER0a99b892015-08-26 00:14:17 +02004740 hlua_class_function(gL.T, "done", hlua_done);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004741
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004742 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004743
4744 /*
4745 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02004746 * Register class Map
4747 *
4748 */
4749
4750 /* This table entry is the object "Map" base. */
4751 lua_newtable(gL.T);
4752
4753 /* register pattern types. */
4754 for (i=0; i<PAT_MATCH_NUM; i++)
4755 hlua_class_const_int(gL.T, pat_match_names[i], i);
4756
4757 /* register constructor. */
4758 hlua_class_function(gL.T, "new", hlua_map_new);
4759
4760 /* Create and fill the metatable. */
4761 lua_newtable(gL.T);
4762
4763 /* Create and fille the __index entry. */
4764 lua_pushstring(gL.T, "__index");
4765 lua_newtable(gL.T);
4766
4767 /* Register . */
4768 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
4769 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
4770
4771 lua_settable(gL.T, -3);
4772
4773 /* Register previous table in the registry with reference and named entry. */
4774 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4775 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4776 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
4777 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4778
4779 /* Assign the metatable to the mai Map object. */
4780 lua_setmetatable(gL.T, -2);
4781
4782 /* Set a name to the table. */
4783 lua_setglobal(gL.T, "Map");
4784
4785 /*
4786 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004787 * Register class Channel
4788 *
4789 */
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, "get", hlua_channel_get);
4800 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4801 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4802 hlua_class_function(gL.T, "set", hlua_channel_set);
4803 hlua_class_function(gL.T, "append", hlua_channel_append);
4804 hlua_class_function(gL.T, "send", hlua_channel_send);
4805 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4806 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4807 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4808
4809 lua_settable(gL.T, -3);
4810
4811 /* Register previous table in the registry with reference and named entry. */
4812 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4813 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4814 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4815
4816 /*
4817 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004818 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004819 *
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
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004829 /* Browse existing fetches and create the associated
4830 * object method.
4831 */
4832 sf = NULL;
4833 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4834
4835 /* Dont register the keywork if the arguments check function are
4836 * not safe during the runtime.
4837 */
4838 if ((sf->val_args != NULL) &&
4839 (sf->val_args != val_payload_lv) &&
4840 (sf->val_args != val_hdr))
4841 continue;
4842
4843 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4844 * by an underscore.
4845 */
4846 strncpy(trash.str, sf->kw, trash.size);
4847 trash.str[trash.size - 1] = '\0';
4848 for (p = trash.str; *p; p++)
4849 if (*p == '.' || *p == '-' || *p == '+')
4850 *p = '_';
4851
4852 /* Register the function. */
4853 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01004854 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004855 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4856 lua_settable(gL.T, -3);
4857 }
4858
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004859 lua_settable(gL.T, -3);
4860
4861 /* Register previous table in the registry with reference and named entry. */
4862 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4863 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4864 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4865
4866 /*
4867 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004868 * Register class Converters
4869 *
4870 */
4871
4872 /* Create and fill the metatable. */
4873 lua_newtable(gL.T);
4874
4875 /* Create and fill the __index entry. */
4876 lua_pushstring(gL.T, "__index");
4877 lua_newtable(gL.T);
4878
4879 /* Browse existing converters and create the associated
4880 * object method.
4881 */
4882 sc = NULL;
4883 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4884 /* Dont register the keywork if the arguments check function are
4885 * not safe during the runtime.
4886 */
4887 if (sc->val_args != NULL)
4888 continue;
4889
4890 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4891 * by an underscore.
4892 */
4893 strncpy(trash.str, sc->kw, trash.size);
4894 trash.str[trash.size - 1] = '\0';
4895 for (p = trash.str; *p; p++)
4896 if (*p == '.' || *p == '-' || *p == '+')
4897 *p = '_';
4898
4899 /* Register the function. */
4900 lua_pushstring(gL.T, trash.str);
4901 lua_pushlightuserdata(gL.T, sc);
4902 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4903 lua_settable(gL.T, -3);
4904 }
4905
4906 lua_settable(gL.T, -3);
4907
4908 /* Register previous table in the registry with reference and named entry. */
4909 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4910 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4911 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4912
4913 /*
4914 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004915 * Register class HTTP
4916 *
4917 */
4918
4919 /* Create and fill the metatable. */
4920 lua_newtable(gL.T);
4921
4922 /* Create and fille the __index entry. */
4923 lua_pushstring(gL.T, "__index");
4924 lua_newtable(gL.T);
4925
4926 /* Register Lua functions. */
4927 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
4928 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
4929 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
4930 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
4931 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
4932 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
4933 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
4934 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
4935 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
4936 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
4937
4938 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
4939 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
4940 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
4941 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
4942 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
4943 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
Thierry FOURNIER35d70ef2015-08-26 16:21:56 +02004944 hlua_class_function(gL.T, "res_set_status", hlua_http_res_set_status);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004945
4946 lua_settable(gL.T, -3);
4947
4948 /* Register previous table in the registry with reference and named entry. */
4949 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4950 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
4951 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4952
4953 /*
4954 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004955 * Register class TXN
4956 *
4957 */
4958
4959 /* Create and fill the metatable. */
4960 lua_newtable(gL.T);
4961
4962 /* Create and fille the __index entry. */
4963 lua_pushstring(gL.T, "__index");
4964 lua_newtable(gL.T);
4965
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004966 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004967 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4968 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004969 hlua_class_function(gL.T, "set_var", hlua_set_var);
4970 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004971 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004972 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
4973 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
4974 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004975 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
4976 hlua_class_function(gL.T, "log", hlua_txn_log);
4977 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
4978 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
4979 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
4980 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004981
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004982 lua_settable(gL.T, -3);
4983
4984 /* Register previous table in the registry with reference and named entry. */
4985 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4986 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
4987 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004988
4989 /*
4990 *
4991 * Register class Socket
4992 *
4993 */
4994
4995 /* Create and fill the metatable. */
4996 lua_newtable(gL.T);
4997
4998 /* Create and fille the __index entry. */
4999 lua_pushstring(gL.T, "__index");
5000 lua_newtable(gL.T);
5001
Baptiste Assmann84bb4932015-03-02 21:40:06 +01005002#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005003 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01005004#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005005 hlua_class_function(gL.T, "connect", hlua_socket_connect);
5006 hlua_class_function(gL.T, "send", hlua_socket_send);
5007 hlua_class_function(gL.T, "receive", hlua_socket_receive);
5008 hlua_class_function(gL.T, "close", hlua_socket_close);
5009 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
5010 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
5011 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
5012 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
5013
5014 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5015
5016 /* Register the garbage collector entry. */
5017 lua_pushstring(gL.T, "__gc");
5018 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
5019 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
5020
5021 /* Register previous table in the registry with reference and named entry. */
5022 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5023 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
5024 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
5025 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
5026
5027 /* Proxy and server configuration initialisation. */
5028 memset(&socket_proxy, 0, sizeof(socket_proxy));
5029 init_new_proxy(&socket_proxy);
5030 socket_proxy.parent = NULL;
5031 socket_proxy.last_change = now.tv_sec;
5032 socket_proxy.id = "LUA-SOCKET";
5033 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
5034 socket_proxy.maxconn = 0;
5035 socket_proxy.accept = NULL;
5036 socket_proxy.options2 |= PR_O2_INDEPSTR;
5037 socket_proxy.srv = NULL;
5038 socket_proxy.conn_retries = 0;
5039 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
5040
5041 /* Init TCP server: unchanged parameters */
5042 memset(&socket_tcp, 0, sizeof(socket_tcp));
5043 socket_tcp.next = NULL;
5044 socket_tcp.proxy = &socket_proxy;
5045 socket_tcp.obj_type = OBJ_TYPE_SERVER;
5046 LIST_INIT(&socket_tcp.actconns);
5047 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005048 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005049 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005050 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005051 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
5052 socket_tcp.last_change = 0;
5053 socket_tcp.id = "LUA-TCP-CONN";
5054 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5055 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5056 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
5057
5058 /* XXX: Copy default parameter from default server,
5059 * but the default server is not initialized.
5060 */
5061 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
5062 socket_tcp.minconn = socket_proxy.defsrv.minconn;
5063 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
5064 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
5065 socket_tcp.onerror = socket_proxy.defsrv.onerror;
5066 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5067 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
5068 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5069 socket_tcp.uweight = socket_proxy.defsrv.iweight;
5070 socket_tcp.iweight = socket_proxy.defsrv.iweight;
5071
5072 socket_tcp.check.status = HCHK_STATUS_INI;
5073 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
5074 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
5075 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
5076 socket_tcp.check.server = &socket_tcp;
5077
5078 socket_tcp.agent.status = HCHK_STATUS_INI;
5079 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
5080 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
5081 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
5082 socket_tcp.agent.server = &socket_tcp;
5083
5084 socket_tcp.xprt = &raw_sock;
5085
5086#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005087 /* Init TCP server: unchanged parameters */
5088 memset(&socket_ssl, 0, sizeof(socket_ssl));
5089 socket_ssl.next = NULL;
5090 socket_ssl.proxy = &socket_proxy;
5091 socket_ssl.obj_type = OBJ_TYPE_SERVER;
5092 LIST_INIT(&socket_ssl.actconns);
5093 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005094 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005095 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005096 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005097 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
5098 socket_ssl.last_change = 0;
5099 socket_ssl.id = "LUA-SSL-CONN";
5100 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5101 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5102 socket_ssl.pp_opts = 0; /* Remove proxy protocol. */
5103
5104 /* XXX: Copy default parameter from default server,
5105 * but the default server is not initialized.
5106 */
5107 socket_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
5108 socket_ssl.minconn = socket_proxy.defsrv.minconn;
5109 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
5110 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5111 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5112 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5113 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5114 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5115 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5116 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5117
5118 socket_ssl.check.status = HCHK_STATUS_INI;
5119 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5120 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5121 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5122 socket_ssl.check.server = &socket_ssl;
5123
5124 socket_ssl.agent.status = HCHK_STATUS_INI;
5125 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5126 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5127 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5128 socket_ssl.agent.server = &socket_ssl;
5129
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005130 socket_ssl.use_ssl = 1;
5131 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005132
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005133 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005134 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5135 /*
5136 *
5137 * If the keyword is not known, we can search in the registered
5138 * server keywords. This is usefull to configure special SSL
5139 * features like client certificates and ssl_verify.
5140 *
5141 */
5142 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5143 if (tmp_error != 0) {
5144 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5145 abort(); /* This must be never arrives because the command line
5146 not editable by the user. */
5147 }
5148 idx += kw->skip;
5149 }
5150 }
5151
5152 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005153 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005154#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005155}