blob: fa67b15f2f90e7350549b1be3ab0db3f56446937 [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 FOURNIER8c542ca2015-08-19 09:00:18 +0200511 smp->data.type = SMP_T_BOOL;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +0200512 smp->data.u.sint = 0;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100513 break;
514 }
515 return 1;
516}
517
518/* This function check the "argp" builded by another conversion function
519 * is in accord with the expected argp defined by the "mask". The fucntion
520 * returns true or false. It can be adjust the types if there compatibles.
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100521 *
522 * This function assumes thant the argp argument contains ARGM_NBARGS + 1
523 * entries.
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100524 */
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100525__LJMP int hlua_lua2arg_check(lua_State *L, int first, struct arg *argp,
526 unsigned int mask, struct proxy *p)
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100527{
528 int min_arg;
529 int idx;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100530 struct proxy *px;
531 char *sname, *pname;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100532
533 idx = 0;
534 min_arg = ARGM(mask);
535 mask >>= ARGM_BITS;
536
537 while (1) {
538
539 /* Check oversize. */
540 if (idx >= ARGM_NBARGS && argp[idx].type != ARGT_STOP) {
Cyril Bonté577a36a2015-03-02 00:08:38 +0100541 WILL_LJMP(luaL_argerror(L, first + idx, "Malformed argument mask"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100542 }
543
544 /* Check for mandatory arguments. */
545 if (argp[idx].type == ARGT_STOP) {
Thierry FOURNIER3caa0392015-03-13 13:38:17 +0100546 if (idx < min_arg) {
547
548 /* If miss other argument than the first one, we return an error. */
549 if (idx > 0)
550 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
551
552 /* If first argument have a certain type, some default values
553 * may be used. See the function smp_resolve_args().
554 */
555 switch (mask & ARGT_MASK) {
556
557 case ARGT_FE:
558 if (!(p->cap & PR_CAP_FE))
559 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
560 argp[idx].data.prx = p;
561 argp[idx].type = ARGT_FE;
562 argp[idx+1].type = ARGT_STOP;
563 break;
564
565 case ARGT_BE:
566 if (!(p->cap & PR_CAP_BE))
567 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
568 argp[idx].data.prx = p;
569 argp[idx].type = ARGT_BE;
570 argp[idx+1].type = ARGT_STOP;
571 break;
572
573 case ARGT_TAB:
574 argp[idx].data.prx = p;
575 argp[idx].type = ARGT_TAB;
576 argp[idx+1].type = ARGT_STOP;
577 break;
578
579 default:
580 WILL_LJMP(luaL_argerror(L, first + idx, "Mandatory argument expected"));
581 break;
582 }
583 }
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100584 return 0;
585 }
586
587 /* Check for exceed the number of requiered argument. */
588 if ((mask & ARGT_MASK) == ARGT_STOP &&
589 argp[idx].type != ARGT_STOP) {
590 WILL_LJMP(luaL_argerror(L, first + idx, "Last argument expected"));
591 }
592
593 if ((mask & ARGT_MASK) == ARGT_STOP &&
594 argp[idx].type == ARGT_STOP) {
595 return 0;
596 }
597
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100598 /* Convert some argument types. */
599 switch (mask & ARGT_MASK) {
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100600 case ARGT_SINT:
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100601 if (argp[idx].type != ARGT_SINT)
602 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
603 argp[idx].type = ARGT_SINT;
604 break;
605
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100606 case ARGT_TIME:
607 if (argp[idx].type != ARGT_SINT)
608 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200609 argp[idx].type = ARGT_TIME;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100610 break;
611
612 case ARGT_SIZE:
613 if (argp[idx].type != ARGT_SINT)
614 WILL_LJMP(luaL_argerror(L, first + idx, "integer expected"));
Thierry FOURNIER29176f32015-07-07 00:41:29 +0200615 argp[idx].type = ARGT_SIZE;
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100616 break;
617
618 case ARGT_FE:
619 if (argp[idx].type != ARGT_STR)
620 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
621 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
622 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200623 argp[idx].data.prx = proxy_fe_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100624 if (!argp[idx].data.prx)
625 WILL_LJMP(luaL_argerror(L, first + idx, "frontend doesn't exist"));
626 argp[idx].type = ARGT_FE;
627 break;
628
629 case ARGT_BE:
630 if (argp[idx].type != ARGT_STR)
631 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
632 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
633 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200634 argp[idx].data.prx = proxy_be_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100635 if (!argp[idx].data.prx)
636 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
637 argp[idx].type = ARGT_BE;
638 break;
639
640 case ARGT_TAB:
641 if (argp[idx].type != ARGT_STR)
642 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
643 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
644 trash.str[argp[idx].data.str.len] = 0;
Willy Tarreaue2dc1fa2015-05-26 12:08:07 +0200645 argp[idx].data.prx = proxy_tbl_by_name(trash.str);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100646 if (!argp[idx].data.prx)
647 WILL_LJMP(luaL_argerror(L, first + idx, "table doesn't exist"));
648 argp[idx].type = ARGT_TAB;
649 break;
650
651 case ARGT_SRV:
652 if (argp[idx].type != ARGT_STR)
653 WILL_LJMP(luaL_argerror(L, first + idx, "string expected"));
654 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
655 trash.str[argp[idx].data.str.len] = 0;
656 sname = strrchr(trash.str, '/');
657 if (sname) {
658 *sname++ = '\0';
659 pname = trash.str;
Willy Tarreau9e0bb102015-05-26 11:24:42 +0200660 px = proxy_be_by_name(pname);
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100661 if (!px)
662 WILL_LJMP(luaL_argerror(L, first + idx, "backend doesn't exist"));
663 }
664 else {
665 sname = trash.str;
666 px = p;
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100667 }
Thierry FOURNIER7f4942a2015-03-12 18:28:50 +0100668 argp[idx].data.srv = findserver(px, sname);
669 if (!argp[idx].data.srv)
670 WILL_LJMP(luaL_argerror(L, first + idx, "server doesn't exist"));
671 argp[idx].type = ARGT_SRV;
672 break;
673
674 case ARGT_IPV4:
675 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
676 trash.str[argp[idx].data.str.len] = 0;
677 if (inet_pton(AF_INET, trash.str, &argp[idx].data.ipv4))
678 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 address"));
679 argp[idx].type = ARGT_IPV4;
680 break;
681
682 case ARGT_MSK4:
683 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
684 trash.str[argp[idx].data.str.len] = 0;
685 if (!str2mask(trash.str, &argp[idx].data.ipv4))
686 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv4 mask"));
687 argp[idx].type = ARGT_MSK4;
688 break;
689
690 case ARGT_IPV6:
691 memcpy(trash.str, argp[idx].data.str.str, argp[idx].data.str.len);
692 trash.str[argp[idx].data.str.len] = 0;
693 if (inet_pton(AF_INET6, trash.str, &argp[idx].data.ipv6))
694 WILL_LJMP(luaL_argerror(L, first + idx, "invalid IPv6 address"));
695 argp[idx].type = ARGT_IPV6;
696 break;
697
698 case ARGT_MSK6:
699 case ARGT_MAP:
700 case ARGT_REG:
701 case ARGT_USR:
702 WILL_LJMP(luaL_argerror(L, first + idx, "type not yet supported"));
Thierry FOURNIER55da1652015-01-23 11:36:30 +0100703 break;
704 }
705
706 /* Check for type of argument. */
707 if ((mask & ARGT_MASK) != argp[idx].type) {
708 const char *msg = lua_pushfstring(L, "'%s' expected, got '%s'",
709 arg_type_names[(mask & ARGT_MASK)],
710 arg_type_names[argp[idx].type & ARGT_MASK]);
711 WILL_LJMP(luaL_argerror(L, first + idx, msg));
712 }
713
714 /* Next argument. */
715 mask >>= ARGT_BITS;
716 idx++;
717 }
718}
719
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100720/*
721 * The following functions are used to make correspondance between the the
722 * executed lua pointer and the "struct hlua *" that contain the context.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100723 *
724 * - hlua_gethlua : return the hlua context associated with an lua_State.
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100725 * - hlua_sethlua : create the association between hlua context and lua_state.
726 */
727static inline struct hlua *hlua_gethlua(lua_State *L)
728{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100729 struct hlua **hlua = lua_getextraspace(L);
730 return *hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100731}
732static inline void hlua_sethlua(struct hlua *hlua)
733{
Thierry FOURNIER38c5fd62015-03-10 02:40:29 +0100734 struct hlua **hlua_store = lua_getextraspace(hlua->T);
735 *hlua_store = hlua;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100736}
737
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +0100738/* This function is used to send logs. It try to send on screen (stderr)
739 * and on the default syslog server.
740 */
741static inline void hlua_sendlog(struct proxy *px, int level, const char *msg)
742{
743 struct tm tm;
744 char *p;
745
746 /* Cleanup the log message. */
747 p = trash.str;
748 for (; *msg != '\0'; msg++, p++) {
749 if (p >= trash.str + trash.size - 1)
750 return;
751 if (isprint(*msg))
752 *p = *msg;
753 else
754 *p = '.';
755 }
756 *p = '\0';
757
758 send_log(px, level, "%s", trash.str);
759 if (!(global.mode & MODE_QUIET) || (global.mode & (MODE_VERBOSE | MODE_STARTING))) {
760 get_localtime(date.tv_sec, &tm);
761 fprintf(stderr, "[%s] %03d/%02d%02d%02d (%d) : %s\n",
762 log_levels[level], tm.tm_yday, tm.tm_hour, tm.tm_min, tm.tm_sec,
763 (int)getpid(), trash.str);
764 fflush(stderr);
765 }
766}
767
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100768/* This function just ensure that the yield will be always
769 * returned with a timeout and permit to set some flags
770 */
771__LJMP void hlua_yieldk(lua_State *L, int nresults, int ctx,
Thierry FOURNIERf90838b2015-03-06 13:48:32 +0100772 lua_KFunction k, int timeout, unsigned int flags)
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100773{
774 struct hlua *hlua = hlua_gethlua(L);
775
776 /* Set the wake timeout. If timeout is required, we set
777 * the expiration time.
778 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100779 hlua->wake_time = tick_first(timeout, hlua->expire);
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100780
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +0100781 hlua->flags |= flags;
782
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100783 /* Process the yield. */
784 WILL_LJMP(lua_yieldk(L, nresults, ctx, k));
785}
786
Willy Tarreau87b09662015-04-03 00:22:06 +0200787/* This function initialises the Lua environment stored in the stream.
788 * It must be called at the start of the stream. This function creates
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100789 * an LUA coroutine. It can not be use to crete the main LUA context.
790 */
791int hlua_ctx_init(struct hlua *lua, struct task *task)
792{
793 lua->Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100794 lua->flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100795 LIST_INIT(&lua->com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100796 lua->T = lua_newthread(gL.T);
797 if (!lua->T) {
798 lua->Tref = LUA_REFNIL;
799 return 0;
800 }
801 hlua_sethlua(lua);
802 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
803 lua->task = task;
804 return 1;
805}
806
Willy Tarreau87b09662015-04-03 00:22:06 +0200807/* Used to destroy the Lua coroutine when the attached stream or task
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100808 * is destroyed. The destroy also the memory context. The struct "lua"
809 * is not freed.
810 */
811void hlua_ctx_destroy(struct hlua *lua)
812{
Thierry FOURNIERa718b292015-03-04 16:48:34 +0100813 if (!lua->T)
814 return;
815
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +0100816 /* Purge all the pending signals. */
817 hlua_com_purge(lua);
818
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100819 /* The thread is garbage collected by Lua. */
820 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
821 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
822}
823
824/* This function is used to restore the Lua context when a coroutine
825 * fails. This function copy the common memory between old coroutine
826 * and the new coroutine. The old coroutine is destroyed, and its
827 * replaced by the new coroutine.
828 * If the flag "keep_msg" is set, the last entry of the old is assumed
829 * as string error message and it is copied in the new stack.
830 */
831static int hlua_ctx_renew(struct hlua *lua, int keep_msg)
832{
833 lua_State *T;
834 int new_ref;
835
836 /* Renew the main LUA stack doesn't have sense. */
837 if (lua == &gL)
838 return 0;
839
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100840 /* New Lua coroutine. */
841 T = lua_newthread(gL.T);
842 if (!T)
843 return 0;
844
845 /* Copy last error message. */
846 if (keep_msg)
847 lua_xmove(lua->T, T, 1);
848
849 /* Copy data between the coroutines. */
850 lua_rawgeti(lua->T, LUA_REGISTRYINDEX, lua->Mref);
851 lua_xmove(lua->T, T, 1);
852 new_ref = luaL_ref(T, LUA_REGISTRYINDEX); /* Valur poped. */
853
854 /* Destroy old data. */
855 luaL_unref(lua->T, LUA_REGISTRYINDEX, lua->Mref);
856
857 /* The thread is garbage collected by Lua. */
858 luaL_unref(gL.T, LUA_REGISTRYINDEX, lua->Tref);
859
860 /* Fill the struct with the new coroutine values. */
861 lua->Mref = new_ref;
862 lua->T = T;
863 lua->Tref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
864
865 /* Set context. */
866 hlua_sethlua(lua);
867
868 return 1;
869}
870
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100871void hlua_hook(lua_State *L, lua_Debug *ar)
872{
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100873 struct hlua *hlua = hlua_gethlua(L);
874
875 /* Lua cannot yield when its returning from a function,
876 * so, we can fix the interrupt hook to 1 instruction,
877 * expecting that the function is finnished.
878 */
879 if (lua_gethookmask(L) & LUA_MASKRET) {
880 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, 1);
881 return;
882 }
883
884 /* restore the interrupt condition. */
885 lua_sethook(hlua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
886
887 /* If we interrupt the Lua processing in yieldable state, we yield.
888 * If the state is not yieldable, trying yield causes an error.
889 */
890 if (lua_isyieldable(L))
891 WILL_LJMP(hlua_yieldk(L, 0, 0, NULL, TICK_ETERNITY, HLUA_CTRLYIELD));
892
Thierry FOURNIERa85cfb12015-03-13 14:50:06 +0100893 /* If we cannot yield, update the clock and check the timeout. */
894 tv_update_date(0, 1);
Thierry FOURNIERcae49c92015-03-06 14:05:24 +0100895 if (tick_is_expired(hlua->expire, now_ms)) {
896 lua_pushfstring(L, "execution timeout");
897 WILL_LJMP(lua_error(L));
898 }
899
900 /* Try to interrupt the process at the end of the current
901 * unyieldable function.
902 */
903 lua_sethook(hlua->T, hlua_hook, LUA_MASKRET|LUA_MASKCOUNT, hlua_nb_instruction);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100904}
905
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100906/* This function start or resumes the Lua stack execution. If the flag
907 * "yield_allowed" if no set and the LUA stack execution returns a yield
908 * The function return an error.
909 *
910 * The function can returns 4 values:
911 * - HLUA_E_OK : The execution is terminated without any errors.
912 * - HLUA_E_AGAIN : The execution must continue at the next associated
913 * task wakeup.
914 * - HLUA_E_ERRMSG : An error has occured, an error message is set in
915 * the top of the stack.
916 * - HLUA_E_ERR : An error has occured without error message.
917 *
918 * If an error occured, the stack is renewed and it is ready to run new
919 * LUA code.
920 */
921static enum hlua_exec hlua_ctx_resume(struct hlua *lua, int yield_allowed)
922{
923 int ret;
924 const char *msg;
925
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +0100926 HLUA_SET_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100927
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100928 /* If we want to resume the task, then check first the execution timeout.
929 * if it is reached, we can interrupt the Lua processing.
930 */
931 if (tick_is_expired(lua->expire, now_ms))
932 goto timeout_reached;
933
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100934resume_execution:
935
936 /* This hook interrupts the Lua processing each 'hlua_nb_instruction'
937 * instructions. it is used for preventing infinite loops.
938 */
939 lua_sethook(lua->T, hlua_hook, LUA_MASKCOUNT, hlua_nb_instruction);
940
Thierry FOURNIER1bfc09b2015-03-05 17:10:14 +0100941 /* Remove all flags except the running flags. */
942 lua->flags = HLUA_RUN;
943
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100944 /* Call the function. */
945 ret = lua_resume(lua->T, gL.T, lua->nargs);
946 switch (ret) {
947
948 case LUA_OK:
949 ret = HLUA_E_OK;
950 break;
951
952 case LUA_YIELD:
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100953 /* Check if the execution timeout is expired. It it is the case, we
954 * break the Lua execution.
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100955 */
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100956 if (tick_is_expired(lua->expire, now_ms)) {
957
958timeout_reached:
959
960 lua_settop(lua->T, 0); /* Empty the stack. */
961 if (!lua_checkstack(lua->T, 1)) {
962 ret = HLUA_E_ERR;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100963 break;
964 }
Thierry FOURNIERdc9ca962015-03-05 11:16:52 +0100965 lua_pushfstring(lua->T, "execution timeout");
966 ret = HLUA_E_ERRMSG;
967 break;
968 }
969 /* Process the forced yield. if the general yield is not allowed or
970 * if no task were associated this the current Lua execution
971 * coroutine, we resume the execution. Else we want to return in the
972 * scheduler and we want to be waked up again, to continue the
973 * current Lua execution. So we schedule our own task.
974 */
975 if (HLUA_IS_CTRLYIELDING(lua)) {
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100976 if (!yield_allowed || !lua->task)
977 goto resume_execution;
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100978 task_wakeup(lua->task, TASK_WOKEN_MSG);
Thierry FOURNIERee9f8022015-03-03 17:37:37 +0100979 }
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100980 if (!yield_allowed) {
981 lua_settop(lua->T, 0); /* Empty the stack. */
982 if (!lua_checkstack(lua->T, 1)) {
983 ret = HLUA_E_ERR;
984 break;
985 }
986 lua_pushfstring(lua->T, "yield not allowed");
987 ret = HLUA_E_ERRMSG;
988 break;
989 }
990 ret = HLUA_E_AGAIN;
991 break;
992
993 case LUA_ERRRUN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +0100994 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +0100995 if (!lua_checkstack(lua->T, 1)) {
996 ret = HLUA_E_ERR;
997 break;
998 }
999 msg = lua_tostring(lua->T, -1);
1000 lua_settop(lua->T, 0); /* Empty the stack. */
1001 lua_pop(lua->T, 1);
1002 if (msg)
1003 lua_pushfstring(lua->T, "runtime error: %s", msg);
1004 else
1005 lua_pushfstring(lua->T, "unknown runtime error");
1006 ret = HLUA_E_ERRMSG;
1007 break;
1008
1009 case LUA_ERRMEM:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001010 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001011 lua_settop(lua->T, 0); /* Empty the stack. */
1012 if (!lua_checkstack(lua->T, 1)) {
1013 ret = HLUA_E_ERR;
1014 break;
1015 }
1016 lua_pushfstring(lua->T, "out of memory error");
1017 ret = HLUA_E_ERRMSG;
1018 break;
1019
1020 case LUA_ERRERR:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001021 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001022 if (!lua_checkstack(lua->T, 1)) {
1023 ret = HLUA_E_ERR;
1024 break;
1025 }
1026 msg = lua_tostring(lua->T, -1);
1027 lua_settop(lua->T, 0); /* Empty the stack. */
1028 lua_pop(lua->T, 1);
1029 if (msg)
1030 lua_pushfstring(lua->T, "message handler error: %s", msg);
1031 else
1032 lua_pushfstring(lua->T, "message handler error");
1033 ret = HLUA_E_ERRMSG;
1034 break;
1035
1036 default:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01001037 lua->wake_time = TICK_ETERNITY;
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001038 lua_settop(lua->T, 0); /* Empty the stack. */
1039 if (!lua_checkstack(lua->T, 1)) {
1040 ret = HLUA_E_ERR;
1041 break;
1042 }
1043 lua_pushfstring(lua->T, "unknonwn error");
1044 ret = HLUA_E_ERRMSG;
1045 break;
1046 }
1047
1048 switch (ret) {
1049 case HLUA_E_AGAIN:
1050 break;
1051
1052 case HLUA_E_ERRMSG:
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001053 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001054 hlua_ctx_renew(lua, 1);
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001055 HLUA_CLR_RUN(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001056 break;
1057
1058 case HLUA_E_ERR:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001059 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001060 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001061 hlua_ctx_renew(lua, 0);
1062 break;
1063
1064 case HLUA_E_OK:
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01001065 HLUA_CLR_RUN(lua);
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01001066 hlua_com_purge(lua);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01001067 break;
1068 }
1069
1070 return ret;
1071}
1072
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01001073/* This function is an LUA binding. It provides a function
1074 * for deleting ACL from a referenced ACL file.
1075 */
1076__LJMP static int hlua_del_acl(lua_State *L)
1077{
1078 const char *name;
1079 const char *key;
1080 struct pat_ref *ref;
1081
1082 MAY_LJMP(check_args(L, 2, "del_acl"));
1083
1084 name = MAY_LJMP(luaL_checkstring(L, 1));
1085 key = MAY_LJMP(luaL_checkstring(L, 2));
1086
1087 ref = pat_ref_lookup(name);
1088 if (!ref)
1089 WILL_LJMP(luaL_error(L, "'del_acl': unkown acl file '%s'", name));
1090
1091 pat_ref_delete(ref, key);
1092 return 0;
1093}
1094
1095/* This function is an LUA binding. It provides a function
1096 * for deleting map entry from a referenced map file.
1097 */
1098static int hlua_del_map(lua_State *L)
1099{
1100 const char *name;
1101 const char *key;
1102 struct pat_ref *ref;
1103
1104 MAY_LJMP(check_args(L, 2, "del_map"));
1105
1106 name = MAY_LJMP(luaL_checkstring(L, 1));
1107 key = MAY_LJMP(luaL_checkstring(L, 2));
1108
1109 ref = pat_ref_lookup(name);
1110 if (!ref)
1111 WILL_LJMP(luaL_error(L, "'del_map': unkown acl file '%s'", name));
1112
1113 pat_ref_delete(ref, key);
1114 return 0;
1115}
1116
1117/* This function is an LUA binding. It provides a function
1118 * for adding ACL pattern from a referenced ACL file.
1119 */
1120static int hlua_add_acl(lua_State *L)
1121{
1122 const char *name;
1123 const char *key;
1124 struct pat_ref *ref;
1125
1126 MAY_LJMP(check_args(L, 2, "add_acl"));
1127
1128 name = MAY_LJMP(luaL_checkstring(L, 1));
1129 key = MAY_LJMP(luaL_checkstring(L, 2));
1130
1131 ref = pat_ref_lookup(name);
1132 if (!ref)
1133 WILL_LJMP(luaL_error(L, "'add_acl': unkown acl file '%s'", name));
1134
1135 if (pat_ref_find_elt(ref, key) == NULL)
1136 pat_ref_add(ref, key, NULL, NULL);
1137 return 0;
1138}
1139
1140/* This function is an LUA binding. It provides a function
1141 * for setting map pattern and sample from a referenced map
1142 * file.
1143 */
1144static int hlua_set_map(lua_State *L)
1145{
1146 const char *name;
1147 const char *key;
1148 const char *value;
1149 struct pat_ref *ref;
1150
1151 MAY_LJMP(check_args(L, 3, "set_map"));
1152
1153 name = MAY_LJMP(luaL_checkstring(L, 1));
1154 key = MAY_LJMP(luaL_checkstring(L, 2));
1155 value = MAY_LJMP(luaL_checkstring(L, 3));
1156
1157 ref = pat_ref_lookup(name);
1158 if (!ref)
1159 WILL_LJMP(luaL_error(L, "'set_map': unkown map file '%s'", name));
1160
1161 if (pat_ref_find_elt(ref, key) != NULL)
1162 pat_ref_set(ref, key, value, NULL);
1163 else
1164 pat_ref_add(ref, key, value, NULL);
1165 return 0;
1166}
1167
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01001168/* A class is a lot of memory that contain data. This data can be a table,
1169 * an integer or user data. This data is associated with a metatable. This
1170 * metatable have an original version registred in the global context with
1171 * the name of the object (_G[<name>] = <metable> ).
1172 *
1173 * A metable is a table that modify the standard behavior of a standard
1174 * access to the associated data. The entries of this new metatable are
1175 * defined as is:
1176 *
1177 * http://lua-users.org/wiki/MetatableEvents
1178 *
1179 * __index
1180 *
1181 * we access an absent field in a table, the result is nil. This is
1182 * true, but it is not the whole truth. Actually, such access triggers
1183 * the interpreter to look for an __index metamethod: If there is no
1184 * such method, as usually happens, then the access results in nil;
1185 * otherwise, the metamethod will provide the result.
1186 *
1187 * Control 'prototype' inheritance. When accessing "myTable[key]" and
1188 * the key does not appear in the table, but the metatable has an __index
1189 * property:
1190 *
1191 * - if the value is a function, the function is called, passing in the
1192 * table and the key; the return value of that function is returned as
1193 * the result.
1194 *
1195 * - if the value is another table, the value of the key in that table is
1196 * asked for and returned (and if it doesn't exist in that table, but that
1197 * table's metatable has an __index property, then it continues on up)
1198 *
1199 * - Use "rawget(myTable,key)" to skip this metamethod.
1200 *
1201 * http://www.lua.org/pil/13.4.1.html
1202 *
1203 * __newindex
1204 *
1205 * Like __index, but control property assignment.
1206 *
1207 * __mode - Control weak references. A string value with one or both
1208 * of the characters 'k' and 'v' which specifies that the the
1209 * keys and/or values in the table are weak references.
1210 *
1211 * __call - Treat a table like a function. When a table is followed by
1212 * parenthesis such as "myTable( 'foo' )" and the metatable has
1213 * a __call key pointing to a function, that function is invoked
1214 * (passing any specified arguments) and the return value is
1215 * returned.
1216 *
1217 * __metatable - Hide the metatable. When "getmetatable( myTable )" is
1218 * called, if the metatable for myTable has a __metatable
1219 * key, the value of that key is returned instead of the
1220 * actual metatable.
1221 *
1222 * __tostring - Control string representation. When the builtin
1223 * "tostring( myTable )" function is called, if the metatable
1224 * for myTable has a __tostring property set to a function,
1225 * that function is invoked (passing myTable to it) and the
1226 * return value is used as the string representation.
1227 *
1228 * __len - Control table length. When the table length is requested using
1229 * the length operator ( '#' ), if the metatable for myTable has
1230 * a __len key pointing to a function, that function is invoked
1231 * (passing myTable to it) and the return value used as the value
1232 * of "#myTable".
1233 *
1234 * __gc - Userdata finalizer code. When userdata is set to be garbage
1235 * collected, if the metatable has a __gc field pointing to a
1236 * function, that function is first invoked, passing the userdata
1237 * to it. The __gc metamethod is not called for tables.
1238 * (See http://lua-users.org/lists/lua-l/2006-11/msg00508.html)
1239 *
1240 * Special metamethods for redefining standard operators:
1241 * http://www.lua.org/pil/13.1.html
1242 *
1243 * __add "+"
1244 * __sub "-"
1245 * __mul "*"
1246 * __div "/"
1247 * __unm "!"
1248 * __pow "^"
1249 * __concat ".."
1250 *
1251 * Special methods for redfining standar relations
1252 * http://www.lua.org/pil/13.2.html
1253 *
1254 * __eq "=="
1255 * __lt "<"
1256 * __le "<="
1257 */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001258
1259/*
1260 *
1261 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001262 * Class Map
1263 *
1264 *
1265 */
1266
1267/* Returns a struct hlua_map if the stack entry "ud" is
1268 * a class session, otherwise it throws an error.
1269 */
1270__LJMP static struct map_descriptor *hlua_checkmap(lua_State *L, int ud)
1271{
1272 return (struct map_descriptor *)MAY_LJMP(hlua_checkudata(L, ud, class_map_ref));
1273}
1274
1275/* This function is the map constructor. It don't need
1276 * the class Map object. It creates and return a new Map
1277 * object. It must be called only during "body" or "init"
1278 * context because it process some filesystem accesses.
1279 */
1280__LJMP static int hlua_map_new(struct lua_State *L)
1281{
1282 const char *fn;
1283 int match = PAT_MATCH_STR;
1284 struct sample_conv conv;
1285 const char *file = "";
1286 int line = 0;
1287 lua_Debug ar;
1288 char *err = NULL;
1289 struct arg args[2];
1290
1291 if (lua_gettop(L) < 1 || lua_gettop(L) > 2)
1292 WILL_LJMP(luaL_error(L, "'new' needs at least 1 argument."));
1293
1294 fn = MAY_LJMP(luaL_checkstring(L, 1));
1295
1296 if (lua_gettop(L) >= 2) {
1297 match = MAY_LJMP(luaL_checkinteger(L, 2));
1298 if (match < 0 || match >= PAT_MATCH_NUM)
1299 WILL_LJMP(luaL_error(L, "'new' needs a valid match method."));
1300 }
1301
1302 /* Get Lua filename and line number. */
1303 if (lua_getstack(L, 1, &ar)) { /* check function at level */
1304 lua_getinfo(L, "Sl", &ar); /* get info about it */
1305 if (ar.currentline > 0) { /* is there info? */
1306 file = ar.short_src;
1307 line = ar.currentline;
1308 }
1309 }
1310
1311 /* fill fake sample_conv struct. */
1312 conv.kw = ""; /* unused. */
1313 conv.process = NULL; /* unused. */
1314 conv.arg_mask = 0; /* unused. */
1315 conv.val_args = NULL; /* unused. */
1316 conv.out_type = SMP_T_STR;
1317 conv.private = (void *)(long)match;
1318 switch (match) {
1319 case PAT_MATCH_STR: conv.in_type = SMP_T_STR; break;
1320 case PAT_MATCH_BEG: conv.in_type = SMP_T_STR; break;
1321 case PAT_MATCH_SUB: conv.in_type = SMP_T_STR; break;
1322 case PAT_MATCH_DIR: conv.in_type = SMP_T_STR; break;
1323 case PAT_MATCH_DOM: conv.in_type = SMP_T_STR; break;
1324 case PAT_MATCH_END: conv.in_type = SMP_T_STR; break;
1325 case PAT_MATCH_REG: conv.in_type = SMP_T_STR; break;
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001326 case PAT_MATCH_INT: conv.in_type = SMP_T_SINT; break;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001327 case PAT_MATCH_IP: conv.in_type = SMP_T_ADDR; break;
1328 default:
1329 WILL_LJMP(luaL_error(L, "'new' doesn't support this match mode."));
1330 }
1331
1332 /* fill fake args. */
1333 args[0].type = ARGT_STR;
1334 args[0].data.str.str = (char *)fn;
1335 args[1].type = ARGT_STOP;
1336
1337 /* load the map. */
1338 if (!sample_load_map(args, &conv, file, line, &err)) {
1339 /* error case: we cant use luaL_error because we must
1340 * free the err variable.
1341 */
1342 luaL_where(L, 1);
1343 lua_pushfstring(L, "'new': %s.", err);
1344 lua_concat(L, 2);
1345 free(err);
1346 WILL_LJMP(lua_error(L));
1347 }
1348
1349 /* create the lua object. */
1350 lua_newtable(L);
1351 lua_pushlightuserdata(L, args[0].data.map);
1352 lua_rawseti(L, -2, 0);
1353
1354 /* Pop a class Map metatable and affect it to the userdata. */
1355 lua_rawgeti(L, LUA_REGISTRYINDEX, class_map_ref);
1356 lua_setmetatable(L, -2);
1357
1358
1359 return 1;
1360}
1361
1362__LJMP static inline int _hlua_map_lookup(struct lua_State *L, int str)
1363{
1364 struct map_descriptor *desc;
1365 struct pattern *pat;
1366 struct sample smp;
1367
1368 MAY_LJMP(check_args(L, 2, "lookup"));
1369 desc = MAY_LJMP(hlua_checkmap(L, 1));
Thierry FOURNIER07ee64e2015-07-06 23:43:03 +02001370 if (desc->pat.expect_type == SMP_T_SINT) {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001371 smp.data.type = SMP_T_SINT;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001372 smp.data.u.sint = MAY_LJMP(luaL_checkinteger(L, 2));
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001373 }
1374 else {
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02001375 smp.data.type = SMP_T_STR;
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001376 smp.flags = SMP_F_CONST;
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001377 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 +02001378 }
1379
1380 pat = pattern_exec_match(&desc->pat, &smp, 1);
Thierry FOURNIER503bb092015-08-19 08:35:43 +02001381 if (!pat || !pat->data) {
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001382 if (str)
1383 lua_pushstring(L, "");
1384 else
1385 lua_pushnil(L);
1386 return 1;
1387 }
1388
1389 /* The Lua pattern must return a string, so we can't check the returned type */
Thierry FOURNIER136f9d32015-08-19 09:07:19 +02001390 lua_pushlstring(L, pat->data->u.str.str, pat->data->u.str.len);
Thierry FOURNIER3def3932015-04-07 11:27:54 +02001391 return 1;
1392}
1393
1394__LJMP static int hlua_map_lookup(struct lua_State *L)
1395{
1396 return _hlua_map_lookup(L, 0);
1397}
1398
1399__LJMP static int hlua_map_slookup(struct lua_State *L)
1400{
1401 return _hlua_map_lookup(L, 1);
1402}
1403
1404/*
1405 *
1406 *
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001407 * Class Socket
1408 *
1409 *
1410 */
1411
1412__LJMP static struct hlua_socket *hlua_checksocket(lua_State *L, int ud)
1413{
1414 return (struct hlua_socket *)MAY_LJMP(hlua_checkudata(L, ud, class_socket_ref));
1415}
1416
1417/* This function is the handler called for each I/O on the established
1418 * connection. It is used for notify space avalaible to send or data
1419 * received.
1420 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001421static void hlua_socket_handler(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001422{
Willy Tarreau00a37f02015-04-13 12:05:19 +02001423 struct stream_interface *si = appctx->owner;
Willy Tarreau50fe03b2014-11-28 13:59:31 +01001424 struct connection *c = objt_conn(si_opposite(si)->end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001425
Willy Tarreau87b09662015-04-03 00:22:06 +02001426 /* Wakeup the main stream if the client connection is closed. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001427 if (!c || channel_output_closed(si_ic(si)) || channel_input_closed(si_oc(si))) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001428 if (appctx->ctx.hlua.socket) {
1429 appctx->ctx.hlua.socket->s = NULL;
1430 appctx->ctx.hlua.socket = NULL;
1431 }
1432 si_shutw(si);
1433 si_shutr(si);
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001434 si_ic(si)->flags |= CF_READ_NULL;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001435 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1436 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
Willy Tarreaud4da1962015-04-20 01:31:23 +02001437 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001438 }
1439
1440 if (!(c->flags & CO_FL_CONNECTED))
Willy Tarreaud4da1962015-04-20 01:31:23 +02001441 return;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001442
1443 /* This function is called after the connect. */
1444 appctx->ctx.hlua.connected = 1;
1445
1446 /* Wake the tasks which wants to write if the buffer have avalaible space. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001447 if (channel_may_recv(si_oc(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001448 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1449
1450 /* Wake the tasks which wants to read if the buffer contains data. */
Willy Tarreau2bb4a962014-11-28 11:11:05 +01001451 if (channel_is_empty(si_ic(si)))
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001452 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1453}
1454
Willy Tarreau87b09662015-04-03 00:22:06 +02001455/* This function is called when the "struct stream" is destroyed.
1456 * Remove the link from the object to this stream.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001457 * Wake all the pending signals.
1458 */
Willy Tarreau00a37f02015-04-13 12:05:19 +02001459static void hlua_socket_release(struct appctx *appctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001460{
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001461 /* Remove my link in the original object. */
1462 if (appctx->ctx.hlua.socket)
1463 appctx->ctx.hlua.socket->s = NULL;
1464
1465 /* Wake all the task waiting for me. */
1466 hlua_com_wake(&appctx->ctx.hlua.wake_on_read);
1467 hlua_com_wake(&appctx->ctx.hlua.wake_on_write);
1468}
1469
1470/* If the garbage collectio of the object is launch, nobody
Willy Tarreau87b09662015-04-03 00:22:06 +02001471 * uses this object. If the stream does not exists, just quit.
1472 * Send the shutdown signal to the stream. In some cases,
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001473 * pending signal can rest in the read and write lists. destroy
1474 * it.
1475 */
1476__LJMP static int hlua_socket_gc(lua_State *L)
1477{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001478 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001479 struct appctx *appctx;
1480
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001481 MAY_LJMP(check_args(L, 1, "__gc"));
1482
1483 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001484 if (!socket->s)
1485 return 0;
1486
Willy Tarreau87b09662015-04-03 00:22:06 +02001487 /* Remove all reference between the Lua stack and the coroutine stream. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001488 appctx = objt_appctx(socket->s->si[0].end);
Willy Tarreaue7dff022015-04-03 01:14:29 +02001489 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001490 socket->s = NULL;
1491 appctx->ctx.hlua.socket = NULL;
1492
1493 return 0;
1494}
1495
1496/* The close function send shutdown signal and break the
Willy Tarreau87b09662015-04-03 00:22:06 +02001497 * links between the stream and the object.
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001498 */
1499__LJMP static int hlua_socket_close(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, "close"));
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 /* Close the stream and remove the associated stop task. */
Willy Tarreaue7dff022015-04-03 01:14:29 +02001511 stream_shutdown(socket->s, SF_ERR_KILLED);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001512 appctx = objt_appctx(socket->s->si[0].end);
1513 appctx->ctx.hlua.socket = NULL;
1514 socket->s = NULL;
1515
1516 return 0;
1517}
1518
1519/* This Lua function assumes that the stack contain three parameters.
1520 * 1 - USERDATA containing a struct socket
1521 * 2 - INTEGER with values of the macro defined below
1522 * If the integer is -1, we must read at most one line.
1523 * If the integer is -2, we ust read all the data until the
1524 * end of the stream.
1525 * If the integer is positive value, we must read a number of
1526 * bytes corresponding to this value.
1527 */
1528#define HLSR_READ_LINE (-1)
1529#define HLSR_READ_ALL (-2)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001530__LJMP static int hlua_socket_receive_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001531{
1532 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
1533 int wanted = lua_tointeger(L, 2);
1534 struct hlua *hlua = hlua_gethlua(L);
1535 struct appctx *appctx;
1536 int len;
1537 int nblk;
1538 char *blk1;
1539 int len1;
1540 char *blk2;
1541 int len2;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001542 int skip_at_end = 0;
Willy Tarreau81389672015-03-10 12:03:52 +01001543 struct channel *oc;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001544
1545 /* Check if this lua stack is schedulable. */
1546 if (!hlua || !hlua->task)
1547 WILL_LJMP(luaL_error(L, "The 'receive' function is only allowed in "
1548 "'frontend', 'backend' or 'task'"));
1549
1550 /* check for connection closed. If some data where read, return it. */
1551 if (!socket->s)
1552 goto connection_closed;
1553
Willy Tarreau94aa6172015-03-13 14:19:06 +01001554 oc = &socket->s->res;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001555 if (wanted == HLSR_READ_LINE) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001556 /* Read line. */
Willy Tarreau81389672015-03-10 12:03:52 +01001557 nblk = bo_getline_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001558 if (nblk < 0) /* Connection close. */
1559 goto connection_closed;
1560 if (nblk == 0) /* No data avalaible. */
1561 goto connection_empty;
Thierry FOURNIER00543922015-03-09 18:35:06 +01001562
1563 /* remove final \r\n. */
1564 if (nblk == 1) {
1565 if (blk1[len1-1] == '\n') {
1566 len1--;
1567 skip_at_end++;
1568 if (blk1[len1-1] == '\r') {
1569 len1--;
1570 skip_at_end++;
1571 }
1572 }
1573 }
1574 else {
1575 if (blk2[len2-1] == '\n') {
1576 len2--;
1577 skip_at_end++;
1578 if (blk2[len2-1] == '\r') {
1579 len2--;
1580 skip_at_end++;
1581 }
1582 }
1583 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001584 }
1585
1586 else if (wanted == HLSR_READ_ALL) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001587 /* Read all the available data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001588 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001589 if (nblk < 0) /* Connection close. */
1590 goto connection_closed;
1591 if (nblk == 0) /* No data avalaible. */
1592 goto connection_empty;
1593 }
1594
1595 else {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001596 /* Read a block of data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001597 nblk = bo_getblk_nc(oc, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001598 if (nblk < 0) /* Connection close. */
1599 goto connection_closed;
1600 if (nblk == 0) /* No data avalaible. */
1601 goto connection_empty;
1602
1603 if (len1 > wanted) {
1604 nblk = 1;
1605 len1 = wanted;
1606 } if (nblk == 2 && len1 + len2 > wanted)
1607 len2 = wanted - len1;
1608 }
1609
1610 len = len1;
1611
1612 luaL_addlstring(&socket->b, blk1, len1);
1613 if (nblk == 2) {
1614 len += len2;
1615 luaL_addlstring(&socket->b, blk2, len2);
1616 }
1617
1618 /* Consume data. */
Willy Tarreau81389672015-03-10 12:03:52 +01001619 bo_skip(oc, len + skip_at_end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001620
1621 /* Don't wait anything. */
Willy Tarreau828824a2015-04-19 17:20:03 +02001622 si_applet_done(&socket->s->si[0]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001623
1624 /* If the pattern reclaim to read all the data
1625 * in the connection, got out.
1626 */
1627 if (wanted == HLSR_READ_ALL)
1628 goto connection_empty;
1629 else if (wanted >= 0 && len < wanted)
1630 goto connection_empty;
1631
1632 /* Return result. */
1633 luaL_pushresult(&socket->b);
1634 return 1;
1635
1636connection_closed:
1637
1638 /* If the buffer containds data. */
1639 if (socket->b.n > 0) {
1640 luaL_pushresult(&socket->b);
1641 return 1;
1642 }
1643 lua_pushnil(L);
1644 lua_pushstring(L, "connection closed.");
1645 return 2;
1646
1647connection_empty:
1648
1649 appctx = objt_appctx(socket->s->si[0].end);
1650 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_read))
1651 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001652 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_receive_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001653 return 0;
1654}
1655
1656/* This Lus function gets two parameters. The first one can be string
1657 * or a number. If the string is "*l", the user require one line. If
1658 * the string is "*a", the user require all the content of the stream.
1659 * If the value is a number, the user require a number of bytes equal
1660 * to the value. The default value is "*l" (a line).
1661 *
1662 * This paraeter with a variable type is converted in integer. This
1663 * integer takes this values:
1664 * -1 : read a line
1665 * -2 : read all the stream
1666 * >0 : amount if bytes.
1667 *
1668 * The second parameter is optinal. It contains a string that must be
1669 * concatenated with the read data.
1670 */
1671__LJMP static int hlua_socket_receive(struct lua_State *L)
1672{
1673 int wanted = HLSR_READ_LINE;
1674 const char *pattern;
1675 int type;
1676 char *error;
1677 size_t len;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001678 struct hlua_socket *socket;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001679
1680 if (lua_gettop(L) < 1 || lua_gettop(L) > 3)
1681 WILL_LJMP(luaL_error(L, "The 'receive' function requires between 1 and 3 arguments."));
1682
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001683 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001684
1685 /* check for pattern. */
1686 if (lua_gettop(L) >= 2) {
1687 type = lua_type(L, 2);
1688 if (type == LUA_TSTRING) {
1689 pattern = lua_tostring(L, 2);
1690 if (strcmp(pattern, "*a") == 0)
1691 wanted = HLSR_READ_ALL;
1692 else if (strcmp(pattern, "*l") == 0)
1693 wanted = HLSR_READ_LINE;
1694 else {
1695 wanted = strtoll(pattern, &error, 10);
1696 if (*error != '\0')
1697 WILL_LJMP(luaL_error(L, "Unsupported pattern."));
1698 }
1699 }
1700 else if (type == LUA_TNUMBER) {
1701 wanted = lua_tointeger(L, 2);
1702 if (wanted < 0)
1703 WILL_LJMP(luaL_error(L, "Unsupported size."));
1704 }
1705 }
1706
1707 /* Set pattern. */
1708 lua_pushinteger(L, wanted);
1709 lua_replace(L, 2);
1710
1711 /* init bufffer, and fiil it wih prefix. */
1712 luaL_buffinit(L, &socket->b);
1713
1714 /* Check prefix. */
1715 if (lua_gettop(L) >= 3) {
1716 if (lua_type(L, 3) != LUA_TSTRING)
1717 WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix"));
1718 pattern = lua_tolstring(L, 3, &len);
1719 luaL_addlstring(&socket->b, pattern, len);
1720 }
1721
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001722 return __LJMP(hlua_socket_receive_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001723}
1724
1725/* Write the Lua input string in the output buffer.
1726 * This fucntion returns a yield if no space are available.
1727 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001728static int hlua_socket_write_yield(struct lua_State *L,int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001729{
1730 struct hlua_socket *socket;
1731 struct hlua *hlua = hlua_gethlua(L);
1732 struct appctx *appctx;
1733 size_t buf_len;
1734 const char *buf;
1735 int len;
1736 int send_len;
1737 int sent;
1738
1739 /* Check if this lua stack is schedulable. */
1740 if (!hlua || !hlua->task)
1741 WILL_LJMP(luaL_error(L, "The 'write' function is only allowed in "
1742 "'frontend', 'backend' or 'task'"));
1743
1744 /* Get object */
1745 socket = MAY_LJMP(hlua_checksocket(L, 1));
1746 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001747 sent = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001748
1749 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001750 if (!socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001751 lua_pushinteger(L, -1);
1752 return 1;
1753 }
1754
1755 /* Update the input buffer data. */
1756 buf += sent;
1757 send_len = buf_len - sent;
1758
1759 /* All the data are sent. */
1760 if (sent >= buf_len)
1761 return 1; /* Implicitly return the length sent. */
1762
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001763 /* Check if the buffer is avalaible because HAProxy doesn't allocate
1764 * the request buffer if its not required.
1765 */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01001766 if (socket->s->req.buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02001767 if (!stream_alloc_recv_buffer(&socket->s->req)) {
Willy Tarreau350f4872014-11-28 14:42:25 +01001768 socket->s->si[0].flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIER486d52a2015-03-09 17:51:43 +01001769 goto hlua_socket_write_yield_return;
1770 }
1771 }
1772
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001773 /* Check for avalaible space. */
Willy Tarreau94aa6172015-03-13 14:19:06 +01001774 len = buffer_total_space(socket->s->req.buf);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001775 if (len <= 0)
1776 goto hlua_socket_write_yield_return;
1777
1778 /* send data */
1779 if (len < send_len)
1780 send_len = len;
Willy Tarreau94aa6172015-03-13 14:19:06 +01001781 len = bi_putblk(&socket->s->req, buf+sent, send_len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001782
1783 /* "Not enough space" (-1), "Buffer too little to contain
1784 * the data" (-2) are not expected because the available length
1785 * is tested.
1786 * Other unknown error are also not expected.
1787 */
1788 if (len <= 0) {
Willy Tarreaubc18da12015-03-13 14:00:47 +01001789 if (len == -1)
Willy Tarreau94aa6172015-03-13 14:19:06 +01001790 socket->s->req.flags |= CF_WAKE_WRITE;
Willy Tarreaubc18da12015-03-13 14:00:47 +01001791
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001792 MAY_LJMP(hlua_socket_close(L));
1793 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001794 lua_pushinteger(L, -1);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001795 return 1;
1796 }
1797
1798 /* update buffers. */
Willy Tarreau828824a2015-04-19 17:20:03 +02001799 si_applet_done(&socket->s->si[0]);
Willy Tarreau94aa6172015-03-13 14:19:06 +01001800 socket->s->req.rex = TICK_ETERNITY;
1801 socket->s->res.wex = TICK_ETERNITY;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001802
1803 /* Update length sent. */
1804 lua_pop(L, 1);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001805 lua_pushinteger(L, sent + len);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001806
1807 /* All the data buffer is sent ? */
1808 if (sent + len >= buf_len)
1809 return 1;
1810
1811hlua_socket_write_yield_return:
1812 appctx = objt_appctx(socket->s->si[0].end);
1813 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
1814 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01001815 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_write_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001816 return 0;
1817}
1818
1819/* This function initiate the send of data. It just check the input
1820 * parameters and push an integer in the Lua stack that contain the
1821 * amount of data writed in the buffer. This is used by the function
1822 * "hlua_socket_write_yield" that can yield.
1823 *
1824 * The Lua function gets between 3 and 4 parameters. The first one is
1825 * the associated object. The second is a string buffer. The third is
1826 * a facultative integer that represents where is the buffer position
1827 * of the start of the data that can send. The first byte is the
1828 * position "1". The default value is "1". The fourth argument is a
1829 * facultative integer that represents where is the buffer position
1830 * of the end of the data that can send. The default is the last byte.
1831 */
1832static int hlua_socket_send(struct lua_State *L)
1833{
1834 int i;
1835 int j;
1836 const char *buf;
1837 size_t buf_len;
1838
1839 /* Check number of arguments. */
1840 if (lua_gettop(L) < 2 || lua_gettop(L) > 4)
1841 WILL_LJMP(luaL_error(L, "'send' needs between 2 and 4 arguments"));
1842
1843 /* Get the string. */
1844 buf = MAY_LJMP(luaL_checklstring(L, 2, &buf_len));
1845
1846 /* Get and check j. */
1847 if (lua_gettop(L) == 4) {
1848 j = MAY_LJMP(luaL_checkinteger(L, 4));
1849 if (j < 0)
1850 j = buf_len + j + 1;
1851 if (j > buf_len)
1852 j = buf_len + 1;
1853 lua_pop(L, 1);
1854 }
1855 else
1856 j = buf_len;
1857
1858 /* Get and check i. */
1859 if (lua_gettop(L) == 3) {
1860 i = MAY_LJMP(luaL_checkinteger(L, 3));
1861 if (i < 0)
1862 i = buf_len + i + 1;
1863 if (i > buf_len)
1864 i = buf_len + 1;
1865 lua_pop(L, 1);
1866 } else
1867 i = 1;
1868
1869 /* Check bth i and j. */
1870 if (i > j) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001871 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001872 return 1;
1873 }
1874 if (i == 0 && j == 0) {
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001875 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001876 return 1;
1877 }
1878 if (i == 0)
1879 i = 1;
1880 if (j == 0)
1881 j = 1;
1882
1883 /* Pop the string. */
1884 lua_pop(L, 1);
1885
1886 /* Update the buffer length. */
1887 buf += i - 1;
1888 buf_len = j - i + 1;
1889 lua_pushlstring(L, buf, buf_len);
1890
1891 /* This unsigned is used to remember the amount of sent data. */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001892 lua_pushinteger(L, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001893
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01001894 return MAY_LJMP(hlua_socket_write_yield(L, 0, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001895}
1896
Willy Tarreau22b0a682015-06-17 19:43:49 +02001897#define SOCKET_INFO_MAX_LEN sizeof("[0000:0000:0000:0000:0000:0000:0000:0000]:12345")
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001898__LJMP static inline int hlua_socket_info(struct lua_State *L, struct sockaddr_storage *addr)
1899{
1900 static char buffer[SOCKET_INFO_MAX_LEN];
1901 int ret;
1902 int len;
1903 char *p;
1904
1905 ret = addr_to_str(addr, buffer+1, SOCKET_INFO_MAX_LEN-1);
1906 if (ret <= 0) {
1907 lua_pushnil(L);
1908 return 1;
1909 }
1910
1911 if (ret == AF_UNIX) {
1912 lua_pushstring(L, buffer+1);
1913 return 1;
1914 }
1915 else if (ret == AF_INET6) {
1916 buffer[0] = '[';
1917 len = strlen(buffer);
1918 buffer[len] = ']';
1919 len++;
1920 buffer[len] = ':';
1921 len++;
1922 p = buffer;
1923 }
1924 else if (ret == AF_INET) {
1925 p = buffer + 1;
1926 len = strlen(p);
1927 p[len] = ':';
1928 len++;
1929 }
1930 else {
1931 lua_pushnil(L);
1932 return 1;
1933 }
1934
1935 if (port_to_str(addr, p + len, SOCKET_INFO_MAX_LEN-1 - len) <= 0) {
1936 lua_pushnil(L);
1937 return 1;
1938 }
1939
1940 lua_pushstring(L, p);
1941 return 1;
1942}
1943
1944/* Returns information about the peer of the connection. */
1945__LJMP static int hlua_socket_getpeername(struct lua_State *L)
1946{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001947 struct hlua_socket *socket;
1948 struct connection *conn;
1949
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001950 MAY_LJMP(check_args(L, 1, "getpeername"));
1951
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001952 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001953
1954 /* Check if the tcp object is avalaible. */
1955 if (!socket->s) {
1956 lua_pushnil(L);
1957 return 1;
1958 }
1959
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001960 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001961 if (!conn) {
1962 lua_pushnil(L);
1963 return 1;
1964 }
1965
1966 if (!(conn->flags & CO_FL_ADDR_TO_SET)) {
1967 unsigned int salen = sizeof(conn->addr.to);
1968 if (getpeername(conn->t.sock.fd, (struct sockaddr *)&conn->addr.to, &salen) == -1) {
1969 lua_pushnil(L);
1970 return 1;
1971 }
1972 conn->flags |= CO_FL_ADDR_TO_SET;
1973 }
1974
1975 return MAY_LJMP(hlua_socket_info(L, &conn->addr.to));
1976}
1977
1978/* Returns information about my connection side. */
1979static int hlua_socket_getsockname(struct lua_State *L)
1980{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001981 struct hlua_socket *socket;
1982 struct connection *conn;
1983
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001984 MAY_LJMP(check_args(L, 1, "getsockname"));
1985
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001986 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001987
1988 /* Check if the tcp object is avalaible. */
1989 if (!socket->s) {
1990 lua_pushnil(L);
1991 return 1;
1992 }
1993
Willy Tarreau80f5fae2015-02-27 16:38:20 +01001994 conn = objt_conn(socket->s->si[1].end);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01001995 if (!conn) {
1996 lua_pushnil(L);
1997 return 1;
1998 }
1999
2000 if (!(conn->flags & CO_FL_ADDR_FROM_SET)) {
2001 unsigned int salen = sizeof(conn->addr.from);
2002 if (getsockname(conn->t.sock.fd, (struct sockaddr *)&conn->addr.from, &salen) == -1) {
2003 lua_pushnil(L);
2004 return 1;
2005 }
2006 conn->flags |= CO_FL_ADDR_FROM_SET;
2007 }
2008
2009 return hlua_socket_info(L, &conn->addr.from);
2010}
2011
2012/* This struct define the applet. */
Willy Tarreau30576452015-04-13 13:50:30 +02002013static struct applet update_applet = {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002014 .obj_type = OBJ_TYPE_APPLET,
2015 .name = "<LUA_TCP>",
2016 .fct = hlua_socket_handler,
2017 .release = hlua_socket_release,
2018};
2019
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002020__LJMP static int hlua_socket_connect_yield(struct lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002021{
2022 struct hlua_socket *socket = MAY_LJMP(hlua_checksocket(L, 1));
2023 struct hlua *hlua = hlua_gethlua(L);
2024 struct appctx *appctx;
2025
2026 /* Check for connection close. */
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002027 if (!hlua || !socket->s || channel_output_closed(&socket->s->req)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002028 lua_pushnil(L);
2029 lua_pushstring(L, "Can't connect");
2030 return 2;
2031 }
2032
2033 appctx = objt_appctx(socket->s->si[0].end);
2034
2035 /* Check for connection established. */
2036 if (appctx->ctx.hlua.connected) {
2037 lua_pushinteger(L, 1);
2038 return 1;
2039 }
2040
2041 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2042 WILL_LJMP(luaL_error(L, "out of memory error"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002043 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002044 return 0;
2045}
2046
2047/* This function fail or initite the connection. */
2048__LJMP static int hlua_socket_connect(struct lua_State *L)
2049{
2050 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002051 int port;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002052 const char *ip;
2053 struct connection *conn;
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002054 struct hlua *hlua;
2055 struct appctx *appctx;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002056
2057 MAY_LJMP(check_args(L, 3, "connect"));
2058
2059 /* Get args. */
2060 socket = MAY_LJMP(hlua_checksocket(L, 1));
2061 ip = MAY_LJMP(luaL_checkstring(L, 2));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002062 port = MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002063
Willy Tarreau973a5422015-08-05 21:47:23 +02002064 conn = si_alloc_conn(&socket->s->si[1]);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002065 if (!conn)
2066 WILL_LJMP(luaL_error(L, "connect: internal error"));
2067
2068 /* Parse ip address. */
2069 conn->addr.to.ss_family = AF_UNSPEC;
2070 if (!str2ip2(ip, &conn->addr.to, 0))
2071 WILL_LJMP(luaL_error(L, "connect: cannot parse ip address '%s'", ip));
2072
2073 /* Set port. */
2074 if (conn->addr.to.ss_family == AF_INET)
2075 ((struct sockaddr_in *)&conn->addr.to)->sin_port = htons(port);
2076 else if (conn->addr.to.ss_family == AF_INET6)
2077 ((struct sockaddr_in6 *)&conn->addr.to)->sin6_port = htons(port);
2078
2079 /* it is important not to call the wakeup function directly but to
2080 * pass through task_wakeup(), because this one knows how to apply
2081 * priorities to tasks.
2082 */
2083 task_wakeup(socket->s->task, TASK_WOKEN_INIT);
2084
Thierry FOURNIER95ad96a2015-03-09 18:12:40 +01002085 hlua = hlua_gethlua(L);
2086 appctx = objt_appctx(socket->s->si[0].end);
2087 if (!hlua_com_new(hlua, &appctx->ctx.hlua.wake_on_write))
2088 WILL_LJMP(luaL_error(L, "out of memory"));
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002089 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_socket_connect_yield, TICK_ETERNITY, 0));
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002090
2091 return 0;
2092}
2093
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002094#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002095__LJMP static int hlua_socket_connect_ssl(struct lua_State *L)
2096{
2097 struct hlua_socket *socket;
2098
2099 MAY_LJMP(check_args(L, 3, "connect_ssl"));
2100 socket = MAY_LJMP(hlua_checksocket(L, 1));
2101 socket->s->target = &socket_ssl.obj_type;
2102 return MAY_LJMP(hlua_socket_connect(L));
2103}
Baptiste Assmann84bb4932015-03-02 21:40:06 +01002104#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002105
2106__LJMP static int hlua_socket_setoption(struct lua_State *L)
2107{
2108 return 0;
2109}
2110
2111__LJMP static int hlua_socket_settimeout(struct lua_State *L)
2112{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002113 struct hlua_socket *socket;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002114 int tmout;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002115
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002116 MAY_LJMP(check_args(L, 2, "settimeout"));
2117
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002118 socket = MAY_LJMP(hlua_checksocket(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002119 tmout = MAY_LJMP(luaL_checkinteger(L, 2)) * 1000;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002120
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01002121 socket->s->req.rto = tmout;
2122 socket->s->req.wto = tmout;
2123 socket->s->res.rto = tmout;
2124 socket->s->res.wto = tmout;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002125
2126 return 0;
2127}
2128
2129__LJMP static int hlua_socket_new(lua_State *L)
2130{
2131 struct hlua_socket *socket;
2132 struct appctx *appctx;
Willy Tarreau15b5e142015-04-04 14:38:25 +02002133 struct session *sess;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002134 struct stream *strm;
Willy Tarreaud420a972015-04-06 00:39:18 +02002135 struct task *task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002136
2137 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002138 if (!lua_checkstack(L, 3)) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002139 hlua_pusherror(L, "socket: full stack");
2140 goto out_fail_conf;
2141 }
2142
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002143 /* Create the object: obj[0] = userdata. */
2144 lua_newtable(L);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002145 socket = MAY_LJMP(lua_newuserdata(L, sizeof(*socket)));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002146 lua_rawseti(L, -2, 0);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002147 memset(socket, 0, sizeof(*socket));
2148
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002149 /* Check if the various memory pools are intialized. */
Willy Tarreau87b09662015-04-03 00:22:06 +02002150 if (!pool2_stream || !pool2_buffer) {
Thierry FOURNIER4a6170c2015-03-09 17:07:10 +01002151 hlua_pusherror(L, "socket: uninitialized pools.");
2152 goto out_fail_conf;
2153 }
2154
Willy Tarreau87b09662015-04-03 00:22:06 +02002155 /* Pop a class stream metatable and affect it to the userdata. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002156 lua_rawgeti(L, LUA_REGISTRYINDEX, class_socket_ref);
2157 lua_setmetatable(L, -2);
2158
Willy Tarreaud420a972015-04-06 00:39:18 +02002159 /* Create the applet context */
2160 appctx = appctx_new(&update_applet);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002161 if (!appctx) {
2162 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002163 goto out_fail_conf;
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002164 }
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002165
Willy Tarreaud420a972015-04-06 00:39:18 +02002166 appctx->ctx.hlua.socket = socket;
2167 appctx->ctx.hlua.connected = 0;
2168 LIST_INIT(&appctx->ctx.hlua.wake_on_write);
2169 LIST_INIT(&appctx->ctx.hlua.wake_on_read);
Willy Tarreaub2bf8332015-04-04 15:58:58 +02002170
Willy Tarreaud420a972015-04-06 00:39:18 +02002171 /* Now create a session, task and stream for this applet */
2172 sess = session_new(&socket_proxy, NULL, &appctx->obj_type);
2173 if (!sess) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002174 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002175 goto out_fail_sess;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002176 }
2177
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002178 task = task_new();
2179 if (!task) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002180 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaufeb76402015-04-03 14:10:06 +02002181 goto out_fail_task;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002182 }
Willy Tarreaud420a972015-04-06 00:39:18 +02002183 task->nice = 0;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002184
Willy Tarreau73b65ac2015-04-08 18:26:29 +02002185 strm = stream_new(sess, task, &appctx->obj_type);
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002186 if (!strm) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002187 hlua_pusherror(L, "socket: out of memory");
Willy Tarreaud420a972015-04-06 00:39:18 +02002188 goto out_fail_stream;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002189 }
2190
Willy Tarreaud420a972015-04-06 00:39:18 +02002191 /* Configure an empty Lua for the stream. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002192 socket->s = strm;
2193 strm->hlua.T = NULL;
2194 strm->hlua.Tref = LUA_REFNIL;
2195 strm->hlua.Mref = LUA_REFNIL;
2196 strm->hlua.nargs = 0;
2197 strm->hlua.flags = 0;
2198 LIST_INIT(&strm->hlua.com);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002199
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002200 /* Configure "right" stream interface. this "si" is used to connect
2201 * and retrieve data from the server. The connection is initialized
2202 * with the "struct server".
2203 */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002204 si_set_state(&strm->si[1], SI_ST_ASS);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002205
2206 /* Force destination server. */
Willy Tarreau61cf7c82015-04-06 00:48:33 +02002207 strm->flags |= SF_DIRECT | SF_ASSIGNED | SF_ADDR_SET | SF_BE_ASSIGNED;
2208 strm->target = &socket_tcp.obj_type;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002209
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002210 /* Update statistics counters. */
2211 socket_proxy.feconn++; /* beconn will be increased later */
2212 jobs++;
2213 totalconn++;
2214
2215 /* Return yield waiting for connection. */
2216 return 1;
2217
Willy Tarreaud420a972015-04-06 00:39:18 +02002218 out_fail_stream:
2219 task_free(task);
2220 out_fail_task:
Willy Tarreau11c36242015-04-04 15:54:03 +02002221 session_free(sess);
Willy Tarreaud420a972015-04-06 00:39:18 +02002222 out_fail_sess:
2223 appctx_free(appctx);
2224 out_fail_conf:
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01002225 WILL_LJMP(lua_error(L));
2226 return 0;
2227}
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01002228
2229/*
2230 *
2231 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002232 * Class Channel
2233 *
2234 *
2235 */
2236
2237/* Returns the struct hlua_channel join to the class channel in the
2238 * stack entry "ud" or throws an argument error.
2239 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002240__LJMP static struct channel *hlua_checkchannel(lua_State *L, int ud)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002241{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002242 return (struct channel *)MAY_LJMP(hlua_checkudata(L, ud, class_channel_ref));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002243}
2244
Willy Tarreau47860ed2015-03-10 14:07:50 +01002245/* Pushes the channel onto the top of the stack. If the stask does not have a
2246 * free slots, the function fails and returns 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002247 */
Willy Tarreau2a71af42015-03-10 13:51:50 +01002248static int hlua_channel_new(lua_State *L, struct channel *channel)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002249{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002250 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002251 if (!lua_checkstack(L, 3))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002252 return 0;
2253
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002254 lua_newtable(L);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002255 lua_pushlightuserdata(L, channel);
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01002256 lua_rawseti(L, -2, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002257
2258 /* Pop a class sesison metatable and affect it to the userdata. */
2259 lua_rawgeti(L, LUA_REGISTRYINDEX, class_channel_ref);
2260 lua_setmetatable(L, -2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002261 return 1;
2262}
2263
2264/* Duplicate all the data present in the input channel and put it
2265 * in a string LUA variables. Returns -1 and push a nil value in
2266 * the stack if the channel is closed and all the data are consumed,
2267 * returns 0 if no data are available, otherwise it returns the length
2268 * of the builded string.
2269 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002270static inline int _hlua_channel_dup(struct channel *chn, lua_State *L)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002271{
2272 char *blk1;
2273 char *blk2;
2274 int len1;
2275 int len2;
2276 int ret;
2277 luaL_Buffer b;
2278
Willy Tarreau47860ed2015-03-10 14:07:50 +01002279 ret = bi_getblk_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002280 if (unlikely(ret == 0))
2281 return 0;
2282
2283 if (unlikely(ret < 0)) {
2284 lua_pushnil(L);
2285 return -1;
2286 }
2287
2288 luaL_buffinit(L, &b);
2289 luaL_addlstring(&b, blk1, len1);
2290 if (unlikely(ret == 2))
2291 luaL_addlstring(&b, blk2, len2);
2292 luaL_pushresult(&b);
2293
2294 if (unlikely(ret == 2))
2295 return len1 + len2;
2296 return len1;
2297}
2298
2299/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2300 * a yield. This function keep the data in the buffer.
2301 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002302__LJMP static int hlua_channel_dup_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002303{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002304 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002305
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002306 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2307
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002308 if (_hlua_channel_dup(chn, L) == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002309 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_dup_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002310 return 1;
2311}
2312
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002313/* Check arguments for the function "hlua_channel_dup_yield". */
2314__LJMP static int hlua_channel_dup(lua_State *L)
2315{
2316 MAY_LJMP(check_args(L, 1, "dup"));
2317 MAY_LJMP(hlua_checkchannel(L, 1));
2318 return MAY_LJMP(hlua_channel_dup_yield(L, 0, 0));
2319}
2320
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002321/* "_hlua_channel_dup" wrapper. If no data are available, it returns
2322 * a yield. This function consumes the data in the buffer. It returns
2323 * a string containing the data or a nil pointer if no data are available
2324 * and the channel is closed.
2325 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002326__LJMP static int hlua_channel_get_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002327{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002328 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002329 int ret;
2330
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002331 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002332
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002333 ret = _hlua_channel_dup(chn, L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002334 if (unlikely(ret == 0))
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002335 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_get_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002336
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002337 if (unlikely(ret == -1))
2338 return 1;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002339
Willy Tarreau47860ed2015-03-10 14:07:50 +01002340 chn->buf->i -= ret;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002341 return 1;
2342}
2343
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002344/* Check arguments for the fucntion "hlua_channel_get_yield". */
2345__LJMP static int hlua_channel_get(lua_State *L)
2346{
2347 MAY_LJMP(check_args(L, 1, "get"));
2348 MAY_LJMP(hlua_checkchannel(L, 1));
2349 return MAY_LJMP(hlua_channel_get_yield(L, 0, 0));
2350}
2351
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002352/* This functions consumes and returns one line. If the channel is closed,
2353 * and the last data does not contains a final '\n', the data are returned
2354 * without the final '\n'. When no more data are avalaible, it returns nil
2355 * value.
2356 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002357__LJMP static int hlua_channel_getline_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002358{
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002359 char *blk1;
2360 char *blk2;
2361 int len1;
2362 int len2;
2363 int len;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002364 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002365 int ret;
2366 luaL_Buffer b;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002367
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002368 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2369
Willy Tarreau47860ed2015-03-10 14:07:50 +01002370 ret = bi_getline_nc(chn, &blk1, &len1, &blk2, &len2);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002371 if (ret == 0)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002372 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_getline_yield, TICK_ETERNITY, 0));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002373
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002374 if (ret == -1) {
2375 lua_pushnil(L);
2376 return 1;
2377 }
2378
2379 luaL_buffinit(L, &b);
2380 luaL_addlstring(&b, blk1, len1);
2381 len = len1;
2382 if (unlikely(ret == 2)) {
2383 luaL_addlstring(&b, blk2, len2);
2384 len += len2;
2385 }
2386 luaL_pushresult(&b);
Willy Tarreau47860ed2015-03-10 14:07:50 +01002387 buffer_replace2(chn->buf, chn->buf->p, chn->buf->p + len, NULL, 0);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002388 return 1;
2389}
2390
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002391/* Check arguments for the fucntion "hlua_channel_getline_yield". */
2392__LJMP static int hlua_channel_getline(lua_State *L)
2393{
2394 MAY_LJMP(check_args(L, 1, "getline"));
2395 MAY_LJMP(hlua_checkchannel(L, 1));
2396 return MAY_LJMP(hlua_channel_getline_yield(L, 0, 0));
2397}
2398
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002399/* This function takes a string as input, and append it at the
2400 * input side of channel. If the data is too big, but a space
2401 * is probably available after sending some data, the function
2402 * yield. If the data is bigger than the buffer, or if the
2403 * channel is closed, it returns -1. otherwise, it returns the
2404 * amount of data writed.
2405 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002406__LJMP static int hlua_channel_append_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002407{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002408 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002409 size_t len;
2410 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2411 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2412 int ret;
2413 int max;
2414
Willy Tarreau47860ed2015-03-10 14:07:50 +01002415 max = channel_recv_limit(chn) - buffer_len(chn->buf);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002416 if (max > len - l)
2417 max = len - l;
2418
Willy Tarreau47860ed2015-03-10 14:07:50 +01002419 ret = bi_putblk(chn, str + l, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002420 if (ret == -2 || ret == -3) {
2421 lua_pushinteger(L, -1);
2422 return 1;
2423 }
Willy Tarreaubc18da12015-03-13 14:00:47 +01002424 if (ret == -1) {
2425 chn->flags |= CF_WAKE_WRITE;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002426 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Willy Tarreaubc18da12015-03-13 14:00:47 +01002427 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002428 l += ret;
2429 lua_pop(L, 1);
2430 lua_pushinteger(L, l);
2431
Willy Tarreau47860ed2015-03-10 14:07:50 +01002432 max = channel_recv_limit(chn) - buffer_len(chn->buf);
2433 if (max == 0 && chn->buf->o == 0) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002434 /* There are no space avalaible, and the output buffer is empty.
2435 * in this case, we cannot add more data, so we cannot yield,
2436 * we return the amount of copyied data.
2437 */
2438 return 1;
2439 }
2440 if (l < len)
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002441 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_append_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002442 return 1;
2443}
2444
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002445/* just a wrapper of "hlua_channel_append_yield". It returns the length
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002446 * of the writed string, or -1 if the channel is closed or if the
2447 * buffer size is too little for the data.
2448 */
2449__LJMP static int hlua_channel_append(lua_State *L)
2450{
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002451 size_t len;
2452
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002453 MAY_LJMP(check_args(L, 2, "append"));
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002454 MAY_LJMP(hlua_checkchannel(L, 1));
2455 MAY_LJMP(luaL_checklstring(L, 2, &len));
2456 MAY_LJMP(luaL_checkinteger(L, 3));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002457 lua_pushinteger(L, 0);
2458
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002459 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002460}
2461
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002462/* just a wrapper of "hlua_channel_append_yield". This wrapper starts
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002463 * his process by cleaning the buffer. The result is a replacement
2464 * of the current data. It returns the length of the writed string,
2465 * or -1 if the channel is closed or if the buffer size is too
2466 * little for the data.
2467 */
2468__LJMP static int hlua_channel_set(lua_State *L)
2469{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002470 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002471
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002472 MAY_LJMP(check_args(L, 2, "set"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002473 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002474 lua_pushinteger(L, 0);
2475
Willy Tarreau47860ed2015-03-10 14:07:50 +01002476 chn->buf->i = 0;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002477
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002478 return MAY_LJMP(hlua_channel_append_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002479}
2480
2481/* Append data in the output side of the buffer. This data is immediatly
2482 * sent. The fcuntion returns the ammount of data writed. If the buffer
2483 * cannot contains the data, the function yield. The function returns -1
2484 * if the channel is closed.
2485 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002486__LJMP static int hlua_channel_send_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002487{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002488 struct channel *chn = MAY_LJMP(hlua_checkchannel(L, 1));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002489 size_t len;
2490 const char *str = MAY_LJMP(luaL_checklstring(L, 2, &len));
2491 int l = MAY_LJMP(luaL_checkinteger(L, 3));
2492 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002493 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002494
Willy Tarreau47860ed2015-03-10 14:07:50 +01002495 if (unlikely(channel_output_closed(chn))) {
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002496 lua_pushinteger(L, -1);
2497 return 1;
2498 }
2499
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002500 /* Check if the buffer is avalaible because HAProxy doesn't allocate
2501 * the request buffer if its not required.
2502 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002503 if (chn->buf->size == 0) {
Willy Tarreau87b09662015-04-03 00:22:06 +02002504 if (!stream_alloc_recv_buffer(chn)) {
Willy Tarreau47860ed2015-03-10 14:07:50 +01002505 chn_prod(chn)->flags |= SI_FL_WAIT_ROOM;
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002506 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIER3e3a6082015-03-05 17:06:12 +01002507 }
2508 }
2509
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002510 /* the writed data will be immediatly sent, so we can check
2511 * the avalaible space without taking in account the reserve.
2512 * The reserve is guaranted for the processing of incoming
2513 * data, because the buffer will be flushed.
2514 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002515 max = chn->buf->size - buffer_len(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002516
2517 /* If there are no space avalaible, and the output buffer is empty.
2518 * in this case, we cannot add more data, so we cannot yield,
2519 * we return the amount of copyied data.
2520 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002521 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002522 return 1;
2523
2524 /* Adjust the real required length. */
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002525 if (max > len - l)
2526 max = len - l;
2527
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002528 /* The buffer avalaible size may be not contiguous. This test
2529 * detects a non contiguous buffer and realign it.
2530 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002531 if (bi_space_for_replace(chn->buf) < max)
2532 buffer_slow_realign(chn->buf);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002533
2534 /* Copy input data in the buffer. */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002535 max = buffer_replace2(chn->buf, chn->buf->p, chn->buf->p, str + l, max);
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002536
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002537 /* buffer replace considers that the input part is filled.
2538 * so, I must forward these new data in the output part.
2539 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002540 b_adv(chn->buf, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002541
2542 l += max;
2543 lua_pop(L, 1);
2544 lua_pushinteger(L, l);
2545
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002546 /* If there are no space avalaible, and the output buffer is empty.
2547 * in this case, we cannot add more data, so we cannot yield,
2548 * we return the amount of copyied data.
2549 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002550 max = chn->buf->size - buffer_len(chn->buf);
2551 if (max == 0 && chn->buf->o == 0)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002552 return 1;
Thierry FOURNIERdeb5d732015-03-06 01:07:45 +01002553
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002554 if (l < len) {
2555 /* If we are waiting for space in the response buffer, we
2556 * must set the flag WAKERESWR. This flag required the task
2557 * wake up if any activity is detected on the response buffer.
2558 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002559 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002560 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002561 else
2562 HLUA_SET_WAKEREQWR(hlua);
2563 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_send_yield, TICK_ETERNITY, 0));
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002564 }
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002565
2566 return 1;
2567}
2568
2569/* Just a wraper of "_hlua_channel_send". This wrapper permits
2570 * yield the LUA process, and resume it without checking the
2571 * input arguments.
2572 */
2573__LJMP static int hlua_channel_send(lua_State *L)
2574{
2575 MAY_LJMP(check_args(L, 2, "send"));
2576 lua_pushinteger(L, 0);
2577
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002578 return MAY_LJMP(hlua_channel_send_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002579}
2580
2581/* This function forward and amount of butes. The data pass from
2582 * the input side of the buffer to the output side, and can be
2583 * forwarded. This function never fails.
2584 *
2585 * The Lua function takes an amount of bytes to be forwarded in
2586 * imput. It returns the number of bytes forwarded.
2587 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002588__LJMP static int hlua_channel_forward_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002589{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002590 struct channel *chn;
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002591 int len;
2592 int l;
2593 int max;
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002594 struct hlua *hlua = hlua_gethlua(L);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002595
2596 chn = MAY_LJMP(hlua_checkchannel(L, 1));
2597 len = MAY_LJMP(luaL_checkinteger(L, 2));
2598 l = MAY_LJMP(luaL_checkinteger(L, -1));
2599
2600 max = len - l;
Willy Tarreau47860ed2015-03-10 14:07:50 +01002601 if (max > chn->buf->i)
2602 max = chn->buf->i;
2603 channel_forward(chn, max);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002604 l += max;
2605
2606 lua_pop(L, 1);
2607 lua_pushinteger(L, l);
2608
2609 /* Check if it miss bytes to forward. */
2610 if (l < len) {
2611 /* The the input channel or the output channel are closed, we
2612 * must return the amount of data forwarded.
2613 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002614 if (channel_input_closed(chn) || channel_output_closed(chn))
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002615 return 1;
2616
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002617 /* If we are waiting for space data in the response buffer, we
2618 * must set the flag WAKERESWR. This flag required the task
2619 * wake up if any activity is detected on the response buffer.
2620 */
Willy Tarreau47860ed2015-03-10 14:07:50 +01002621 if (chn->flags & CF_ISRESP)
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002622 HLUA_SET_WAKERESWR(hlua);
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01002623 else
2624 HLUA_SET_WAKEREQWR(hlua);
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01002625
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002626 /* Otherwise, we can yield waiting for new data in the inpout side. */
Thierry FOURNIER4abd3ae2015-03-03 17:29:06 +01002627 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_channel_forward_yield, TICK_ETERNITY, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002628 }
2629
2630 return 1;
2631}
2632
2633/* Just check the input and prepare the stack for the previous
2634 * function "hlua_channel_forward_yield"
2635 */
2636__LJMP static int hlua_channel_forward(lua_State *L)
2637{
2638 MAY_LJMP(check_args(L, 2, "forward"));
2639 MAY_LJMP(hlua_checkchannel(L, 1));
2640 MAY_LJMP(luaL_checkinteger(L, 2));
2641
2642 lua_pushinteger(L, 0);
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01002643 return MAY_LJMP(hlua_channel_forward_yield(L, 0, 0));
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002644}
2645
2646/* Just returns the number of bytes available in the input
2647 * side of the buffer. This function never fails.
2648 */
2649__LJMP static int hlua_channel_get_in_len(lua_State *L)
2650{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002651 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002652
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002653 MAY_LJMP(check_args(L, 1, "get_in_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002654 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002655 lua_pushinteger(L, chn->buf->i);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002656 return 1;
2657}
2658
2659/* Just returns the number of bytes available in the output
2660 * side of the buffer. This function never fails.
2661 */
2662__LJMP static int hlua_channel_get_out_len(lua_State *L)
2663{
Willy Tarreau47860ed2015-03-10 14:07:50 +01002664 struct channel *chn;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002665
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002666 MAY_LJMP(check_args(L, 1, "get_out_len"));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01002667 chn = MAY_LJMP(hlua_checkchannel(L, 1));
Willy Tarreau47860ed2015-03-10 14:07:50 +01002668 lua_pushinteger(L, chn->buf->o);
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002669 return 1;
2670}
2671
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002672/*
2673 *
2674 *
2675 * Class Fetches
2676 *
2677 *
2678 */
2679
2680/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002681 * a class stream, otherwise it throws an error.
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002682 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002683__LJMP static struct hlua_smp *hlua_checkfetches(lua_State *L, int ud)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002684{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002685 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_fetches_ref));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002686}
2687
2688/* This function creates and push in the stack a fetch object according
2689 * with a current TXN.
2690 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002691static int hlua_fetches_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002692{
Willy Tarreau7073c472015-04-06 11:15:40 +02002693 struct hlua_smp *hsmp;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002694
2695 /* Check stack size. */
2696 if (!lua_checkstack(L, 3))
2697 return 0;
2698
2699 /* Create the object: obj[0] = userdata.
2700 * Note that the base of the Fetches object is the
2701 * transaction object.
2702 */
2703 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002704 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002705 lua_rawseti(L, -2, 0);
2706
Willy Tarreau7073c472015-04-06 11:15:40 +02002707 hsmp->s = txn->s;
2708 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002709 hsmp->stringsafe = stringsafe;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002710
2711 /* Pop a class sesison metatable and affect it to the userdata. */
2712 lua_rawgeti(L, LUA_REGISTRYINDEX, class_fetches_ref);
2713 lua_setmetatable(L, -2);
2714
2715 return 1;
2716}
2717
2718/* This function is an LUA binding. It is called with each sample-fetch.
2719 * It uses closure argument to store the associated sample-fetch. It
2720 * returns only one argument or throws an error. An error is thrown
2721 * only if an error is encountered during the argument parsing. If
2722 * the "sample-fetch" function fails, nil is returned.
2723 */
2724__LJMP static int hlua_run_sample_fetch(lua_State *L)
2725{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002726 struct hlua_smp *hsmp;
Willy Tarreau2ec22742015-03-10 14:27:20 +01002727 struct sample_fetch *f;
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002728 struct arg args[ARGM_NBARGS + 1];
2729 int i;
2730 struct sample smp;
2731
2732 /* Get closure arguments. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002733 f = (struct sample_fetch *)lua_touserdata(L, lua_upvalueindex(1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002734
2735 /* Get traditionnal arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002736 hsmp = MAY_LJMP(hlua_checkfetches(L, 1));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002737
2738 /* Get extra arguments. */
2739 for (i = 0; i < lua_gettop(L) - 1; i++) {
2740 if (i >= ARGM_NBARGS)
2741 break;
2742 hlua_lua2arg(L, i + 2, &args[i]);
2743 }
2744 args[i].type = ARGT_STOP;
2745
2746 /* Check arguments. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002747 MAY_LJMP(hlua_lua2arg_check(L, 2, args, f->arg_mask, hsmp->p));
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002748
2749 /* Run the special args checker. */
Willy Tarreau2ec22742015-03-10 14:27:20 +01002750 if (f->val_args && !f->val_args(args, NULL)) {
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002751 lua_pushfstring(L, "error in arguments");
2752 WILL_LJMP(lua_error(L));
2753 }
2754
2755 /* Initialise the sample. */
2756 memset(&smp, 0, sizeof(smp));
2757
2758 /* Run the sample fetch process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02002759 smp.px = hsmp->p;
2760 smp.sess = hsmp->s->sess;
2761 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002762 smp.opt = 0;
Thierry FOURNIER0786d052015-05-11 15:42:45 +02002763 if (!f->process(args, &smp, f->kw, f->private)) {
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002764 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002765 lua_pushstring(L, "");
2766 else
2767 lua_pushnil(L);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002768 return 1;
2769 }
2770
2771 /* Convert the returned sample in lua value. */
Willy Tarreaub2ccb562015-04-06 11:11:15 +02002772 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002773 hlua_smp2lua_str(L, &smp);
2774 else
2775 hlua_smp2lua(L, &smp);
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01002776 return 1;
2777}
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01002778
2779/*
2780 *
2781 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002782 * Class Converters
2783 *
2784 *
2785 */
2786
2787/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002788 * a class stream, otherwise it throws an error.
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002789 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002790__LJMP static struct hlua_smp *hlua_checkconverters(lua_State *L, int ud)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002791{
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002792 return (struct hlua_smp *)MAY_LJMP(hlua_checkudata(L, ud, class_converters_ref));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002793}
2794
2795/* This function creates and push in the stack a Converters object
2796 * according with a current TXN.
2797 */
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002798static int hlua_converters_new(lua_State *L, struct hlua_txn *txn, int stringsafe)
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002799{
Willy Tarreau7073c472015-04-06 11:15:40 +02002800 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002801
2802 /* Check stack size. */
2803 if (!lua_checkstack(L, 3))
2804 return 0;
2805
2806 /* Create the object: obj[0] = userdata.
2807 * Note that the base of the Converters object is the
2808 * same than the TXN object.
2809 */
2810 lua_newtable(L);
Willy Tarreau7073c472015-04-06 11:15:40 +02002811 hsmp = lua_newuserdata(L, sizeof(*hsmp));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002812 lua_rawseti(L, -2, 0);
2813
Willy Tarreau7073c472015-04-06 11:15:40 +02002814 hsmp->s = txn->s;
2815 hsmp->p = txn->p;
Willy Tarreau7073c472015-04-06 11:15:40 +02002816 hsmp->stringsafe = stringsafe;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002817
Willy Tarreau87b09662015-04-03 00:22:06 +02002818 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002819 lua_rawgeti(L, LUA_REGISTRYINDEX, class_converters_ref);
2820 lua_setmetatable(L, -2);
2821
2822 return 1;
2823}
2824
2825/* This function is an LUA binding. It is called with each converter.
2826 * It uses closure argument to store the associated converter. It
2827 * returns only one argument or throws an error. An error is thrown
2828 * only if an error is encountered during the argument parsing. If
2829 * the converter function function fails, nil is returned.
2830 */
2831__LJMP static int hlua_run_sample_conv(lua_State *L)
2832{
Willy Tarreauda5f1082015-04-06 11:17:13 +02002833 struct hlua_smp *hsmp;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002834 struct sample_conv *conv;
2835 struct arg args[ARGM_NBARGS + 1];
2836 int i;
2837 struct sample smp;
2838
2839 /* Get closure arguments. */
2840 conv = (struct sample_conv *)lua_touserdata(L, lua_upvalueindex(1));
2841
2842 /* Get traditionnal arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002843 hsmp = MAY_LJMP(hlua_checkconverters(L, 1));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002844
2845 /* Get extra arguments. */
2846 for (i = 0; i < lua_gettop(L) - 2; i++) {
2847 if (i >= ARGM_NBARGS)
2848 break;
2849 hlua_lua2arg(L, i + 3, &args[i]);
2850 }
2851 args[i].type = ARGT_STOP;
2852
2853 /* Check arguments. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002854 MAY_LJMP(hlua_lua2arg_check(L, 3, args, conv->arg_mask, hsmp->p));
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002855
2856 /* Run the special args checker. */
2857 if (conv->val_args && !conv->val_args(args, conv, "", 0, NULL)) {
2858 hlua_pusherror(L, "error in arguments");
2859 WILL_LJMP(lua_error(L));
2860 }
2861
2862 /* Initialise the sample. */
2863 if (!hlua_lua2smp(L, 2, &smp)) {
2864 hlua_pusherror(L, "error in the input argument");
2865 WILL_LJMP(lua_error(L));
2866 }
2867
2868 /* Apply expected cast. */
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002869 if (!sample_casts[smp.data.type][conv->in_type]) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002870 hlua_pusherror(L, "invalid input argument: cannot cast '%s' to '%s'",
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002871 smp_to_type[smp.data.type], smp_to_type[conv->in_type]);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002872 WILL_LJMP(lua_error(L));
2873 }
Thierry FOURNIER8c542ca2015-08-19 09:00:18 +02002874 if (sample_casts[smp.data.type][conv->in_type] != c_none &&
2875 !sample_casts[smp.data.type][conv->in_type](&smp)) {
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002876 hlua_pusherror(L, "error during the input argument casting");
2877 WILL_LJMP(lua_error(L));
2878 }
2879
2880 /* Run the sample conversion process. */
Thierry FOURNIER6879ad32015-05-11 11:54:58 +02002881 smp.px = hsmp->p;
2882 smp.sess = hsmp->s->sess;
2883 smp.strm = hsmp->s;
Thierry FOURNIER1d33b882015-05-11 15:25:29 +02002884 smp.opt = 0;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02002885 if (!conv->process(args, &smp, conv->private)) {
Willy Tarreauda5f1082015-04-06 11:17:13 +02002886 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002887 lua_pushstring(L, "");
2888 else
2889 lua_pushnil(L);
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002890 return 1;
2891 }
2892
2893 /* Convert the returned sample in lua value. */
Willy Tarreauda5f1082015-04-06 11:17:13 +02002894 if (hsmp->stringsafe)
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01002895 hlua_smp2lua_str(L, &smp);
2896 else
2897 hlua_smp2lua(L, &smp);
2898 return 1;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01002899}
2900
2901/*
2902 *
2903 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002904 * Class HTTP
2905 *
2906 *
2907 */
2908
2909/* Returns a struct hlua_txn if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02002910 * a class stream, otherwise it throws an error.
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002911 */
2912__LJMP static struct hlua_txn *hlua_checkhttp(lua_State *L, int ud)
2913{
2914 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_http_ref));
2915}
2916
2917/* This function creates and push in the stack a HTTP object
2918 * according with a current TXN.
2919 */
2920static int hlua_http_new(lua_State *L, struct hlua_txn *txn)
2921{
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002922 struct hlua_txn *htxn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002923
2924 /* Check stack size. */
2925 if (!lua_checkstack(L, 3))
2926 return 0;
2927
2928 /* Create the object: obj[0] = userdata.
2929 * Note that the base of the Converters object is the
2930 * same than the TXN object.
2931 */
2932 lua_newtable(L);
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002933 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002934 lua_rawseti(L, -2, 0);
2935
Willy Tarreau9a8ad862015-04-06 11:14:06 +02002936 htxn->s = txn->s;
2937 htxn->p = txn->p;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002938
Willy Tarreau87b09662015-04-03 00:22:06 +02002939 /* Pop a class stream metatable and affect it to the table. */
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002940 lua_rawgeti(L, LUA_REGISTRYINDEX, class_http_ref);
2941 lua_setmetatable(L, -2);
2942
2943 return 1;
2944}
2945
2946/* This function creates ans returns an array of HTTP headers.
2947 * This function does not fails. It is used as wrapper with the
2948 * 2 following functions.
2949 */
2950__LJMP static int hlua_http_get_headers(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
2951{
2952 const char *cur_ptr, *cur_next, *p;
2953 int old_idx, cur_idx;
2954 struct hdr_idx_elem *cur_hdr;
2955 const char *hn, *hv;
2956 int hnl, hvl;
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01002957 int type;
2958 const char *in;
2959 char *out;
2960 int len;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002961
2962 /* Create the table. */
2963 lua_newtable(L);
2964
Willy Tarreaueee5b512015-04-03 23:46:31 +02002965 if (!htxn->s->txn)
2966 return 1;
2967
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002968 /* Build array of headers. */
2969 old_idx = 0;
Willy Tarreaueee5b512015-04-03 23:46:31 +02002970 cur_next = msg->chn->buf->p + hdr_idx_first_pos(&htxn->s->txn->hdr_idx);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002971
2972 while (1) {
Willy Tarreaueee5b512015-04-03 23:46:31 +02002973 cur_idx = htxn->s->txn->hdr_idx.v[old_idx].next;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002974 if (!cur_idx)
2975 break;
2976 old_idx = cur_idx;
2977
Willy Tarreaueee5b512015-04-03 23:46:31 +02002978 cur_hdr = &htxn->s->txn->hdr_idx.v[cur_idx];
Thierry FOURNIER08504f42015-03-16 14:17:08 +01002979 cur_ptr = cur_next;
2980 cur_next = cur_ptr + cur_hdr->len + cur_hdr->cr + 1;
2981
2982 /* Now we have one full header at cur_ptr of len cur_hdr->len,
2983 * and the next header starts at cur_next. We'll check
2984 * this header in the list as well as against the default
2985 * rule.
2986 */
2987
2988 /* look for ': *'. */
2989 hn = cur_ptr;
2990 for (p = cur_ptr; p < cur_ptr + cur_hdr->len && *p != ':'; p++);
2991 if (p >= cur_ptr+cur_hdr->len)
2992 continue;
2993 hnl = p - hn;
2994 p++;
2995 while (p < cur_ptr+cur_hdr->len && ( *p == ' ' || *p == '\t' ))
2996 p++;
2997 if (p >= cur_ptr+cur_hdr->len)
2998 continue;
2999 hv = p;
3000 hvl = cur_ptr+cur_hdr->len-p;
3001
Thierry FOURNIER04c57b32015-03-18 13:43:10 +01003002 /* Lowercase the key. Don't check the size of trash, it have
3003 * the size of one buffer and the input data contains in one
3004 * buffer.
3005 */
3006 out = trash.str;
3007 for (in=hn; in<hn+hnl; in++, out++)
3008 *out = tolower(*in);
3009 *out = '\0';
3010
3011 /* Check for existing entry:
3012 * assume that the table is on the top of the stack, and
3013 * push the key in the stack, the function lua_gettable()
3014 * perform the lookup.
3015 */
3016 lua_pushlstring(L, trash.str, hnl);
3017 lua_gettable(L, -2);
3018 type = lua_type(L, -1);
3019
3020 switch (type) {
3021 case LUA_TNIL:
3022 /* Table not found, create it. */
3023 lua_pop(L, 1); /* remove the nil value. */
3024 lua_pushlstring(L, trash.str, hnl); /* push the header name as key. */
3025 lua_newtable(L); /* create and push empty table. */
3026 lua_pushlstring(L, hv, hvl); /* push header value. */
3027 lua_rawseti(L, -2, 0); /* index header value (pop it). */
3028 lua_rawset(L, -3); /* index new table with header name (pop the values). */
3029 break;
3030
3031 case LUA_TTABLE:
3032 /* Entry found: push the value in the table. */
3033 len = lua_rawlen(L, -1);
3034 lua_pushlstring(L, hv, hvl); /* push header value. */
3035 lua_rawseti(L, -2, len+1); /* index header value (pop it). */
3036 lua_pop(L, 1); /* remove the table (it is stored in the main table). */
3037 break;
3038
3039 default:
3040 /* Other cases are errors. */
3041 hlua_pusherror(L, "internal error during the parsing of headers.");
3042 WILL_LJMP(lua_error(L));
3043 }
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003044 }
3045
3046 return 1;
3047}
3048
3049__LJMP static int hlua_http_req_get_headers(lua_State *L)
3050{
3051 struct hlua_txn *htxn;
3052
3053 MAY_LJMP(check_args(L, 1, "req_get_headers"));
3054 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3055
Willy Tarreaueee5b512015-04-03 23:46:31 +02003056 return hlua_http_get_headers(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003057}
3058
3059__LJMP static int hlua_http_res_get_headers(lua_State *L)
3060{
3061 struct hlua_txn *htxn;
3062
3063 MAY_LJMP(check_args(L, 1, "res_get_headers"));
3064 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3065
Willy Tarreaueee5b512015-04-03 23:46:31 +02003066 return hlua_http_get_headers(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003067}
3068
3069/* This function replace full header, or just a value in
3070 * the request or in the response. It is a wrapper fir the
3071 * 4 following functions.
3072 */
3073__LJMP static inline int hlua_http_rep_hdr(lua_State *L, struct hlua_txn *htxn,
3074 struct http_msg *msg, int action)
3075{
3076 size_t name_len;
3077 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3078 const char *reg = MAY_LJMP(luaL_checkstring(L, 3));
3079 const char *value = MAY_LJMP(luaL_checkstring(L, 4));
3080 struct my_regex re;
3081
3082 if (!regex_comp(reg, &re, 1, 1, NULL))
3083 WILL_LJMP(luaL_argerror(L, 3, "invalid regex"));
3084
3085 http_transform_header_str(htxn->s, msg, name, name_len, value, &re, action);
3086 regex_free(&re);
3087 return 0;
3088}
3089
3090__LJMP static int hlua_http_req_rep_hdr(lua_State *L)
3091{
3092 struct hlua_txn *htxn;
3093
3094 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3095 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3096
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003097 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003098}
3099
3100__LJMP static int hlua_http_res_rep_hdr(lua_State *L)
3101{
3102 struct hlua_txn *htxn;
3103
3104 MAY_LJMP(check_args(L, 4, "res_rep_hdr"));
3105 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3106
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003107 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->rsp, ACT_HTTP_REPLACE_HDR));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003108}
3109
3110__LJMP static int hlua_http_req_rep_val(lua_State *L)
3111{
3112 struct hlua_txn *htxn;
3113
3114 MAY_LJMP(check_args(L, 4, "req_rep_hdr"));
3115 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3116
Thierry FOURNIER0ea5c7f2015-08-05 19:05:19 +02003117 return MAY_LJMP(hlua_http_rep_hdr(L, htxn, &htxn->s->txn->req, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003118}
3119
3120__LJMP static int hlua_http_res_rep_val(lua_State *L)
3121{
3122 struct hlua_txn *htxn;
3123
3124 MAY_LJMP(check_args(L, 4, "res_rep_val"));
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->rsp, ACT_HTTP_REPLACE_VAL));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003128}
3129
3130/* This function deletes all the occurences of an header.
3131 * It is a wrapper for the 2 following functions.
3132 */
3133__LJMP static inline int hlua_http_del_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3134{
3135 size_t len;
3136 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3137 struct hdr_ctx ctx;
Willy Tarreaueee5b512015-04-03 23:46:31 +02003138 struct http_txn *txn = htxn->s->txn;
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003139
3140 ctx.idx = 0;
3141 while (http_find_header2(name, len, msg->chn->buf->p, &txn->hdr_idx, &ctx))
3142 http_remove_header2(msg, &txn->hdr_idx, &ctx);
3143 return 0;
3144}
3145
3146__LJMP static int hlua_http_req_del_hdr(lua_State *L)
3147{
3148 struct hlua_txn *htxn;
3149
3150 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3151 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3152
Willy Tarreaueee5b512015-04-03 23:46:31 +02003153 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003154}
3155
3156__LJMP static int hlua_http_res_del_hdr(lua_State *L)
3157{
3158 struct hlua_txn *htxn;
3159
3160 MAY_LJMP(check_args(L, 2, "req_del_hdr"));
3161 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3162
Willy Tarreaueee5b512015-04-03 23:46:31 +02003163 return hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003164}
3165
3166/* This function adds an header. It is a wrapper used by
3167 * the 2 following functions.
3168 */
3169__LJMP static inline int hlua_http_add_hdr(lua_State *L, struct hlua_txn *htxn, struct http_msg *msg)
3170{
3171 size_t name_len;
3172 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
3173 size_t value_len;
3174 const char *value = MAY_LJMP(luaL_checklstring(L, 3, &value_len));
3175 char *p;
3176
3177 /* Check length. */
3178 trash.len = value_len + name_len + 2;
3179 if (trash.len > trash.size)
3180 return 0;
3181
3182 /* Creates the header string. */
3183 p = trash.str;
3184 memcpy(p, name, name_len);
3185 p += name_len;
3186 *p = ':';
3187 p++;
3188 *p = ' ';
3189 p++;
3190 memcpy(p, value, value_len);
3191
Willy Tarreaueee5b512015-04-03 23:46:31 +02003192 lua_pushboolean(L, http_header_add_tail2(msg, &htxn->s->txn->hdr_idx,
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003193 trash.str, trash.len) != 0);
3194
3195 return 0;
3196}
3197
3198__LJMP static int hlua_http_req_add_hdr(lua_State *L)
3199{
3200 struct hlua_txn *htxn;
3201
3202 MAY_LJMP(check_args(L, 3, "req_add_hdr"));
3203 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3204
Willy Tarreaueee5b512015-04-03 23:46:31 +02003205 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003206}
3207
3208__LJMP static int hlua_http_res_add_hdr(lua_State *L)
3209{
3210 struct hlua_txn *htxn;
3211
3212 MAY_LJMP(check_args(L, 3, "res_add_hdr"));
3213 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3214
Willy Tarreaueee5b512015-04-03 23:46:31 +02003215 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003216}
3217
3218static int hlua_http_req_set_hdr(lua_State *L)
3219{
3220 struct hlua_txn *htxn;
3221
3222 MAY_LJMP(check_args(L, 3, "req_set_hdr"));
3223 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3224
Willy Tarreaueee5b512015-04-03 23:46:31 +02003225 hlua_http_del_hdr(L, htxn, &htxn->s->txn->req);
3226 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->req);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003227}
3228
3229static int hlua_http_res_set_hdr(lua_State *L)
3230{
3231 struct hlua_txn *htxn;
3232
3233 MAY_LJMP(check_args(L, 3, "res_set_hdr"));
3234 htxn = MAY_LJMP(hlua_checkhttp(L, 1));
3235
Willy Tarreaueee5b512015-04-03 23:46:31 +02003236 hlua_http_del_hdr(L, htxn, &htxn->s->txn->rsp);
3237 return hlua_http_add_hdr(L, htxn, &htxn->s->txn->rsp);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003238}
3239
3240/* This function set the method. */
3241static int hlua_http_req_set_meth(lua_State *L)
3242{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003243 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003244 size_t name_len;
3245 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003246
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003247 lua_pushboolean(L, http_replace_req_line(0, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003248 return 1;
3249}
3250
3251/* This function set the method. */
3252static int hlua_http_req_set_path(lua_State *L)
3253{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003254 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003255 size_t name_len;
3256 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003257 lua_pushboolean(L, http_replace_req_line(1, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003258 return 1;
3259}
3260
3261/* This function set the query-string. */
3262static int hlua_http_req_set_query(lua_State *L)
3263{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003264 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003265 size_t name_len;
3266 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003267
3268 /* Check length. */
3269 if (name_len > trash.size - 1) {
3270 lua_pushboolean(L, 0);
3271 return 1;
3272 }
3273
3274 /* Add the mark question as prefix. */
3275 chunk_reset(&trash);
3276 trash.str[trash.len++] = '?';
3277 memcpy(trash.str + trash.len, name, name_len);
3278 trash.len += name_len;
3279
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003280 lua_pushboolean(L, http_replace_req_line(2, trash.str, trash.len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003281 return 1;
3282}
3283
3284/* This function set the uri. */
3285static int hlua_http_req_set_uri(lua_State *L)
3286{
Willy Tarreaubcb39cc2015-04-06 11:21:44 +02003287 struct hlua_txn *htxn = MAY_LJMP(hlua_checkhttp(L, 1));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003288 size_t name_len;
3289 const char *name = MAY_LJMP(luaL_checklstring(L, 2, &name_len));
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003290
Willy Tarreau987e3fb2015-04-04 01:09:08 +02003291 lua_pushboolean(L, http_replace_req_line(3, name, name_len, htxn->p, htxn->s) != -1);
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003292 return 1;
3293}
3294
3295/*
3296 *
3297 *
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003298 * Class TXN
3299 *
3300 *
3301 */
3302
3303/* Returns a struct hlua_session if the stack entry "ud" is
Willy Tarreau87b09662015-04-03 00:22:06 +02003304 * a class stream, otherwise it throws an error.
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003305 */
3306__LJMP static struct hlua_txn *hlua_checktxn(lua_State *L, int ud)
3307{
3308 return (struct hlua_txn *)MAY_LJMP(hlua_checkudata(L, ud, class_txn_ref));
3309}
3310
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02003311__LJMP static int hlua_set_var(lua_State *L)
3312{
3313 struct hlua_txn *htxn;
3314 const char *name;
3315 size_t len;
3316 struct sample smp;
3317
3318 MAY_LJMP(check_args(L, 3, "set_var"));
3319
3320 /* It is useles to retrieve the stream, but this function
3321 * runs only in a stream context.
3322 */
3323 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3324 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3325
3326 /* Converts the third argument in a sample. */
3327 hlua_lua2smp(L, 3, &smp);
3328
3329 /* Store the sample in a variable. */
3330 vars_set_by_name(name, len, htxn->s, &smp);
3331 return 0;
3332}
3333
3334__LJMP static int hlua_get_var(lua_State *L)
3335{
3336 struct hlua_txn *htxn;
3337 const char *name;
3338 size_t len;
3339 struct sample smp;
3340
3341 MAY_LJMP(check_args(L, 2, "get_var"));
3342
3343 /* It is useles to retrieve the stream, but this function
3344 * runs only in a stream context.
3345 */
3346 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3347 name = MAY_LJMP(luaL_checklstring(L, 2, &len));
3348
3349 if (!vars_get_by_name(name, len, htxn->s, &smp)) {
3350 lua_pushnil(L);
3351 return 1;
3352 }
3353
3354 return hlua_smp2lua(L, &smp);
3355}
3356
Willy Tarreau59551662015-03-10 14:23:13 +01003357__LJMP static int hlua_set_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003358{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003359 struct hlua *hlua;
3360
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003361 MAY_LJMP(check_args(L, 2, "set_priv"));
3362
Willy Tarreau87b09662015-04-03 00:22:06 +02003363 /* It is useles to retrieve the stream, but this function
3364 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003365 */
3366 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003367 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003368
3369 /* Remove previous value. */
3370 if (hlua->Mref != -1)
3371 luaL_unref(L, hlua->Mref, LUA_REGISTRYINDEX);
3372
3373 /* Get and store new value. */
3374 lua_pushvalue(L, 2); /* Copy the element 2 at the top of the stack. */
3375 hlua->Mref = luaL_ref(L, LUA_REGISTRYINDEX); /* pop the previously pushed value. */
3376
3377 return 0;
3378}
3379
Willy Tarreau59551662015-03-10 14:23:13 +01003380__LJMP static int hlua_get_priv(lua_State *L)
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003381{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003382 struct hlua *hlua;
3383
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003384 MAY_LJMP(check_args(L, 1, "get_priv"));
3385
Willy Tarreau87b09662015-04-03 00:22:06 +02003386 /* It is useles to retrieve the stream, but this function
3387 * runs only in a stream context.
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003388 */
3389 MAY_LJMP(hlua_checktxn(L, 1));
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003390 hlua = hlua_gethlua(L);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01003391
3392 /* Push configuration index in the stack. */
3393 lua_rawgeti(L, LUA_REGISTRYINDEX, hlua->Mref);
3394
3395 return 1;
3396}
3397
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003398/* Create stack entry containing a class TXN. This function
3399 * return 0 if the stack does not contains free slots,
3400 * otherwise it returns 1.
3401 */
Willy Tarreau15e91e12015-04-04 00:52:09 +02003402static int hlua_txn_new(lua_State *L, struct stream *s, struct proxy *p)
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003403{
Willy Tarreaude491382015-04-06 11:04:28 +02003404 struct hlua_txn *htxn;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003405
3406 /* Check stack size. */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003407 if (!lua_checkstack(L, 3))
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003408 return 0;
3409
3410 /* NOTE: The allocation never fails. The failure
3411 * throw an error, and the function never returns.
3412 * if the throw is not avalaible, the process is aborted.
3413 */
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003414 /* Create the object: obj[0] = userdata. */
3415 lua_newtable(L);
Willy Tarreaude491382015-04-06 11:04:28 +02003416 htxn = lua_newuserdata(L, sizeof(*htxn));
Thierry FOURNIER2297bc22015-03-11 17:43:33 +01003417 lua_rawseti(L, -2, 0);
3418
Willy Tarreaude491382015-04-06 11:04:28 +02003419 htxn->s = s;
3420 htxn->p = p;
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003421
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003422 /* Create the "f" field that contains a list of fetches. */
3423 lua_pushstring(L, "f");
Willy Tarreaude491382015-04-06 11:04:28 +02003424 if (!hlua_fetches_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003425 return 0;
3426 lua_settable(L, -3);
3427
3428 /* Create the "sf" field that contains a list of stringsafe fetches. */
3429 lua_pushstring(L, "sf");
Willy Tarreaude491382015-04-06 11:04:28 +02003430 if (!hlua_fetches_new(L, htxn, 1))
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01003431 return 0;
3432 lua_settable(L, -3);
3433
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003434 /* Create the "c" field that contains a list of converters. */
3435 lua_pushstring(L, "c");
Willy Tarreaude491382015-04-06 11:04:28 +02003436 if (!hlua_converters_new(L, htxn, 0))
Thierry FOURNIER2694a1a2015-03-11 20:13:36 +01003437 return 0;
3438 lua_settable(L, -3);
3439
3440 /* Create the "sc" field that contains a list of stringsafe converters. */
3441 lua_pushstring(L, "sc");
Willy Tarreaude491382015-04-06 11:04:28 +02003442 if (!hlua_converters_new(L, htxn, 1))
Thierry FOURNIER594afe72015-03-10 23:58:30 +01003443 return 0;
3444 lua_settable(L, -3);
3445
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003446 /* Create the "req" field that contains the request channel object. */
3447 lua_pushstring(L, "req");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003448 if (!hlua_channel_new(L, &s->req))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003449 return 0;
3450 lua_settable(L, -3);
3451
3452 /* Create the "res" field that contains the response channel object. */
3453 lua_pushstring(L, "res");
Willy Tarreau2a71af42015-03-10 13:51:50 +01003454 if (!hlua_channel_new(L, &s->res))
Thierry FOURNIER397826a2015-03-11 19:39:09 +01003455 return 0;
3456 lua_settable(L, -3);
3457
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003458 /* Creates the HTTP object is the current proxy allows http. */
3459 lua_pushstring(L, "http");
3460 if (p->mode == PR_MODE_HTTP) {
Willy Tarreaude491382015-04-06 11:04:28 +02003461 if (!hlua_http_new(L, htxn))
Thierry FOURNIER08504f42015-03-16 14:17:08 +01003462 return 0;
3463 }
3464 else
3465 lua_pushnil(L);
3466 lua_settable(L, -3);
3467
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01003468 /* Pop a class sesison metatable and affect it to the userdata. */
3469 lua_rawgeti(L, LUA_REGISTRYINDEX, class_txn_ref);
3470 lua_setmetatable(L, -2);
3471
3472 return 1;
3473}
3474
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003475__LJMP static int hlua_txn_deflog(lua_State *L)
3476{
3477 const char *msg;
3478 struct hlua_txn *htxn;
3479
3480 MAY_LJMP(check_args(L, 2, "deflog"));
3481 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3482 msg = MAY_LJMP(luaL_checkstring(L, 2));
3483
3484 hlua_sendlog(htxn->s->be, htxn->s->logs.level, msg);
3485 return 0;
3486}
3487
3488__LJMP static int hlua_txn_log(lua_State *L)
3489{
3490 int level;
3491 const char *msg;
3492 struct hlua_txn *htxn;
3493
3494 MAY_LJMP(check_args(L, 3, "log"));
3495 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3496 level = MAY_LJMP(luaL_checkinteger(L, 2));
3497 msg = MAY_LJMP(luaL_checkstring(L, 3));
3498
3499 if (level < 0 || level >= NB_LOG_LEVELS)
3500 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3501
3502 hlua_sendlog(htxn->s->be, level, msg);
3503 return 0;
3504}
3505
3506__LJMP static int hlua_txn_log_debug(lua_State *L)
3507{
3508 const char *msg;
3509 struct hlua_txn *htxn;
3510
3511 MAY_LJMP(check_args(L, 2, "Debug"));
3512 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3513 msg = MAY_LJMP(luaL_checkstring(L, 2));
3514 hlua_sendlog(htxn->s->be, LOG_DEBUG, msg);
3515 return 0;
3516}
3517
3518__LJMP static int hlua_txn_log_info(lua_State *L)
3519{
3520 const char *msg;
3521 struct hlua_txn *htxn;
3522
3523 MAY_LJMP(check_args(L, 2, "Info"));
3524 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3525 msg = MAY_LJMP(luaL_checkstring(L, 2));
3526 hlua_sendlog(htxn->s->be, LOG_INFO, msg);
3527 return 0;
3528}
3529
3530__LJMP static int hlua_txn_log_warning(lua_State *L)
3531{
3532 const char *msg;
3533 struct hlua_txn *htxn;
3534
3535 MAY_LJMP(check_args(L, 2, "Warning"));
3536 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3537 msg = MAY_LJMP(luaL_checkstring(L, 2));
3538 hlua_sendlog(htxn->s->be, LOG_WARNING, msg);
3539 return 0;
3540}
3541
3542__LJMP static int hlua_txn_log_alert(lua_State *L)
3543{
3544 const char *msg;
3545 struct hlua_txn *htxn;
3546
3547 MAY_LJMP(check_args(L, 2, "Alert"));
3548 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3549 msg = MAY_LJMP(luaL_checkstring(L, 2));
3550 hlua_sendlog(htxn->s->be, LOG_ALERT, msg);
3551 return 0;
3552}
3553
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003554__LJMP static int hlua_txn_set_loglevel(lua_State *L)
3555{
3556 struct hlua_txn *htxn;
3557 int ll;
3558
3559 MAY_LJMP(check_args(L, 2, "set_loglevel"));
3560 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3561 ll = MAY_LJMP(luaL_checkinteger(L, 2));
3562
3563 if (ll < 0 || ll > 7)
3564 WILL_LJMP(luaL_argerror(L, 2, "Bad log level. It must be between 0 and 7"));
3565
3566 htxn->s->logs.level = ll;
3567 return 0;
3568}
3569
3570__LJMP static int hlua_txn_set_tos(lua_State *L)
3571{
3572 struct hlua_txn *htxn;
3573 struct connection *cli_conn;
3574 int tos;
3575
3576 MAY_LJMP(check_args(L, 2, "set_tos"));
3577 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3578 tos = MAY_LJMP(luaL_checkinteger(L, 2));
3579
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003580 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003581 inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, tos);
3582
3583 return 0;
3584}
3585
3586__LJMP static int hlua_txn_set_mark(lua_State *L)
3587{
3588#ifdef SO_MARK
3589 struct hlua_txn *htxn;
3590 struct connection *cli_conn;
3591 int mark;
3592
3593 MAY_LJMP(check_args(L, 2, "set_mark"));
3594 htxn = MAY_LJMP(hlua_checktxn(L, 1));
3595 mark = MAY_LJMP(luaL_checkinteger(L, 2));
3596
Willy Tarreau9ad7bd42015-04-03 19:19:59 +02003597 if ((cli_conn = objt_conn(htxn->s->sess->origin)) && conn_ctrl_ready(cli_conn))
Willy Tarreau07081fe2015-04-06 10:59:20 +02003598 setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &mark, sizeof(mark));
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01003599#endif
3600 return 0;
3601}
3602
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003603/* This function is an Lua binding that send pending data
3604 * to the client, and close the stream interface.
3605 */
3606__LJMP static int hlua_txn_close(lua_State *L)
3607{
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003608 struct hlua_txn *htxn;
Willy Tarreau81389672015-03-10 12:03:52 +01003609 struct channel *ic, *oc;
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003610
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003611 MAY_LJMP(check_args(L, 1, "close"));
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003612 htxn = MAY_LJMP(hlua_checktxn(L, 1));
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003613
Willy Tarreaub2ccb562015-04-06 11:11:15 +02003614 ic = &htxn->s->req;
3615 oc = &htxn->s->res;
Willy Tarreau81389672015-03-10 12:03:52 +01003616
3617 channel_abort(ic);
3618 channel_auto_close(ic);
3619 channel_erase(ic);
3620 channel_auto_read(oc);
3621 channel_auto_close(oc);
3622 channel_shutr_now(oc);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003623
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01003624 return 0;
3625}
3626
3627__LJMP static int hlua_log(lua_State *L)
3628{
3629 int level;
3630 const char *msg;
3631
3632 MAY_LJMP(check_args(L, 2, "log"));
3633 level = MAY_LJMP(luaL_checkinteger(L, 1));
3634 msg = MAY_LJMP(luaL_checkstring(L, 2));
3635
3636 if (level < 0 || level >= NB_LOG_LEVELS)
3637 WILL_LJMP(luaL_argerror(L, 1, "Invalid loglevel."));
3638
3639 hlua_sendlog(NULL, level, msg);
3640 return 0;
3641}
3642
3643__LJMP static int hlua_log_debug(lua_State *L)
3644{
3645 const char *msg;
3646
3647 MAY_LJMP(check_args(L, 1, "debug"));
3648 msg = MAY_LJMP(luaL_checkstring(L, 1));
3649 hlua_sendlog(NULL, LOG_DEBUG, msg);
3650 return 0;
3651}
3652
3653__LJMP static int hlua_log_info(lua_State *L)
3654{
3655 const char *msg;
3656
3657 MAY_LJMP(check_args(L, 1, "info"));
3658 msg = MAY_LJMP(luaL_checkstring(L, 1));
3659 hlua_sendlog(NULL, LOG_INFO, msg);
3660 return 0;
3661}
3662
3663__LJMP static int hlua_log_warning(lua_State *L)
3664{
3665 const char *msg;
3666
3667 MAY_LJMP(check_args(L, 1, "warning"));
3668 msg = MAY_LJMP(luaL_checkstring(L, 1));
3669 hlua_sendlog(NULL, LOG_WARNING, msg);
3670 return 0;
3671}
3672
3673__LJMP static int hlua_log_alert(lua_State *L)
3674{
3675 const char *msg;
3676
3677 MAY_LJMP(check_args(L, 1, "alert"));
3678 msg = MAY_LJMP(luaL_checkstring(L, 1));
3679 hlua_sendlog(NULL, LOG_ALERT, msg);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01003680 return 0;
3681}
3682
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003683__LJMP static int hlua_sleep_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003684{
3685 int wakeup_ms = lua_tointeger(L, -1);
3686 if (now_ms < wakeup_ms)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003687 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003688 return 0;
3689}
3690
3691__LJMP static int hlua_sleep(lua_State *L)
3692{
3693 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003694 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003695
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003696 MAY_LJMP(check_args(L, 1, "sleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003697
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003698 delay = MAY_LJMP(luaL_checkinteger(L, 1)) * 1000;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003699 wakeup_ms = tick_add(now_ms, delay);
3700 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003701
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003702 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3703 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003704}
3705
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003706__LJMP static int hlua_msleep(lua_State *L)
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003707{
3708 unsigned int delay;
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003709 unsigned int wakeup_ms;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003710
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003711 MAY_LJMP(check_args(L, 1, "msleep"));
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003712
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003713 delay = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003714 wakeup_ms = tick_add(now_ms, delay);
3715 lua_pushinteger(L, wakeup_ms);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003716
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003717 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_sleep_yield, wakeup_ms, 0));
3718 return 0;
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01003719}
3720
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003721/* This functionis an LUA binding. it permits to give back
3722 * the hand at the HAProxy scheduler. It is used when the
3723 * LUA processing consumes a lot of time.
3724 */
Thierry FOURNIERf90838b2015-03-06 13:48:32 +01003725__LJMP static int hlua_yield_yield(lua_State *L, int status, lua_KContext ctx)
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003726{
3727 return 0;
3728}
3729
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003730__LJMP static int hlua_yield(lua_State *L)
3731{
Thierry FOURNIERd44731f2015-03-04 15:51:09 +01003732 WILL_LJMP(hlua_yieldk(L, 0, 0, hlua_yield_yield, TICK_ETERNITY, HLUA_CTRLYIELD));
3733 return 0;
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01003734}
3735
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003736/* This function change the nice of the currently executed
3737 * task. It is used set low or high priority at the current
3738 * task.
3739 */
Willy Tarreau59551662015-03-10 14:23:13 +01003740__LJMP static int hlua_set_nice(lua_State *L)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003741{
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003742 struct hlua *hlua;
3743 int nice;
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003744
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003745 MAY_LJMP(check_args(L, 1, "set_nice"));
3746 hlua = hlua_gethlua(L);
3747 nice = MAY_LJMP(luaL_checkinteger(L, 1));
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003748
3749 /* If he task is not set, I'm in a start mode. */
3750 if (!hlua || !hlua->task)
3751 return 0;
3752
3753 if (nice < -1024)
3754 nice = -1024;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01003755 else if (nice > 1024)
Thierry FOURNIER37196f42015-02-16 19:34:56 +01003756 nice = 1024;
3757
3758 hlua->task->nice = nice;
3759 return 0;
3760}
3761
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003762/* This function is used as a calback of a task. It is called by the
3763 * HAProxy task subsystem when the task is awaked. The LUA runtime can
3764 * return an E_AGAIN signal, the emmiter of this signal must set a
3765 * signal to wake the task.
3766 */
3767static struct task *hlua_process_task(struct task *task)
3768{
3769 struct hlua *hlua = task->context;
3770 enum hlua_exec status;
3771
3772 /* We need to remove the task from the wait queue before executing
3773 * the Lua code because we don't know if it needs to wait for
3774 * another timer or not in the case of E_AGAIN.
3775 */
3776 task_delete(task);
3777
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003778 /* If it is the first call to the task, we must initialize the
3779 * execution timeouts.
3780 */
3781 if (!HLUA_IS_RUNNING(hlua))
Camilo Lopez685c0142015-08-02 19:07:28 -04003782 hlua->expire = tick_add_ifset(now_ms, hlua_timeout_task);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003783
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003784 /* Execute the Lua code. */
3785 status = hlua_ctx_resume(hlua, 1);
3786
3787 switch (status) {
3788 /* finished or yield */
3789 case HLUA_E_OK:
3790 hlua_ctx_destroy(hlua);
3791 task_delete(task);
3792 task_free(task);
3793 break;
3794
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01003795 case HLUA_E_AGAIN: /* co process or timeout wake me later. */
3796 if (hlua->wake_time != TICK_ETERNITY)
3797 task_schedule(task, hlua->wake_time);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003798 break;
3799
3800 /* finished with error. */
3801 case HLUA_E_ERRMSG:
3802 send_log(NULL, LOG_ERR, "Lua task: %s.", lua_tostring(hlua->T, -1));
3803 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3804 Alert("Lua task: %s.\n", lua_tostring(hlua->T, -1));
3805 hlua_ctx_destroy(hlua);
3806 task_delete(task);
3807 task_free(task);
3808 break;
3809
3810 case HLUA_E_ERR:
3811 default:
3812 send_log(NULL, LOG_ERR, "Lua task: unknown error.");
3813 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3814 Alert("Lua task: unknown error.\n");
3815 hlua_ctx_destroy(hlua);
3816 task_delete(task);
3817 task_free(task);
3818 break;
3819 }
3820 return NULL;
3821}
3822
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01003823/* This function is an LUA binding that register LUA function to be
3824 * executed after the HAProxy configuration parsing and before the
3825 * HAProxy scheduler starts. This function expect only one LUA
3826 * argument that is a function. This function returns nothing, but
3827 * throws if an error is encountered.
3828 */
3829__LJMP static int hlua_register_init(lua_State *L)
3830{
3831 struct hlua_init_function *init;
3832 int ref;
3833
3834 MAY_LJMP(check_args(L, 1, "register_init"));
3835
3836 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3837
3838 init = malloc(sizeof(*init));
3839 if (!init)
3840 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3841
3842 init->function_ref = ref;
3843 LIST_ADDQ(&hlua_init_functions, &init->l);
3844 return 0;
3845}
3846
Thierry FOURNIER24f33532015-01-23 12:13:00 +01003847/* This functio is an LUA binding. It permits to register a task
3848 * executed in parallel of the main HAroxy activity. The task is
3849 * created and it is set in the HAProxy scheduler. It can be called
3850 * from the "init" section, "post init" or during the runtime.
3851 *
3852 * Lua prototype:
3853 *
3854 * <none> core.register_task(<function>)
3855 */
3856static int hlua_register_task(lua_State *L)
3857{
3858 struct hlua *hlua;
3859 struct task *task;
3860 int ref;
3861
3862 MAY_LJMP(check_args(L, 1, "register_task"));
3863
3864 ref = MAY_LJMP(hlua_checkfunction(L, 1));
3865
3866 hlua = malloc(sizeof(*hlua));
3867 if (!hlua)
3868 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3869
3870 task = task_new();
3871 task->context = hlua;
3872 task->process = hlua_process_task;
3873
3874 if (!hlua_ctx_init(hlua, task))
3875 WILL_LJMP(luaL_error(L, "lua out of memory error."));
3876
3877 /* Restore the function in the stack. */
3878 lua_rawgeti(hlua->T, LUA_REGISTRYINDEX, ref);
3879 hlua->nargs = 0;
3880
3881 /* Schedule task. */
3882 task_schedule(task, now_ms);
3883
3884 return 0;
3885}
3886
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003887/* Wrapper called by HAProxy to execute an LUA converter. This wrapper
3888 * doesn't allow "yield" functions because the HAProxy engine cannot
3889 * resume converters.
3890 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003891static int hlua_sample_conv_wrapper(const struct arg *arg_p, struct sample *smp, void *private)
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003892{
3893 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003894 struct stream *stream = smp->strm;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003895
Willy Tarreau87b09662015-04-03 00:22:06 +02003896 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003897 * Lua context can be not initialized. This behavior
3898 * permits to save performances because a systematic
3899 * Lua initialization cause 5% performances loss.
3900 */
Willy Tarreau87b09662015-04-03 00:22:06 +02003901 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
3902 send_log(stream->be, LOG_ERR, "Lua converter '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003903 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3904 Alert("Lua converter '%s': can't initialize Lua context.\n", fcn->name);
3905 return 0;
3906 }
3907
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003908 /* If it is the first run, initialize the data for the call. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003909 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003910 /* Check stack available size. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003911 if (!lua_checkstack(stream->hlua.T, 1)) {
3912 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003913 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3914 Alert("Lua converter '%s': full stack.\n", fcn->name);
3915 return 0;
3916 }
3917
3918 /* Restore the function in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003919 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003920
3921 /* convert input sample and pust-it in the stack. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003922 if (!lua_checkstack(stream->hlua.T, 1)) {
3923 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003924 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3925 Alert("Lua converter '%s': full stack.\n", fcn->name);
3926 return 0;
3927 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003928 hlua_smp2lua(stream->hlua.T, smp);
3929 stream->hlua.nargs = 2;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003930
3931 /* push keywords in the stack. */
3932 if (arg_p) {
3933 for (; arg_p->type != ARGT_STOP; arg_p++) {
Willy Tarreau87b09662015-04-03 00:22:06 +02003934 if (!lua_checkstack(stream->hlua.T, 1)) {
3935 send_log(stream->be, LOG_ERR, "Lua converter '%s': full stack.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003936 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3937 Alert("Lua converter '%s': full stack.\n", fcn->name);
3938 return 0;
3939 }
Willy Tarreau87b09662015-04-03 00:22:06 +02003940 hlua_arg2lua(stream->hlua.T, arg_p);
3941 stream->hlua.nargs++;
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003942 }
3943 }
3944
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003945 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02003946 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01003947
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003948 /* Set the currently running flag. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003949 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003950 }
3951
3952 /* Execute the function. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003953 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003954 /* finished. */
3955 case HLUA_E_OK:
3956 /* Convert the returned value in sample. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003957 hlua_lua2smp(stream->hlua.T, -1, smp);
3958 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003959 return 1;
3960
3961 /* yield. */
3962 case HLUA_E_AGAIN:
Willy Tarreau87b09662015-04-03 00:22:06 +02003963 send_log(stream->be, LOG_ERR, "Lua converter '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003964 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3965 Alert("Lua converter '%s': cannot use yielded functions.\n", fcn->name);
3966 return 0;
3967
3968 /* finished with error. */
3969 case HLUA_E_ERRMSG:
3970 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003971 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 +01003972 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Willy Tarreau87b09662015-04-03 00:22:06 +02003973 Alert("Lua converter '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
3974 lua_pop(stream->hlua.T, 1);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003975 return 0;
3976
3977 case HLUA_E_ERR:
3978 /* Display log. */
Willy Tarreau87b09662015-04-03 00:22:06 +02003979 send_log(stream->be, LOG_ERR, "Lua converter '%s' returns an unknown error.", fcn->name);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01003980 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
3981 Alert("Lua converter '%s' returns an unknown error.\n", fcn->name);
3982
3983 default:
3984 return 0;
3985 }
3986}
3987
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003988/* Wrapper called by HAProxy to execute a sample-fetch. this wrapper
3989 * doesn't allow "yield" functions because the HAProxy engine cannot
3990 * resume sample-fetches.
3991 */
Thierry FOURNIER0786d052015-05-11 15:42:45 +02003992static int hlua_sample_fetch_wrapper(const struct arg *arg_p, struct sample *smp,
3993 const char *kw, void *private)
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003994{
3995 struct hlua_function *fcn = (struct hlua_function *)private;
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02003996 struct stream *stream = smp->strm;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01003997
Willy Tarreau87b09662015-04-03 00:22:06 +02003998 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01003999 * Lua context can be not initialized. This behavior
4000 * permits to save performances because a systematic
4001 * Lua initialization cause 5% performances loss.
4002 */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004003 if (!stream->hlua.T && !hlua_ctx_init(&stream->hlua, stream->task)) {
4004 send_log(stream->be, LOG_ERR, "Lua sample-fetch '%s': can't initialize Lua context.", fcn->name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004005 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4006 Alert("Lua sample-fetch '%s': can't initialize Lua context.\n", fcn->name);
4007 return 0;
4008 }
4009
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004010 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004011 if (!HLUA_IS_RUNNING(&stream->hlua)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004012 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004013 if (!lua_checkstack(stream->hlua.T, 2)) {
4014 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004015 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4016 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4017 return 0;
4018 }
4019
4020 /* Restore the function in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004021 lua_rawgeti(stream->hlua.T, LUA_REGISTRYINDEX, fcn->function_ref);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004022
4023 /* push arguments in the stack. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004024 if (!hlua_txn_new(stream->hlua.T, stream, smp->px)) {
4025 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004026 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4027 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4028 return 0;
4029 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004030 stream->hlua.nargs = 1;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004031
4032 /* push keywords in the stack. */
4033 for (; arg_p && arg_p->type != ARGT_STOP; arg_p++) {
4034 /* Check stack available size. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004035 if (!lua_checkstack(stream->hlua.T, 1)) {
4036 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004037 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4038 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4039 return 0;
4040 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004041 if (!lua_checkstack(stream->hlua.T, 1)) {
4042 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': full stack.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004043 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4044 Alert("Lua sample-fetch '%s': full stack.\n", fcn->name);
4045 return 0;
4046 }
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004047 hlua_arg2lua(stream->hlua.T, arg_p);
4048 stream->hlua.nargs++;
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004049 }
4050
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004051 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004052 stream->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004053
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004054 /* Set the currently running flag. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004055 HLUA_SET_RUN(&stream->hlua);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004056 }
4057
4058 /* Execute the function. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004059 switch (hlua_ctx_resume(&stream->hlua, 0)) {
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004060 /* finished. */
4061 case HLUA_E_OK:
4062 /* Convert the returned value in sample. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004063 hlua_lua2smp(stream->hlua.T, -1, smp);
4064 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004065
4066 /* Set the end of execution flag. */
4067 smp->flags &= ~SMP_F_MAY_CHANGE;
4068 return 1;
4069
4070 /* yield. */
4071 case HLUA_E_AGAIN:
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004072 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s': cannot use yielded functions.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004073 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4074 Alert("Lua sample-fetch '%s': cannot use yielded functions.\n", fcn->name);
4075 return 0;
4076
4077 /* finished with error. */
4078 case HLUA_E_ERRMSG:
4079 /* Display log. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004080 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 +01004081 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004082 Alert("Lua sample-fetch '%s': %s.\n", fcn->name, lua_tostring(stream->hlua.T, -1));
4083 lua_pop(stream->hlua.T, 1);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004084 return 0;
4085
4086 case HLUA_E_ERR:
4087 /* Display log. */
Thierry FOURNIER0a9a2b82015-05-11 15:20:49 +02004088 send_log(smp->px, LOG_ERR, "Lua sample-fetch '%s' returns an unknown error.", fcn->name);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004089 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4090 Alert("Lua sample-fetch '%s': returns an unknown error.\n", fcn->name);
4091
4092 default:
4093 return 0;
4094 }
4095}
4096
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004097/* This function is an LUA binding used for registering
4098 * "sample-conv" functions. It expects a converter name used
4099 * in the haproxy configuration file, and an LUA function.
4100 */
4101__LJMP static int hlua_register_converters(lua_State *L)
4102{
4103 struct sample_conv_kw_list *sck;
4104 const char *name;
4105 int ref;
4106 int len;
4107 struct hlua_function *fcn;
4108
4109 MAY_LJMP(check_args(L, 2, "register_converters"));
4110
4111 /* First argument : converter name. */
4112 name = MAY_LJMP(luaL_checkstring(L, 1));
4113
4114 /* Second argument : lua function. */
4115 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4116
4117 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004118 sck = malloc(sizeof(*sck) + sizeof(struct sample_conv) * 2);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004119 if (!sck)
4120 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4121 fcn = malloc(sizeof(*fcn));
4122 if (!fcn)
4123 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4124
4125 /* Fill fcn. */
4126 fcn->name = strdup(name);
4127 if (!fcn->name)
4128 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4129 fcn->function_ref = ref;
4130
4131 /* List head */
4132 sck->list.n = sck->list.p = NULL;
4133
4134 /* converter keyword. */
4135 len = strlen("lua.") + strlen(name) + 1;
4136 sck->kw[0].kw = malloc(len);
4137 if (!sck->kw[0].kw)
4138 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4139
4140 snprintf((char *)sck->kw[0].kw, len, "lua.%s", name);
4141 sck->kw[0].process = hlua_sample_conv_wrapper;
4142 sck->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4143 sck->kw[0].val_args = NULL;
4144 sck->kw[0].in_type = SMP_T_STR;
4145 sck->kw[0].out_type = SMP_T_STR;
4146 sck->kw[0].private = fcn;
4147
4148 /* End of array. */
4149 memset(&sck->kw[1], 0, sizeof(struct sample_conv));
4150
4151 /* Register this new converter */
4152 sample_register_convs(sck);
4153
4154 return 0;
4155}
4156
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004157/* This fucntion is an LUA binding used for registering
4158 * "sample-fetch" functions. It expects a converter name used
4159 * in the haproxy configuration file, and an LUA function.
4160 */
4161__LJMP static int hlua_register_fetches(lua_State *L)
4162{
4163 const char *name;
4164 int ref;
4165 int len;
4166 struct sample_fetch_kw_list *sfk;
4167 struct hlua_function *fcn;
4168
4169 MAY_LJMP(check_args(L, 2, "register_fetches"));
4170
4171 /* First argument : sample-fetch name. */
4172 name = MAY_LJMP(luaL_checkstring(L, 1));
4173
4174 /* Second argument : lua function. */
4175 ref = MAY_LJMP(hlua_checkfunction(L, 2));
4176
4177 /* Allocate and fill the sample fetch keyword struct. */
Willy Tarreau07081fe2015-04-06 10:59:20 +02004178 sfk = malloc(sizeof(*sfk) + sizeof(struct sample_fetch) * 2);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004179 if (!sfk)
4180 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4181 fcn = malloc(sizeof(*fcn));
4182 if (!fcn)
4183 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4184
4185 /* Fill fcn. */
4186 fcn->name = strdup(name);
4187 if (!fcn->name)
4188 WILL_LJMP(luaL_error(L, "lua out of memory error."));
4189 fcn->function_ref = ref;
4190
4191 /* List head */
4192 sfk->list.n = sfk->list.p = NULL;
4193
4194 /* sample-fetch keyword. */
4195 len = strlen("lua.") + strlen(name) + 1;
4196 sfk->kw[0].kw = malloc(len);
4197 if (!sfk->kw[0].kw)
4198 return luaL_error(L, "lua out of memory error.");
4199
4200 snprintf((char *)sfk->kw[0].kw, len, "lua.%s", name);
4201 sfk->kw[0].process = hlua_sample_fetch_wrapper;
4202 sfk->kw[0].arg_mask = ARG5(0,STR,STR,STR,STR,STR);
4203 sfk->kw[0].val_args = NULL;
4204 sfk->kw[0].out_type = SMP_T_STR;
4205 sfk->kw[0].use = SMP_USE_HTTP_ANY;
4206 sfk->kw[0].val = 0;
4207 sfk->kw[0].private = fcn;
4208
4209 /* End of array. */
4210 memset(&sfk->kw[1], 0, sizeof(struct sample_fetch));
4211
4212 /* Register this new fetch. */
4213 sample_register_fetches(sfk);
4214
4215 return 0;
4216}
4217
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004218/* This function is a wrapper to execute each LUA function declared
4219 * as an action wrapper during the initialisation period. This function
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004220 * return ACT_RET_CONT if the processing is finished (with or without
4221 * error) and return ACT_RET_YIELD if the function must be called again
4222 * because the LUA returns a yield.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004223 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004224static enum act_return hlua_action(struct act_rule *rule, struct proxy *px,
4225 struct session *sess, struct stream *s)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004226{
4227 char **arg;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004228 unsigned int analyzer;
4229
4230 switch (rule->from) {
4231 case ACT_F_TCP_REQ_CNT: analyzer = AN_REQ_INSPECT_FE ; break;
4232 case ACT_F_TCP_RES_CNT: analyzer = AN_RES_INSPECT ; break;
4233 case ACT_F_HTTP_REQ: analyzer = AN_REQ_HTTP_PROCESS_FE; break;
4234 case ACT_F_HTTP_RES: analyzer = AN_RES_HTTP_PROCESS_BE; break;
4235 default:
4236 send_log(px, LOG_ERR, "Lua: internal error while execute action.");
4237 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
4238 Alert("Lua: internal error while execute action.\n");
4239 return ACT_RET_CONT;
4240 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004241
Willy Tarreau87b09662015-04-03 00:22:06 +02004242 /* In the execution wrappers linked with a stream, the
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004243 * Lua context can be not initialized. This behavior
4244 * permits to save performances because a systematic
4245 * Lua initialization cause 5% performances loss.
4246 */
4247 if (!s->hlua.T && !hlua_ctx_init(&s->hlua, s->task)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004248 send_log(px, LOG_ERR, "Lua action '%s': can't initialize Lua context.",
4249 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004250 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004251 Alert("Lua action '%s': can't initialize Lua context.\n",
4252 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004253 return ACT_RET_CONT;
Thierry FOURNIER05ac4242015-02-27 18:37:27 +01004254 }
4255
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004256 /* If it is the first run, initialize the data for the call. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004257 if (!HLUA_IS_RUNNING(&s->hlua)) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004258 /* Check stack available size. */
4259 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004260 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4261 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004262 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004263 Alert("Lua function '%s': full stack.\n",
4264 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004265 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004266 }
4267
4268 /* Restore the function in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004269 lua_rawgeti(s->hlua.T, LUA_REGISTRYINDEX, rule->arg.hlua_rule->fcn.function_ref);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004270
Willy Tarreau87b09662015-04-03 00:22:06 +02004271 /* Create and and push object stream in the stack. */
Willy Tarreau15e91e12015-04-04 00:52:09 +02004272 if (!hlua_txn_new(s->hlua.T, s, px)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004273 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4274 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004275 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004276 Alert("Lua function '%s': full stack.\n",
4277 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004278 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004279 }
4280 s->hlua.nargs = 1;
4281
4282 /* push keywords in the stack. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004283 for (arg = rule->arg.hlua_rule->args; arg && *arg; arg++) {
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004284 if (!lua_checkstack(s->hlua.T, 1)) {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004285 send_log(px, LOG_ERR, "Lua function '%s': full stack.",
4286 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004287 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004288 Alert("Lua function '%s': full stack.\n",
4289 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004290 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004291 }
4292 lua_pushstring(s->hlua.T, *arg);
4293 s->hlua.nargs++;
4294 }
4295
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004296 /* We must initialize the execution timeouts. */
Thierry FOURNIER61e96c62015-08-09 13:10:24 +02004297 s->hlua.expire = tick_add_ifset(now_ms, hlua_timeout_session);
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004298
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004299 /* Set the currently running flag. */
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004300 HLUA_SET_RUN(&s->hlua);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004301 }
4302
4303 /* Execute the function. */
4304 switch (hlua_ctx_resume(&s->hlua, 1)) {
4305 /* finished. */
4306 case HLUA_E_OK:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004307 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004308
4309 /* yield. */
4310 case HLUA_E_AGAIN:
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004311 /* Set timeout in the required channel. */
4312 if (s->hlua.wake_time != TICK_ETERNITY) {
4313 if (analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004314 s->req.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004315 else if (analyzer & (AN_RES_INSPECT|AN_RES_HTTP_PROCESS_BE))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004316 s->res.analyse_exp = s->hlua.wake_time;
Thierry FOURNIERc42c1ae2015-03-03 17:17:55 +01004317 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004318 /* Some actions can be wake up when a "write" event
4319 * is detected on a response channel. This is useful
4320 * only for actions targetted on the requests.
4321 */
Thierry FOURNIERef6a2112015-03-05 17:45:34 +01004322 if (HLUA_IS_WAKERESWR(&s->hlua)) {
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004323 s->res.flags |= CF_WAKE_WRITE;
Willy Tarreau76bd97f2015-03-10 17:16:10 +01004324 if ((analyzer & (AN_REQ_INSPECT_FE|AN_REQ_HTTP_PROCESS_FE)))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004325 s->res.analysers |= analyzer;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004326 }
Thierry FOURNIER53e08ec2015-03-06 00:35:53 +01004327 if (HLUA_IS_WAKEREQWR(&s->hlua))
Willy Tarreau22ec1ea2014-11-27 20:45:39 +01004328 s->req.flags |= CF_WAKE_WRITE;
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004329 return ACT_RET_YIELD;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004330
4331 /* finished with error. */
4332 case HLUA_E_ERRMSG:
4333 /* Display log. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004334 send_log(px, LOG_ERR, "Lua function '%s': %s.",
4335 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004336 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004337 Alert("Lua function '%s': %s.\n",
4338 rule->arg.hlua_rule->fcn.name, lua_tostring(s->hlua.T, -1));
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004339 lua_pop(s->hlua.T, 1);
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004340 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004341
4342 case HLUA_E_ERR:
4343 /* Display log. */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004344 send_log(px, LOG_ERR, "Lua function '%s' return an unknown error.",
4345 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004346 if (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE))
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004347 Alert("Lua function '%s' return an unknown error.\n",
4348 rule->arg.hlua_rule->fcn.name);
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004349
4350 default:
Thierry FOURNIER24ff6c62015-08-06 08:52:53 +02004351 return ACT_RET_CONT;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004352 }
4353}
4354
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004355/* global {tcp|http}-request parser. Return ACT_RET_PRS_OK in
4356 * succes case, else return ACT_RET_PRS_ERR.
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004357 */
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004358static enum act_parse_ret action_register_lua(const char **args, int *cur_arg, struct proxy *px,
4359 struct act_rule *rule, char **err)
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004360{
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004361 /* Memory for the rule. */
4362 rule->arg.hlua_rule = malloc(sizeof(*rule->arg.hlua_rule));
4363 if (!rule->arg.hlua_rule) {
4364 memprintf(err, "out of memory error");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004365 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004366 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004367
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004368 /* The requiered arg is a function name. */
4369 if (!args[*cur_arg]) {
4370 memprintf(err, "expect Lua function name");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004371 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004372 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004373
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004374 /* Lookup for the symbol, and check if it is a function. */
4375 lua_getglobal(gL.T, args[*cur_arg]);
4376 if (lua_isnil(gL.T, -1)) {
4377 lua_pop(gL.T, 1);
4378 memprintf(err, "Lua function '%s' not found", args[*cur_arg]);
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004379 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004380 }
4381 if (!lua_isfunction(gL.T, -1)) {
4382 lua_pop(gL.T, 1);
4383 memprintf(err, "'%s' is not a function", args[*cur_arg]);
4384 return ACT_RET_PRS_ERR;
4385 }
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004386
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004387 /* Reference the Lua function and store the reference. */
4388 rule->arg.hlua_rule->fcn.function_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX);
4389 rule->arg.hlua_rule->fcn.name = strdup(args[*cur_arg]);
4390 if (!rule->arg.hlua_rule->fcn.name) {
4391 memprintf(err, "out of memory error.");
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004392 return ACT_RET_PRS_ERR;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004393 }
4394 (*cur_arg)++;
4395
4396 /* TODO: later accept arguments. */
4397 rule->arg.hlua_rule->args = NULL;
4398
Thierry FOURNIER91f6ba02015-08-06 08:30:11 +02004399 rule->action = ACT_ACTION_CONT;
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004400 rule->action_ptr = hlua_action;
Thierry FOURNIERafa80492015-08-19 09:04:15 +02004401 return ACT_RET_PRS_OK;
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004402}
4403
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004404static int hlua_read_timeout(char **args, int section_type, struct proxy *curpx,
4405 struct proxy *defpx, const char *file, int line,
4406 char **err, unsigned int *timeout)
4407{
4408 const char *error;
4409
4410 error = parse_time_err(args[1], timeout, TIME_UNIT_MS);
4411 if (error && *error != '\0') {
4412 memprintf(err, "%s: invalid timeout", args[0]);
4413 return -1;
4414 }
4415 return 0;
4416}
4417
4418static int hlua_session_timeout(char **args, int section_type, struct proxy *curpx,
4419 struct proxy *defpx, const char *file, int line,
4420 char **err)
4421{
4422 return hlua_read_timeout(args, section_type, curpx, defpx,
4423 file, line, err, &hlua_timeout_session);
4424}
4425
4426static int hlua_task_timeout(char **args, int section_type, struct proxy *curpx,
4427 struct proxy *defpx, const char *file, int line,
4428 char **err)
4429{
4430 return hlua_read_timeout(args, section_type, curpx, defpx,
4431 file, line, err, &hlua_timeout_task);
4432}
4433
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004434static int hlua_forced_yield(char **args, int section_type, struct proxy *curpx,
4435 struct proxy *defpx, const char *file, int line,
4436 char **err)
4437{
4438 char *error;
4439
4440 hlua_nb_instruction = strtoll(args[1], &error, 10);
4441 if (*error != '\0') {
4442 memprintf(err, "%s: invalid number", args[0]);
4443 return -1;
4444 }
4445 return 0;
4446}
4447
Willy Tarreau32f61e22015-03-18 17:54:59 +01004448static int hlua_parse_maxmem(char **args, int section_type, struct proxy *curpx,
4449 struct proxy *defpx, const char *file, int line,
4450 char **err)
4451{
4452 char *error;
4453
4454 if (*(args[1]) == 0) {
4455 memprintf(err, "'%s' expects an integer argument (Lua memory size in MB).\n", args[0]);
4456 return -1;
4457 }
4458 hlua_global_allocator.limit = strtoll(args[1], &error, 10) * 1024L * 1024L;
4459 if (*error != '\0') {
4460 memprintf(err, "%s: invalid number %s (error at '%c')", args[0], args[1], *error);
4461 return -1;
4462 }
4463 return 0;
4464}
4465
4466
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004467/* This function is called by the main configuration key "lua-load". It loads and
4468 * execute an lua file during the parsing of the HAProxy configuration file. It is
4469 * the main lua entry point.
4470 *
4471 * This funtion runs with the HAProxy keywords API. It returns -1 if an error is
4472 * occured, otherwise it returns 0.
4473 *
4474 * In some error case, LUA set an error message in top of the stack. This function
4475 * returns this error message in the HAProxy logs and pop it from the stack.
4476 */
4477static int hlua_load(char **args, int section_type, struct proxy *curpx,
4478 struct proxy *defpx, const char *file, int line,
4479 char **err)
4480{
4481 int error;
4482
4483 /* Just load and compile the file. */
4484 error = luaL_loadfile(gL.T, args[1]);
4485 if (error) {
4486 memprintf(err, "error in lua file '%s': %s", args[1], lua_tostring(gL.T, -1));
4487 lua_pop(gL.T, 1);
4488 return -1;
4489 }
4490
4491 /* If no syntax error where detected, execute the code. */
4492 error = lua_pcall(gL.T, 0, LUA_MULTRET, 0);
4493 switch (error) {
4494 case LUA_OK:
4495 break;
4496 case LUA_ERRRUN:
4497 memprintf(err, "lua runtime error: %s\n", lua_tostring(gL.T, -1));
4498 lua_pop(gL.T, 1);
4499 return -1;
4500 case LUA_ERRMEM:
4501 memprintf(err, "lua out of memory error\n");
4502 return -1;
4503 case LUA_ERRERR:
4504 memprintf(err, "lua message handler error: %s\n", lua_tostring(gL.T, -1));
4505 lua_pop(gL.T, 1);
4506 return -1;
4507 case LUA_ERRGCMM:
4508 memprintf(err, "lua garbage collector error: %s\n", lua_tostring(gL.T, -1));
4509 lua_pop(gL.T, 1);
4510 return -1;
4511 default:
4512 memprintf(err, "lua unknonwn error: %s\n", lua_tostring(gL.T, -1));
4513 lua_pop(gL.T, 1);
4514 return -1;
4515 }
4516
4517 return 0;
4518}
4519
4520/* configuration keywords declaration */
4521static struct cfg_kw_list cfg_kws = {{ },{
Thierry FOURNIERbd413492015-03-03 16:52:26 +01004522 { CFG_GLOBAL, "lua-load", hlua_load },
4523 { CFG_GLOBAL, "tune.lua.session-timeout", hlua_session_timeout },
4524 { CFG_GLOBAL, "tune.lua.task-timeout", hlua_task_timeout },
Thierry FOURNIERee9f8022015-03-03 17:37:37 +01004525 { CFG_GLOBAL, "tune.lua.forced-yield", hlua_forced_yield },
Willy Tarreau32f61e22015-03-18 17:54:59 +01004526 { CFG_GLOBAL, "tune.lua.maxmem", hlua_parse_maxmem },
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004527 { 0, NULL, NULL },
4528}};
4529
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004530static struct action_kw_list http_req_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004531 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004532 { NULL, NULL }
4533}};
4534
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004535static struct action_kw_list http_res_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004536 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004537 { NULL, NULL }
4538}};
4539
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004540static struct action_kw_list tcp_req_cont_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004541 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004542 { NULL, NULL }
4543}};
4544
Thierry FOURNIER36481b82015-08-19 09:01:53 +02004545static struct action_kw_list tcp_res_cont_kws = { { }, {
Thierry FOURNIER4dc15d12015-08-06 18:25:56 +02004546 { "lua", action_register_lua },
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004547 { NULL, NULL }
4548}};
4549
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004550int hlua_post_init()
4551{
4552 struct hlua_init_function *init;
4553 const char *msg;
4554 enum hlua_exec ret;
4555
4556 list_for_each_entry(init, &hlua_init_functions, l) {
4557 lua_rawgeti(gL.T, LUA_REGISTRYINDEX, init->function_ref);
4558 ret = hlua_ctx_resume(&gL, 0);
4559 switch (ret) {
4560 case HLUA_E_OK:
4561 lua_pop(gL.T, -1);
4562 return 1;
4563 case HLUA_E_AGAIN:
4564 Alert("lua init: yield not allowed.\n");
4565 return 0;
4566 case HLUA_E_ERRMSG:
4567 msg = lua_tostring(gL.T, -1);
4568 Alert("lua init: %s.\n", msg);
4569 return 0;
4570 case HLUA_E_ERR:
4571 default:
4572 Alert("lua init: unknown runtime error.\n");
4573 return 0;
4574 }
4575 }
4576 return 1;
4577}
4578
Willy Tarreau32f61e22015-03-18 17:54:59 +01004579/* The memory allocator used by the Lua stack. <ud> is a pointer to the
4580 * allocator's context. <ptr> is the pointer to alloc/free/realloc. <osize>
4581 * is the previously allocated size or the kind of object in case of a new
4582 * allocation. <nsize> is the requested new size.
4583 */
4584static void *hlua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
4585{
4586 struct hlua_mem_allocator *zone = ud;
4587
4588 if (nsize == 0) {
4589 /* it's a free */
4590 if (ptr)
4591 zone->allocated -= osize;
4592 free(ptr);
4593 return NULL;
4594 }
4595
4596 if (!ptr) {
4597 /* it's a new allocation */
4598 if (zone->limit && zone->allocated + nsize > zone->limit)
4599 return NULL;
4600
4601 ptr = malloc(nsize);
4602 if (ptr)
4603 zone->allocated += nsize;
4604 return ptr;
4605 }
4606
4607 /* it's a realloc */
4608 if (zone->limit && zone->allocated + nsize - osize > zone->limit)
4609 return NULL;
4610
4611 ptr = realloc(ptr, nsize);
4612 if (ptr)
4613 zone->allocated += nsize - osize;
4614 return ptr;
4615}
4616
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01004617void hlua_init(void)
4618{
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004619 int i;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004620 int idx;
4621 struct sample_fetch *sf;
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004622 struct sample_conv *sc;
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004623 char *p;
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004624#ifdef USE_OPENSSL
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004625 struct srv_kw *kw;
4626 int tmp_error;
4627 char *error;
Thierry FOURNIER36d13742015-03-17 16:48:53 +01004628 char *args[] = { /* SSL client configuration. */
4629 "ssl",
4630 "verify",
4631 "none",
4632 "force-sslv3",
4633 NULL
4634 };
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004635#endif
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004636
Willy Tarreau87b09662015-04-03 00:22:06 +02004637 /* Initialise com signals pool */
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004638 pool2_hlua_com = create_pool("hlua_com", sizeof(struct hlua_com), MEM_F_SHARED);
4639
Thierry FOURNIER6c9b52c2015-01-23 15:57:06 +01004640 /* Register configuration keywords. */
4641 cfg_register_keywords(&cfg_kws);
4642
Thierry FOURNIER258d8aa2015-02-16 20:23:40 +01004643 /* Register custom HTTP rules. */
4644 http_req_keywords_register(&http_req_kws);
4645 http_res_keywords_register(&http_res_kws);
4646 tcp_req_cont_keywords_register(&tcp_req_cont_kws);
4647 tcp_res_cont_keywords_register(&tcp_res_cont_kws);
4648
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004649 /* Init main lua stack. */
4650 gL.Mref = LUA_REFNIL;
Thierry FOURNIERa097fdf2015-03-03 15:17:35 +01004651 gL.flags = 0;
Thierry FOURNIER9ff7e6e2015-01-23 11:08:20 +01004652 LIST_INIT(&gL.com);
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004653 gL.T = luaL_newstate();
4654 hlua_sethlua(&gL);
4655 gL.Tref = LUA_REFNIL;
4656 gL.task = NULL;
4657
Willy Tarreau32f61e22015-03-18 17:54:59 +01004658 /* change the memory allocators to track memory usage */
4659 lua_setallocf(gL.T, hlua_alloc, &hlua_global_allocator);
4660
Thierry FOURNIER380d0932015-01-23 14:27:52 +01004661 /* Initialise lua. */
4662 luaL_openlibs(gL.T);
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004663
4664 /*
4665 *
4666 * Create "core" object.
4667 *
4668 */
4669
Thierry FOURNIERa2d8c652015-03-11 17:29:39 +01004670 /* This table entry is the object "core" base. */
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004671 lua_newtable(gL.T);
4672
4673 /* Push the loglevel constants. */
Willy Tarreau80f5fae2015-02-27 16:38:20 +01004674 for (i = 0; i < NB_LOG_LEVELS; i++)
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004675 hlua_class_const_int(gL.T, log_levels[i], i);
4676
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004677 /* Register special functions. */
4678 hlua_class_function(gL.T, "register_init", hlua_register_init);
Thierry FOURNIER24f33532015-01-23 12:13:00 +01004679 hlua_class_function(gL.T, "register_task", hlua_register_task);
Thierry FOURNIERfa0e5dd2015-02-16 20:19:18 +01004680 hlua_class_function(gL.T, "register_fetches", hlua_register_fetches);
Thierry FOURNIER9be813f2015-02-16 20:21:12 +01004681 hlua_class_function(gL.T, "register_converters", hlua_register_converters);
Thierry FOURNIER13416fe2015-02-17 15:01:59 +01004682 hlua_class_function(gL.T, "yield", hlua_yield);
Willy Tarreau59551662015-03-10 14:23:13 +01004683 hlua_class_function(gL.T, "set_nice", hlua_set_nice);
Thierry FOURNIER5b8608f2015-02-16 19:43:25 +01004684 hlua_class_function(gL.T, "sleep", hlua_sleep);
4685 hlua_class_function(gL.T, "msleep", hlua_msleep);
Thierry FOURNIER83758bb2015-02-04 13:21:04 +01004686 hlua_class_function(gL.T, "add_acl", hlua_add_acl);
4687 hlua_class_function(gL.T, "del_acl", hlua_del_acl);
4688 hlua_class_function(gL.T, "set_map", hlua_set_map);
4689 hlua_class_function(gL.T, "del_map", hlua_del_map);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004690 hlua_class_function(gL.T, "tcp", hlua_socket_new);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004691 hlua_class_function(gL.T, "log", hlua_log);
4692 hlua_class_function(gL.T, "Debug", hlua_log_debug);
4693 hlua_class_function(gL.T, "Info", hlua_log_info);
4694 hlua_class_function(gL.T, "Warning", hlua_log_warning);
4695 hlua_class_function(gL.T, "Alert", hlua_log_alert);
Thierry FOURNIERa4a0f3d2015-01-23 12:08:30 +01004696
Thierry FOURNIER2ba18a22015-01-23 14:07:08 +01004697 lua_setglobal(gL.T, "core");
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004698
4699 /*
4700 *
Thierry FOURNIER3def3932015-04-07 11:27:54 +02004701 * Register class Map
4702 *
4703 */
4704
4705 /* This table entry is the object "Map" base. */
4706 lua_newtable(gL.T);
4707
4708 /* register pattern types. */
4709 for (i=0; i<PAT_MATCH_NUM; i++)
4710 hlua_class_const_int(gL.T, pat_match_names[i], i);
4711
4712 /* register constructor. */
4713 hlua_class_function(gL.T, "new", hlua_map_new);
4714
4715 /* Create and fill the metatable. */
4716 lua_newtable(gL.T);
4717
4718 /* Create and fille the __index entry. */
4719 lua_pushstring(gL.T, "__index");
4720 lua_newtable(gL.T);
4721
4722 /* Register . */
4723 hlua_class_function(gL.T, "lookup", hlua_map_lookup);
4724 hlua_class_function(gL.T, "slookup", hlua_map_slookup);
4725
4726 lua_settable(gL.T, -3);
4727
4728 /* Register previous table in the registry with reference and named entry. */
4729 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4730 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4731 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_MAP); /* register class session. */
4732 class_map_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4733
4734 /* Assign the metatable to the mai Map object. */
4735 lua_setmetatable(gL.T, -2);
4736
4737 /* Set a name to the table. */
4738 lua_setglobal(gL.T, "Map");
4739
4740 /*
4741 *
Thierry FOURNIER5a6d3fd2015-02-09 16:38:34 +01004742 * Register class Channel
4743 *
4744 */
4745
4746 /* Create and fill the metatable. */
4747 lua_newtable(gL.T);
4748
4749 /* Create and fille the __index entry. */
4750 lua_pushstring(gL.T, "__index");
4751 lua_newtable(gL.T);
4752
4753 /* Register . */
4754 hlua_class_function(gL.T, "get", hlua_channel_get);
4755 hlua_class_function(gL.T, "dup", hlua_channel_dup);
4756 hlua_class_function(gL.T, "getline", hlua_channel_getline);
4757 hlua_class_function(gL.T, "set", hlua_channel_set);
4758 hlua_class_function(gL.T, "append", hlua_channel_append);
4759 hlua_class_function(gL.T, "send", hlua_channel_send);
4760 hlua_class_function(gL.T, "forward", hlua_channel_forward);
4761 hlua_class_function(gL.T, "get_in_len", hlua_channel_get_in_len);
4762 hlua_class_function(gL.T, "get_out_len", hlua_channel_get_out_len);
4763
4764 lua_settable(gL.T, -3);
4765
4766 /* Register previous table in the registry with reference and named entry. */
4767 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4768 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CHANNEL); /* register class session. */
4769 class_channel_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4770
4771 /*
4772 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004773 * Register class Fetches
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004774 *
4775 */
4776
4777 /* Create and fill the metatable. */
4778 lua_newtable(gL.T);
4779
4780 /* Create and fille the __index entry. */
4781 lua_pushstring(gL.T, "__index");
4782 lua_newtable(gL.T);
4783
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004784 /* Browse existing fetches and create the associated
4785 * object method.
4786 */
4787 sf = NULL;
4788 while ((sf = sample_fetch_getnext(sf, &idx)) != NULL) {
4789
4790 /* Dont register the keywork if the arguments check function are
4791 * not safe during the runtime.
4792 */
4793 if ((sf->val_args != NULL) &&
4794 (sf->val_args != val_payload_lv) &&
4795 (sf->val_args != val_hdr))
4796 continue;
4797
4798 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4799 * by an underscore.
4800 */
4801 strncpy(trash.str, sf->kw, trash.size);
4802 trash.str[trash.size - 1] = '\0';
4803 for (p = trash.str; *p; p++)
4804 if (*p == '.' || *p == '-' || *p == '+')
4805 *p = '_';
4806
4807 /* Register the function. */
4808 lua_pushstring(gL.T, trash.str);
Willy Tarreau2ec22742015-03-10 14:27:20 +01004809 lua_pushlightuserdata(gL.T, sf);
Thierry FOURNIERd0fa5382015-02-16 20:14:51 +01004810 lua_pushcclosure(gL.T, hlua_run_sample_fetch, 1);
4811 lua_settable(gL.T, -3);
4812 }
4813
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004814 lua_settable(gL.T, -3);
4815
4816 /* Register previous table in the registry with reference and named entry. */
4817 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4818 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_FETCHES); /* register class session. */
4819 class_fetches_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4820
4821 /*
4822 *
Thierry FOURNIER594afe72015-03-10 23:58:30 +01004823 * Register class Converters
4824 *
4825 */
4826
4827 /* Create and fill the metatable. */
4828 lua_newtable(gL.T);
4829
4830 /* Create and fill the __index entry. */
4831 lua_pushstring(gL.T, "__index");
4832 lua_newtable(gL.T);
4833
4834 /* Browse existing converters and create the associated
4835 * object method.
4836 */
4837 sc = NULL;
4838 while ((sc = sample_conv_getnext(sc, &idx)) != NULL) {
4839 /* Dont register the keywork if the arguments check function are
4840 * not safe during the runtime.
4841 */
4842 if (sc->val_args != NULL)
4843 continue;
4844
4845 /* gL.Tua doesn't support '.' and '-' in the function names, replace it
4846 * by an underscore.
4847 */
4848 strncpy(trash.str, sc->kw, trash.size);
4849 trash.str[trash.size - 1] = '\0';
4850 for (p = trash.str; *p; p++)
4851 if (*p == '.' || *p == '-' || *p == '+')
4852 *p = '_';
4853
4854 /* Register the function. */
4855 lua_pushstring(gL.T, trash.str);
4856 lua_pushlightuserdata(gL.T, sc);
4857 lua_pushcclosure(gL.T, hlua_run_sample_conv, 1);
4858 lua_settable(gL.T, -3);
4859 }
4860
4861 lua_settable(gL.T, -3);
4862
4863 /* Register previous table in the registry with reference and named entry. */
4864 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4865 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_CONVERTERS); /* register class session. */
4866 class_converters_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4867
4868 /*
4869 *
Thierry FOURNIER08504f42015-03-16 14:17:08 +01004870 * Register class HTTP
4871 *
4872 */
4873
4874 /* Create and fill the metatable. */
4875 lua_newtable(gL.T);
4876
4877 /* Create and fille the __index entry. */
4878 lua_pushstring(gL.T, "__index");
4879 lua_newtable(gL.T);
4880
4881 /* Register Lua functions. */
4882 hlua_class_function(gL.T, "req_get_headers",hlua_http_req_get_headers);
4883 hlua_class_function(gL.T, "req_del_header", hlua_http_req_del_hdr);
4884 hlua_class_function(gL.T, "req_rep_header", hlua_http_req_rep_hdr);
4885 hlua_class_function(gL.T, "req_rep_value", hlua_http_req_rep_val);
4886 hlua_class_function(gL.T, "req_add_header", hlua_http_req_add_hdr);
4887 hlua_class_function(gL.T, "req_set_header", hlua_http_req_set_hdr);
4888 hlua_class_function(gL.T, "req_set_method", hlua_http_req_set_meth);
4889 hlua_class_function(gL.T, "req_set_path", hlua_http_req_set_path);
4890 hlua_class_function(gL.T, "req_set_query", hlua_http_req_set_query);
4891 hlua_class_function(gL.T, "req_set_uri", hlua_http_req_set_uri);
4892
4893 hlua_class_function(gL.T, "res_get_headers",hlua_http_res_get_headers);
4894 hlua_class_function(gL.T, "res_del_header", hlua_http_res_del_hdr);
4895 hlua_class_function(gL.T, "res_rep_header", hlua_http_res_rep_hdr);
4896 hlua_class_function(gL.T, "res_rep_value", hlua_http_res_rep_val);
4897 hlua_class_function(gL.T, "res_add_header", hlua_http_res_add_hdr);
4898 hlua_class_function(gL.T, "res_set_header", hlua_http_res_set_hdr);
4899
4900 lua_settable(gL.T, -3);
4901
4902 /* Register previous table in the registry with reference and named entry. */
4903 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4904 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_HTTP); /* register class session. */
4905 class_http_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
4906
4907 /*
4908 *
Thierry FOURNIERbb53c7b2015-03-11 18:28:02 +01004909 * Register class TXN
4910 *
4911 */
4912
4913 /* Create and fill the metatable. */
4914 lua_newtable(gL.T);
4915
4916 /* Create and fille the __index entry. */
4917 lua_pushstring(gL.T, "__index");
4918 lua_newtable(gL.T);
4919
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004920 /* Register Lua functions. */
Willy Tarreau59551662015-03-10 14:23:13 +01004921 hlua_class_function(gL.T, "set_priv", hlua_set_priv);
4922 hlua_class_function(gL.T, "get_priv", hlua_get_priv);
Thierry FOURNIER053ba8ad2015-06-08 13:05:33 +02004923 hlua_class_function(gL.T, "set_var", hlua_set_var);
4924 hlua_class_function(gL.T, "get_var", hlua_get_var);
Thierry FOURNIER893bfa32015-02-17 18:42:34 +01004925 hlua_class_function(gL.T, "close", hlua_txn_close);
Thierry FOURNIER2cce3532015-03-16 12:04:16 +01004926 hlua_class_function(gL.T, "set_loglevel",hlua_txn_set_loglevel);
4927 hlua_class_function(gL.T, "set_tos", hlua_txn_set_tos);
4928 hlua_class_function(gL.T, "set_mark", hlua_txn_set_mark);
Thierry FOURNIERc798b5d2015-03-17 01:09:57 +01004929 hlua_class_function(gL.T, "deflog", hlua_txn_deflog);
4930 hlua_class_function(gL.T, "log", hlua_txn_log);
4931 hlua_class_function(gL.T, "Debug", hlua_txn_log_debug);
4932 hlua_class_function(gL.T, "Info", hlua_txn_log_info);
4933 hlua_class_function(gL.T, "Warning", hlua_txn_log_warning);
4934 hlua_class_function(gL.T, "Alert", hlua_txn_log_alert);
Thierry FOURNIER05c0b8a2015-02-25 11:43:21 +01004935
Thierry FOURNIER65f34c62015-02-16 20:11:43 +01004936 lua_settable(gL.T, -3);
4937
4938 /* Register previous table in the registry with reference and named entry. */
4939 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4940 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_TXN); /* register class session. */
4941 class_txn_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class session. */
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004942
4943 /*
4944 *
4945 * Register class Socket
4946 *
4947 */
4948
4949 /* Create and fill the metatable. */
4950 lua_newtable(gL.T);
4951
4952 /* Create and fille the __index entry. */
4953 lua_pushstring(gL.T, "__index");
4954 lua_newtable(gL.T);
4955
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004956#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004957 hlua_class_function(gL.T, "connect_ssl", hlua_socket_connect_ssl);
Baptiste Assmann84bb4932015-03-02 21:40:06 +01004958#endif
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01004959 hlua_class_function(gL.T, "connect", hlua_socket_connect);
4960 hlua_class_function(gL.T, "send", hlua_socket_send);
4961 hlua_class_function(gL.T, "receive", hlua_socket_receive);
4962 hlua_class_function(gL.T, "close", hlua_socket_close);
4963 hlua_class_function(gL.T, "getpeername", hlua_socket_getpeername);
4964 hlua_class_function(gL.T, "getsockname", hlua_socket_getsockname);
4965 hlua_class_function(gL.T, "setoption", hlua_socket_setoption);
4966 hlua_class_function(gL.T, "settimeout", hlua_socket_settimeout);
4967
4968 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4969
4970 /* Register the garbage collector entry. */
4971 lua_pushstring(gL.T, "__gc");
4972 lua_pushcclosure(gL.T, hlua_socket_gc, 0);
4973 lua_settable(gL.T, -3); /* Push the last 2 entries in the table at index -3 */
4974
4975 /* Register previous table in the registry with reference and named entry. */
4976 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4977 lua_pushvalue(gL.T, -1); /* Copy the -1 entry and push it on the stack. */
4978 lua_setfield(gL.T, LUA_REGISTRYINDEX, CLASS_SOCKET); /* register class socket. */
4979 class_socket_ref = luaL_ref(gL.T, LUA_REGISTRYINDEX); /* reference class socket. */
4980
4981 /* Proxy and server configuration initialisation. */
4982 memset(&socket_proxy, 0, sizeof(socket_proxy));
4983 init_new_proxy(&socket_proxy);
4984 socket_proxy.parent = NULL;
4985 socket_proxy.last_change = now.tv_sec;
4986 socket_proxy.id = "LUA-SOCKET";
4987 socket_proxy.cap = PR_CAP_FE | PR_CAP_BE;
4988 socket_proxy.maxconn = 0;
4989 socket_proxy.accept = NULL;
4990 socket_proxy.options2 |= PR_O2_INDEPSTR;
4991 socket_proxy.srv = NULL;
4992 socket_proxy.conn_retries = 0;
4993 socket_proxy.timeout.connect = 5000; /* By default the timeout connection is 5s. */
4994
4995 /* Init TCP server: unchanged parameters */
4996 memset(&socket_tcp, 0, sizeof(socket_tcp));
4997 socket_tcp.next = NULL;
4998 socket_tcp.proxy = &socket_proxy;
4999 socket_tcp.obj_type = OBJ_TYPE_SERVER;
5000 LIST_INIT(&socket_tcp.actconns);
5001 LIST_INIT(&socket_tcp.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005002 LIST_INIT(&socket_tcp.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005003 LIST_INIT(&socket_tcp.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005004 LIST_INIT(&socket_tcp.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005005 socket_tcp.state = SRV_ST_RUNNING; /* early server setup */
5006 socket_tcp.last_change = 0;
5007 socket_tcp.id = "LUA-TCP-CONN";
5008 socket_tcp.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5009 socket_tcp.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5010 socket_tcp.pp_opts = 0; /* Remove proxy protocol. */
5011
5012 /* XXX: Copy default parameter from default server,
5013 * but the default server is not initialized.
5014 */
5015 socket_tcp.maxqueue = socket_proxy.defsrv.maxqueue;
5016 socket_tcp.minconn = socket_proxy.defsrv.minconn;
5017 socket_tcp.maxconn = socket_proxy.defsrv.maxconn;
5018 socket_tcp.slowstart = socket_proxy.defsrv.slowstart;
5019 socket_tcp.onerror = socket_proxy.defsrv.onerror;
5020 socket_tcp.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5021 socket_tcp.onmarkedup = socket_proxy.defsrv.onmarkedup;
5022 socket_tcp.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5023 socket_tcp.uweight = socket_proxy.defsrv.iweight;
5024 socket_tcp.iweight = socket_proxy.defsrv.iweight;
5025
5026 socket_tcp.check.status = HCHK_STATUS_INI;
5027 socket_tcp.check.rise = socket_proxy.defsrv.check.rise;
5028 socket_tcp.check.fall = socket_proxy.defsrv.check.fall;
5029 socket_tcp.check.health = socket_tcp.check.rise; /* socket, but will fall down at first failure */
5030 socket_tcp.check.server = &socket_tcp;
5031
5032 socket_tcp.agent.status = HCHK_STATUS_INI;
5033 socket_tcp.agent.rise = socket_proxy.defsrv.agent.rise;
5034 socket_tcp.agent.fall = socket_proxy.defsrv.agent.fall;
5035 socket_tcp.agent.health = socket_tcp.agent.rise; /* socket, but will fall down at first failure */
5036 socket_tcp.agent.server = &socket_tcp;
5037
5038 socket_tcp.xprt = &raw_sock;
5039
5040#ifdef USE_OPENSSL
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005041 /* Init TCP server: unchanged parameters */
5042 memset(&socket_ssl, 0, sizeof(socket_ssl));
5043 socket_ssl.next = NULL;
5044 socket_ssl.proxy = &socket_proxy;
5045 socket_ssl.obj_type = OBJ_TYPE_SERVER;
5046 LIST_INIT(&socket_ssl.actconns);
5047 LIST_INIT(&socket_ssl.pendconns);
Willy Tarreau600802a2015-08-04 17:19:06 +02005048 LIST_INIT(&socket_ssl.priv_conns);
Willy Tarreau173a1c62015-08-05 10:31:57 +02005049 LIST_INIT(&socket_ssl.idle_conns);
Willy Tarreau7017cb02015-08-05 16:35:23 +02005050 LIST_INIT(&socket_ssl.safe_conns);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005051 socket_ssl.state = SRV_ST_RUNNING; /* early server setup */
5052 socket_ssl.last_change = 0;
5053 socket_ssl.id = "LUA-SSL-CONN";
5054 socket_ssl.check.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5055 socket_ssl.agent.state &= ~CHK_ST_ENABLED; /* Disable health checks. */
5056 socket_ssl.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_ssl.maxqueue = socket_proxy.defsrv.maxqueue;
5062 socket_ssl.minconn = socket_proxy.defsrv.minconn;
5063 socket_ssl.maxconn = socket_proxy.defsrv.maxconn;
5064 socket_ssl.slowstart = socket_proxy.defsrv.slowstart;
5065 socket_ssl.onerror = socket_proxy.defsrv.onerror;
5066 socket_ssl.onmarkeddown = socket_proxy.defsrv.onmarkeddown;
5067 socket_ssl.onmarkedup = socket_proxy.defsrv.onmarkedup;
5068 socket_ssl.consecutive_errors_limit = socket_proxy.defsrv.consecutive_errors_limit;
5069 socket_ssl.uweight = socket_proxy.defsrv.iweight;
5070 socket_ssl.iweight = socket_proxy.defsrv.iweight;
5071
5072 socket_ssl.check.status = HCHK_STATUS_INI;
5073 socket_ssl.check.rise = socket_proxy.defsrv.check.rise;
5074 socket_ssl.check.fall = socket_proxy.defsrv.check.fall;
5075 socket_ssl.check.health = socket_ssl.check.rise; /* socket, but will fall down at first failure */
5076 socket_ssl.check.server = &socket_ssl;
5077
5078 socket_ssl.agent.status = HCHK_STATUS_INI;
5079 socket_ssl.agent.rise = socket_proxy.defsrv.agent.rise;
5080 socket_ssl.agent.fall = socket_proxy.defsrv.agent.fall;
5081 socket_ssl.agent.health = socket_ssl.agent.rise; /* socket, but will fall down at first failure */
5082 socket_ssl.agent.server = &socket_ssl;
5083
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005084 socket_ssl.use_ssl = 1;
5085 socket_ssl.xprt = &ssl_sock;
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005086
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005087 for (idx = 0; args[idx] != NULL; idx++) {
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005088 if ((kw = srv_find_kw(args[idx])) != NULL) { /* Maybe it's registered server keyword */
5089 /*
5090 *
5091 * If the keyword is not known, we can search in the registered
5092 * server keywords. This is usefull to configure special SSL
5093 * features like client certificates and ssl_verify.
5094 *
5095 */
5096 tmp_error = kw->parse(args, &idx, &socket_proxy, &socket_ssl, &error);
5097 if (tmp_error != 0) {
5098 fprintf(stderr, "INTERNAL ERROR: %s\n", error);
5099 abort(); /* This must be never arrives because the command line
5100 not editable by the user. */
5101 }
5102 idx += kw->skip;
5103 }
5104 }
5105
5106 /* Initialize SSL server. */
Thierry FOURNIER36d13742015-03-17 16:48:53 +01005107 ssl_sock_prepare_srv_ctx(&socket_ssl, &socket_proxy);
Thierry FOURNIER7e7ac322015-02-16 19:27:16 +01005108#endif
Thierry FOURNIER6f1fd482015-01-23 14:06:13 +01005109}