1 /*
2  * Lua safe functions
3  *
4  * Copyright 2015-2016 Thierry Fournier <tfournier@arpalert.org>
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version
9  * 2 of the License, or (at your option) any later version.
10  *
11  *
12  * All the functions in this file runs with a Lua stack, and can
13  * return with a longjmp. All of these function must be launched
14  * in an environment able to catch a longjmp, otherwise a
15  * critical error can be raised.
16  */
17 
18 #define _GNU_SOURCE
19 
20 #include <lauxlib.h>
21 #include <lua.h>
22 #include <lualib.h>
23 
24 #include <haproxy/cli-t.h>
25 #include <haproxy/errors.h>
26 #include <haproxy/hlua-t.h>
27 #include <haproxy/http.h>
28 #include <haproxy/net_helper.h>
29 #include <haproxy/pattern-t.h>
30 #include <haproxy/proxy.h>
31 #include <haproxy/regex.h>
32 #include <haproxy/server.h>
33 #include <haproxy/stats.h>
34 #include <haproxy/stick_table.h>
35 #include <haproxy/time.h>
36 
37 /* Contains the class reference of the concat object. */
38 static int class_concat_ref;
39 static int class_proxy_ref;
40 static int class_server_ref;
41 static int class_listener_ref;
42 static int class_regex_ref;
43 static int class_stktable_ref;
44 
45 #define STATS_LEN (MAX((int)ST_F_TOTAL_FIELDS, (int)INF_TOTAL_FIELDS))
46 
47 static THREAD_LOCAL struct field stats[STATS_LEN];
48 
hlua_checkboolean(lua_State * L,int index)49 int hlua_checkboolean(lua_State *L, int index)
50 {
51 	if (!lua_isboolean(L, index))
52 		luaL_argerror(L, index, "boolean expected");
53 	return lua_toboolean(L, index);
54 }
55 
56 /* Helper to push unsigned integers to Lua stack, respecting Lua limitations  */
hlua_fcn_pushunsigned(lua_State * L,unsigned int val)57 static int hlua_fcn_pushunsigned(lua_State *L, unsigned int val)
58 {
59 #if (LUA_MAXINTEGER == LLONG_MAX || ((LUA_MAXINTEGER == LONG_MAX) && (__WORDSIZE == 64)))
60 	lua_pushinteger(L, val);
61 #else
62 	if (val > INT_MAX)
63 		lua_pushnumber(L, (lua_Number)val);
64 	else
65 		lua_pushinteger(L, (int)val);
66 #endif
67 	return 1;
68 }
69 
70 /* Helper to push unsigned long long to Lua stack, respecting Lua limitations  */
hlua_fcn_pushunsigned_ll(lua_State * L,unsigned long long val)71 static int hlua_fcn_pushunsigned_ll(lua_State *L, unsigned long long val) {
72 #if (LUA_MAXINTEGER == LLONG_MAX || ((LUA_MAXINTEGER == LONG_MAX) && (__WORDSIZE == 64)))
73 	/* 64 bits case, U64 is supported until LLONG_MAX */
74 	if (val > LLONG_MAX)
75 		lua_pushnumber(L, (lua_Number)val);
76 	else
77 		lua_pushinteger(L, val);
78 #else
79 	/* 32 bits case, U64 is supported until INT_MAX */
80 	if (val > INT_MAX)
81 		lua_pushnumber(L, (lua_Number)val);
82 	else
83 		lua_pushinteger(L, (int)val);
84 #endif
85 	return 1;
86 }
87 
88 /* This function gets a struct field and converts it in Lua
89  * variable. The variable is pushed at the top of the stack.
90  */
hlua_fcn_pushfield(lua_State * L,struct field * field)91 int hlua_fcn_pushfield(lua_State *L, struct field *field)
92 {
93 	/* The lua_Integer is always signed. Its length depends on
94 	 * compilation options, so the following code is conditioned
95 	 * by some macros. Windows maros are not supported.
96 	 * If the number cannot be represented as integer, we try to
97 	 * convert to float.
98 	 */
99 	switch (field_format(field, 0)) {
100 
101 	case FF_EMPTY:
102 		lua_pushnil(L);
103 		return 1;
104 
105 	case FF_S32:
106 		/* S32 is always supported. */
107 		lua_pushinteger(L, field->u.s32);
108 		return 1;
109 
110 	case FF_U32:
111 #if (LUA_MAXINTEGER == LLONG_MAX || ((LUA_MAXINTEGER == LONG_MAX) && (__WORDSIZE == 64)))
112 		/* 64 bits case, U32 is always supported */
113 		lua_pushinteger(L, field->u.u32);
114 #else
115 		/* 32 bits case, U32 is supported until INT_MAX. */
116 		if (field->u.u32 > INT_MAX)
117 			lua_pushnumber(L, (lua_Number)field->u.u32);
118 		else
119 			lua_pushinteger(L, field->u.u32);
120 #endif
121 		return 1;
122 
123 	case FF_S64:
124 #if (LUA_MAXINTEGER == LLONG_MAX || ((LUA_MAXINTEGER == LONG_MAX) && (__WORDSIZE == 64)))
125 		/* 64 bits case, S64 is always supported */
126 		lua_pushinteger(L, field->u.s64);
127 #else
128 		/* 64 bits case, S64 is supported between INT_MIN and INT_MAX */
129 		if (field->u.s64 < INT_MIN || field->u.s64 > INT_MAX)
130 			lua_pushnumber(L, (lua_Number)field->u.s64);
131 		else
132 			lua_pushinteger(L, (int)field->u.s64);
133 #endif
134 		return 1;
135 
136 	case FF_U64:
137 #if (LUA_MAXINTEGER == LLONG_MAX || ((LUA_MAXINTEGER == LONG_MAX) && (__WORDSIZE == 64)))
138 		/* 64 bits case, U64 is supported until LLONG_MAX */
139 		if (field->u.u64 > LLONG_MAX)
140 			lua_pushnumber(L, (lua_Number)field->u.u64);
141 		else
142 			lua_pushinteger(L, field->u.u64);
143 #else
144 		/* 64 bits case, U64 is supported until INT_MAX */
145 		if (field->u.u64 > INT_MAX)
146 			lua_pushnumber(L, (lua_Number)field->u.u64);
147 		else
148 			lua_pushinteger(L, (int)field->u.u64);
149 #endif
150 		return 1;
151 
152 	case FF_STR:
153 		lua_pushstring(L, field->u.str);
154 		return 1;
155 
156 	default:
157 		break;
158 	}
159 
160 	/* Default case, never reached. */
161 	lua_pushnil(L);
162 	return 1;
163 }
164 
165 /* Some string are started or terminated by blank chars,
166  * this function removes the spaces, tabs, \r and
167  * \n at the begin and at the end of the string "str", and
168  * push the result in the lua stack.
169  * Returns a pointer to the Lua internal copy of the string.
170  */
hlua_pushstrippedstring(lua_State * L,const char * str)171 const char *hlua_pushstrippedstring(lua_State *L, const char *str)
172 {
173 	const char *p;
174 	int l;
175 
176 	for (p = str; HTTP_IS_LWS(*p); p++);
177 
178 	for (l = strlen(p); l && HTTP_IS_LWS(p[l-1]); l--);
179 
180 	return lua_pushlstring(L, p, l);
181 }
182 
183 /* The three following functions are useful for adding entries
184  * in a table. These functions takes a string and respectively an
185  * integer, a string or a function and add it to the table in the
186  * top of the stack.
187  *
188  * These functions throws an error if no more stack size is
189  * available.
190  */
hlua_class_const_int(lua_State * L,const char * name,int value)191 void hlua_class_const_int(lua_State *L, const char *name, int value)
192 {
193 	lua_pushstring(L, name);
194 	lua_pushinteger(L, value);
195 	lua_rawset(L, -3);
196 }
hlua_class_const_str(lua_State * L,const char * name,const char * value)197 void hlua_class_const_str(lua_State *L, const char *name, const char *value)
198 {
199 	lua_pushstring(L, name);
200 	lua_pushstring(L, value);
201 	lua_rawset(L, -3);
202 }
hlua_class_function(lua_State * L,const char * name,int (* function)(lua_State * L))203 void hlua_class_function(lua_State *L, const char *name, int (*function)(lua_State *L))
204 {
205 	lua_pushstring(L, name);
206 	lua_pushcclosure(L, function, 0);
207 	lua_rawset(L, -3);
208 }
209 
210 /* This function returns a string containing the HAProxy object name. */
hlua_dump_object(struct lua_State * L)211 int hlua_dump_object(struct lua_State *L)
212 {
213 	const char *name = (const char *)lua_tostring(L, lua_upvalueindex(1));
214 	lua_pushfstring(L, "HAProxy class %s", name);
215 	return 1;
216 }
217 
218 /* This function register a table as metatable and. It names
219  * the metatable, and returns the associated reference.
220  * The original table is popped from the top of the stack.
221  * "name" is the referenced class name.
222  */
hlua_register_metatable(struct lua_State * L,char * name)223 int hlua_register_metatable(struct lua_State *L, char *name)
224 {
225 	/* Check the type of the top element. it must be
226 	 * a table.
227 	 */
228 	if (lua_type(L, -1) != LUA_TTABLE)
229 		luaL_error(L, "hlua_register_metatable() requires a type Table "
230 		              "in the top of the stack");
231 
232 	/* Add the __tostring function which identify the
233 	 * created object.
234 	 */
235 	lua_pushstring(L, "__tostring");
236 	lua_pushstring(L, name);
237 	lua_pushcclosure(L, hlua_dump_object, 1);
238 	lua_rawset(L, -3);
239 
240 	/* Register a named entry for the table. The table
241 	 * reference is copied first because the function
242 	 * lua_setfield() pop the entry.
243 	 */
244 	lua_pushvalue(L, -1);
245 	lua_setfield(L, LUA_REGISTRYINDEX, name);
246 
247 	/* Creates the reference of the object. The
248 	 * function luaL_ref pop the top of the stack.
249 	 */
250 	return luaL_ref(L, LUA_REGISTRYINDEX);
251 }
252 
253 /* Return an object of the expected type, or throws an error. */
hlua_checkudata(lua_State * L,int ud,int class_ref)254 void *hlua_checkudata(lua_State *L, int ud, int class_ref)
255 {
256 	void *p;
257 	int ret;
258 
259 	/* Check if the stack entry is an array. */
260 	if (!lua_istable(L, ud))
261 		luaL_argerror(L, ud, NULL);
262 
263 	/* pop the metatable of the referencecd object. */
264 	if (!lua_getmetatable(L, ud))
265 		luaL_argerror(L, ud, NULL);
266 
267 	/* pop the expected metatable. */
268 	lua_rawgeti(L, LUA_REGISTRYINDEX, class_ref);
269 
270 	/* Check if the metadata have the expected type. */
271 	ret = lua_rawequal(L, -1, -2);
272 	lua_pop(L, 2);
273 	if (!ret)
274 		luaL_argerror(L, ud, NULL);
275 
276 	/* Push on the stack at the entry [0] of the table. */
277 	lua_rawgeti(L, ud, 0);
278 
279 	/* Check if this entry is userdata. */
280 	p = lua_touserdata(L, -1);
281 	if (!p)
282 		luaL_argerror(L, ud, NULL);
283 
284 	/* Remove the entry returned by lua_rawgeti(). */
285 	lua_pop(L, 1);
286 
287 	/* Return the associated struct. */
288 	return p;
289 }
290 
291 /* This function return the current date at epoch format in milliseconds. */
hlua_now(lua_State * L)292 int hlua_now(lua_State *L)
293 {
294 	lua_newtable(L);
295 	lua_pushstring(L, "sec");
296 	lua_pushinteger(L, now.tv_sec);
297 	lua_rawset(L, -3);
298 	lua_pushstring(L, "usec");
299 	lua_pushinteger(L, now.tv_usec);
300 	lua_rawset(L, -3);
301 	return 1;
302 }
303 
304 /* This functions expects a Lua string as HTTP date, parse it and
305  * returns an integer containing the epoch format of the date, or
306  * nil if the parsing fails.
307  */
hlua_parse_date(lua_State * L,int (* fcn)(const char *,int,struct tm *))308 static int hlua_parse_date(lua_State *L, int (*fcn)(const char *, int, struct tm*))
309 {
310 	const char *str;
311 	size_t len;
312 	struct tm tm;
313 	time_t time;
314 
315 	str = luaL_checklstring(L, 1, &len);
316 
317 	if (!fcn(str, len, &tm)) {
318 		lua_pushnil(L);
319 		return 1;
320 	}
321 
322 	/* This function considers the content of the broken-down time
323 	 * is exprimed in the UTC timezone. timegm don't care about
324 	 * the gnu variable tm_gmtoff. If gmtoff is set, or if you know
325 	 * the timezone from the broken-down time, it must be fixed
326 	 * after the conversion.
327 	 */
328 	time = my_timegm(&tm);
329 	if (time == -1) {
330 		lua_pushnil(L);
331 		return 1;
332 	}
333 
334 	lua_pushinteger(L, (int)time);
335 	return 1;
336 }
hlua_http_date(lua_State * L)337 static int hlua_http_date(lua_State *L)
338 {
339 	return hlua_parse_date(L, parse_http_date);
340 }
hlua_imf_date(lua_State * L)341 static int hlua_imf_date(lua_State *L)
342 {
343 	return hlua_parse_date(L, parse_imf_date);
344 }
hlua_rfc850_date(lua_State * L)345 static int hlua_rfc850_date(lua_State *L)
346 {
347 	return hlua_parse_date(L, parse_rfc850_date);
348 }
hlua_asctime_date(lua_State * L)349 static int hlua_asctime_date(lua_State *L)
350 {
351 	return hlua_parse_date(L, parse_asctime_date);
352 }
353 
hlua_get_info(lua_State * L)354 static int hlua_get_info(lua_State *L)
355 {
356 	int i;
357 
358 	stats_fill_info(stats, STATS_LEN);
359 
360 	lua_newtable(L);
361 	for (i=0; i<INF_TOTAL_FIELDS; i++) {
362 		lua_pushstring(L, info_fields[i].name);
363 		hlua_fcn_pushfield(L, &stats[i]);
364 		lua_settable(L, -3);
365 	}
366 	return 1;
367 }
368 
hlua_check_concat(lua_State * L,int ud)369 static struct hlua_concat *hlua_check_concat(lua_State *L, int ud)
370 {
371 	return (hlua_checkudata(L, ud, class_concat_ref));
372 }
373 
hlua_concat_add(lua_State * L)374 static int hlua_concat_add(lua_State *L)
375 {
376 	struct hlua_concat *b;
377 	char *buffer;
378 	char *new;
379 	const char *str;
380 	size_t l;
381 
382 	/* First arg must be a concat object. */
383 	b = hlua_check_concat(L, 1);
384 
385 	/* Second arg must be a string. */
386 	str = luaL_checklstring(L, 2, &l);
387 
388 	/* Get the buffer. */
389 	lua_rawgeti(L, 1, 1);
390 	buffer = lua_touserdata(L, -1);
391 	lua_pop(L, 1);
392 
393 	/* Update the buffer size if it s required. The old buffer
394 	 * is crushed by the new in the object array, so it will
395 	 * be deleted by the GC.
396 	 * Note that in the first loop, the "new" variable is only
397 	 * used as a flag.
398 	 */
399 	new = NULL;
400 	while (b->size - b->len < l) {
401 		b->size += HLUA_CONCAT_BLOCSZ;
402 		new = buffer;
403 	}
404 	if (new) {
405 		new = lua_newuserdata(L, b->size);
406 		memcpy(new, buffer, b->len);
407 		lua_rawseti(L, 1, 1);
408 		buffer = new;
409 	}
410 
411 	/* Copy string, and update metadata. */
412 	memcpy(buffer + b->len, str, l);
413 	b->len += l;
414 	return 0;
415 }
416 
hlua_concat_dump(lua_State * L)417 static int hlua_concat_dump(lua_State *L)
418 {
419 	struct hlua_concat *b;
420 	char *buffer;
421 
422 	/* First arg must be a concat object. */
423 	b = hlua_check_concat(L, 1);
424 
425 	/* Get the buffer. */
426 	lua_rawgeti(L, 1, 1);
427 	buffer = lua_touserdata(L, -1);
428 	lua_pop(L, 1);
429 
430 	/* Push the soncatenated string in the stack. */
431 	lua_pushlstring(L, buffer, b->len);
432 	return 1;
433 }
434 
hlua_concat_new(lua_State * L)435 int hlua_concat_new(lua_State *L)
436 {
437 	struct hlua_concat *b;
438 
439 	lua_newtable(L);
440 	b = lua_newuserdata(L, sizeof(*b));
441 	b->size = HLUA_CONCAT_BLOCSZ;
442 	b->len = 0;
443 	lua_rawseti(L, -2, 0);
444 	lua_newuserdata(L, HLUA_CONCAT_BLOCSZ);
445 	lua_rawseti(L, -2, 1);
446 
447 	lua_rawgeti(L, LUA_REGISTRYINDEX, class_concat_ref);
448 	lua_setmetatable(L, -2);
449 
450 	return 1;
451 }
452 
concat_tostring(lua_State * L)453 static int concat_tostring(lua_State *L)
454 {
455 	const void *ptr = lua_topointer(L, 1);
456 	lua_pushfstring(L, "Concat object: %p", ptr);
457 	return 1;
458 }
459 
hlua_concat_init(lua_State * L)460 static int hlua_concat_init(lua_State *L)
461 {
462 	/* Creates the buffered concat object. */
463 	lua_newtable(L);
464 
465 	lua_pushstring(L, "__tostring");
466 	lua_pushcclosure(L, concat_tostring, 0);
467 	lua_settable(L, -3);
468 
469 	lua_pushstring(L, "__index"); /* Creates the index entry. */
470 	lua_newtable(L); /* The "__index" content. */
471 
472 	lua_pushstring(L, "add");
473 	lua_pushcclosure(L, hlua_concat_add, 0);
474 	lua_settable(L, -3);
475 
476 	lua_pushstring(L, "dump");
477 	lua_pushcclosure(L, hlua_concat_dump, 0);
478 	lua_settable(L, -3);
479 
480 	lua_settable(L, -3); /* Sets the __index entry. */
481 	class_concat_ref = luaL_ref(L, LUA_REGISTRYINDEX);
482 
483 	return 1;
484 }
485 
hlua_fcn_new_stktable(lua_State * L,struct stktable * tbl)486 int hlua_fcn_new_stktable(lua_State *L, struct stktable *tbl)
487 {
488 	lua_newtable(L);
489 
490 	/* Pop a class stktbl metatable and affect it to the userdata. */
491 	lua_rawgeti(L, LUA_REGISTRYINDEX, class_stktable_ref);
492 	lua_setmetatable(L, -2);
493 
494 	lua_pushlightuserdata(L, tbl);
495 	lua_rawseti(L, -2, 0);
496 	return 1;
497 }
498 
hlua_check_stktable(lua_State * L,int ud)499 static struct stktable *hlua_check_stktable(lua_State *L, int ud)
500 {
501 	return hlua_checkudata(L, ud, class_stktable_ref);
502 }
503 
504 /* Extract stick table attributes into Lua table */
hlua_stktable_info(lua_State * L)505 int hlua_stktable_info(lua_State *L)
506 {
507 	struct stktable *tbl;
508 	int dt;
509 
510 	tbl = hlua_check_stktable(L, 1);
511 
512 	if (!tbl->id) {
513 		lua_pushnil(L);
514 		return 1;
515 	}
516 
517 	lua_newtable(L);
518 
519 	lua_pushstring(L, "type");
520 	lua_pushstring(L, stktable_types[tbl->type].kw);
521 	lua_settable(L, -3);
522 
523 	lua_pushstring(L, "length");
524 	lua_pushinteger(L, tbl->key_size);
525 	lua_settable(L, -3);
526 
527 	lua_pushstring(L, "size");
528 	hlua_fcn_pushunsigned(L, tbl->size);
529 	lua_settable(L, -3);
530 
531 	lua_pushstring(L, "used");
532 	hlua_fcn_pushunsigned(L, tbl->current);
533 	lua_settable(L, -3);
534 
535 	lua_pushstring(L, "nopurge");
536 	lua_pushboolean(L, tbl->nopurge > 0);
537 	lua_settable(L, -3);
538 
539 	lua_pushstring(L, "expire");
540 	lua_pushinteger(L, tbl->expire);
541 	lua_settable(L, -3);
542 
543 	/* Save data types periods (if applicable) in 'data' table */
544 	lua_pushstring(L, "data");
545 	lua_newtable(L);
546 
547 	for (dt = 0; dt < STKTABLE_DATA_TYPES; dt++) {
548 		if (tbl->data_ofs[dt] == 0)
549 			continue;
550 
551 		lua_pushstring(L, stktable_data_types[dt].name);
552 
553 		if (stktable_data_types[dt].arg_type == ARG_T_DELAY)
554 			lua_pushinteger(L, tbl->data_arg[dt].u);
555 		else
556 			lua_pushinteger(L, -1);
557 
558 		lua_settable(L, -3);
559 	}
560 
561 	lua_settable(L, -3);
562 
563 	return 1;
564 }
565 
566 /* Helper to get extract stick table entry into Lua table */
hlua_stktable_entry(lua_State * L,struct stktable * t,struct stksess * ts)567 static void hlua_stktable_entry(lua_State *L, struct stktable *t, struct stksess *ts)
568 {
569 	int dt;
570 	void *ptr;
571 
572 	for (dt = 0; dt < STKTABLE_DATA_TYPES; dt++) {
573 
574 		if (t->data_ofs[dt] == 0)
575 			continue;
576 
577 		lua_pushstring(L, stktable_data_types[dt].name);
578 
579 		ptr = stktable_data_ptr(t, ts, dt);
580 		switch (stktable_data_types[dt].std_type) {
581 		case STD_T_SINT:
582 			lua_pushinteger(L, stktable_data_cast(ptr, std_t_sint));
583 			break;
584 		case STD_T_UINT:
585 			hlua_fcn_pushunsigned(L, stktable_data_cast(ptr, std_t_uint));
586 			break;
587 		case STD_T_ULL:
588 			hlua_fcn_pushunsigned_ll(L, stktable_data_cast(ptr, std_t_ull));
589 			break;
590 		case STD_T_FRQP:
591 			lua_pushinteger(L, read_freq_ctr_period(&stktable_data_cast(ptr, std_t_frqp),
592 			                t->data_arg[dt].u));
593 			break;
594 		case STD_T_DICT: {
595 			struct dict_entry *de;
596 			de = stktable_data_cast(ptr, std_t_dict);
597 			lua_pushstring(L, de ? (char *)de->value.key : "-");
598 			break;
599 		}
600 		}
601 
602 		lua_settable(L, -3);
603 	}
604 }
605 
606 /* Looks in table <t> for a sticky session matching key <key>
607  * Returns table with session data or nil
608  *
609  * The returned table always contains 'use' and 'expire' (integer) fields.
610  * For frequency/rate counters, each data entry is returned as table with
611  * 'value' and 'period' fields.
612  */
hlua_stktable_lookup(lua_State * L)613 int hlua_stktable_lookup(lua_State *L)
614 {
615 	struct stktable *t;
616 	struct sample smp;
617 	struct stktable_key *skey;
618 	struct stksess *ts;
619 
620 	t = hlua_check_stktable(L, 1);
621 	smp.data.type = SMP_T_STR;
622 	smp.flags = SMP_F_CONST;
623 	smp.data.u.str.area = (char *)lua_tolstring(L, 2, &smp.data.u.str.data);
624 
625 	skey = smp_to_stkey(&smp, t);
626 	if (!skey) {
627 		lua_pushnil(L);
628 		return 1;
629 	}
630 
631 	ts = stktable_lookup_key(t, skey);
632 	if (!ts) {
633 		lua_pushnil(L);
634 		return 1;
635 	}
636 
637 	lua_newtable(L);
638 	lua_pushstring(L, "use");
639 	lua_pushinteger(L, ts->ref_cnt - 1);
640 	lua_settable(L, -3);
641 
642 	lua_pushstring(L, "expire");
643 	lua_pushinteger(L, tick_remain(now_ms, ts->expire));
644 	lua_settable(L, -3);
645 
646 	hlua_stktable_entry(L, t, ts);
647 	HA_SPIN_LOCK(STK_TABLE_LOCK, &t->lock);
648 	ts->ref_cnt--;
649 	HA_SPIN_UNLOCK(STK_TABLE_LOCK, &t->lock);
650 
651 	return 1;
652 }
653 
654 struct stk_filter {
655 	long long val;
656 	int type;
657 	int op;
658 };
659 
660 
661 /* Helper for returning errors to callers using Lua convention (nil, err) */
hlua_error(lua_State * L,const char * fmt,...)662 static int hlua_error(lua_State *L, const char *fmt, ...)  {
663 	char buf[256];
664 	int len;
665 	va_list args;
666 	va_start(args, fmt);
667         len = vsnprintf(buf, sizeof(buf), fmt, args);
668 	va_end(args);
669 
670 	if (len < 0) {
671 		ha_alert("hlua_error(): Could not write error message.\n");
672 		lua_pushnil(L);
673 		return 1;
674 	} else if (len >= sizeof(buf))
675 		ha_alert("hlua_error(): Error message was truncated.\n");
676 
677 	lua_pushnil(L);
678 	lua_pushstring(L, buf);
679 
680 	return 2;
681 }
682 
683 /* Dump the contents of stick table <t>*/
hlua_stktable_dump(lua_State * L)684 int hlua_stktable_dump(lua_State *L)
685 {
686 	struct stktable *t;
687 	struct ebmb_node *eb;
688 	struct ebmb_node *n;
689 	struct stksess *ts;
690 	int type;
691 	int op;
692 	int dt;
693 	long long val;
694 	struct stk_filter filter[STKTABLE_FILTER_LEN];
695 	int filter_count = 0;
696 	int i;
697 	int skip_entry;
698 	void *ptr;
699 
700 	t = hlua_check_stktable(L, 1);
701 	type = lua_type(L, 2);
702 
703 	switch (type) {
704 	case LUA_TNONE:
705 	case LUA_TNIL:
706 		break;
707 	case LUA_TTABLE:
708 		lua_pushnil(L);
709 		while (lua_next(L, 2) != 0) {
710 			int entry_idx = 0;
711 
712 			if (filter_count >= STKTABLE_FILTER_LEN)
713 				return hlua_error(L, "Filter table too large (len > %d)", STKTABLE_FILTER_LEN);
714 
715 			if (lua_type(L, -1) != LUA_TTABLE  || lua_rawlen(L, -1) != 3)
716 				return hlua_error(L, "Filter table entry must be a triplet: {\"data_col\", \"op\", val} (entry #%d)", filter_count + 1);
717 
718 			lua_pushnil(L);
719 			while (lua_next(L, -2) != 0) {
720 				switch (entry_idx) {
721 				case 0:
722 					if (lua_type(L, -1) != LUA_TSTRING)
723 						return hlua_error(L, "Filter table data column must be string (entry #%d)", filter_count + 1);
724 
725 					dt = stktable_get_data_type((char *)lua_tostring(L, -1));
726 					if (dt < 0 || t->data_ofs[dt] == 0)
727 						return hlua_error(L, "Filter table data column not present in stick table (entry #%d)", filter_count + 1);
728 					filter[filter_count].type = dt;
729 					break;
730 				case 1:
731 					if (lua_type(L, -1) != LUA_TSTRING)
732 						return hlua_error(L, "Filter table operator must be string (entry #%d)", filter_count + 1);
733 
734 					op = get_std_op(lua_tostring(L, -1));
735 					if (op < 0)
736 						return hlua_error(L, "Unknown operator in filter table (entry #%d)", filter_count + 1);
737 					filter[filter_count].op = op;
738 					break;
739 				case 2:
740 					val = lua_tointeger(L, -1);
741 					filter[filter_count].val = val;
742 					filter_count++;
743 					break;
744 				default:
745 					break;
746 				}
747 				entry_idx++;
748 				lua_pop(L, 1);
749 			}
750 			lua_pop(L, 1);
751 		}
752 		break;
753 	default:
754 		return hlua_error(L, "filter table expected");
755 	}
756 
757 	lua_newtable(L);
758 
759 	HA_SPIN_LOCK(STK_TABLE_LOCK, &t->lock);
760 	eb = ebmb_first(&t->keys);
761 	for (n = eb; n; n = ebmb_next(n)) {
762 		ts = ebmb_entry(n, struct stksess, key);
763 		if (!ts) {
764 			HA_SPIN_UNLOCK(STK_TABLE_LOCK, &t->lock);
765 			return 1;
766 		}
767 		ts->ref_cnt++;
768 		HA_SPIN_UNLOCK(STK_TABLE_LOCK, &t->lock);
769 
770 		/* multi condition/value filter */
771 		skip_entry = 0;
772 		for (i = 0; i < filter_count; i++) {
773 			if (t->data_ofs[filter[i].type] == 0)
774 				continue;
775 
776 			ptr = stktable_data_ptr(t, ts, filter[i].type);
777 
778 			switch (stktable_data_types[filter[i].type].std_type) {
779 			case STD_T_SINT:
780 				val = stktable_data_cast(ptr, std_t_sint);
781 				break;
782 			case STD_T_UINT:
783 				val = stktable_data_cast(ptr, std_t_uint);
784 				break;
785 			case STD_T_ULL:
786 				val = stktable_data_cast(ptr, std_t_ull);
787 				break;
788 			case STD_T_FRQP:
789 				val = read_freq_ctr_period(&stktable_data_cast(ptr, std_t_frqp),
790 						           t->data_arg[filter[i].type].u);
791 				break;
792 			default:
793 				continue;
794 				break;
795 			}
796 
797 			op = filter[i].op;
798 
799 			if ((val < filter[i].val && (op == STD_OP_EQ || op == STD_OP_GT || op == STD_OP_GE)) ||
800 			    (val == filter[i].val && (op == STD_OP_NE || op == STD_OP_GT || op == STD_OP_LT)) ||
801 			    (val > filter[i].val && (op == STD_OP_EQ || op == STD_OP_LT || op == STD_OP_LE))) {
802 				skip_entry = 1;
803 				break;
804 			}
805 		}
806 
807 		if (skip_entry) {
808 			HA_SPIN_LOCK(STK_TABLE_LOCK, &t->lock);
809 			ts->ref_cnt--;
810 			continue;
811 		}
812 
813 		if (t->type == SMP_T_IPV4) {
814 			char addr[INET_ADDRSTRLEN];
815 			inet_ntop(AF_INET, (const void *)&ts->key.key, addr, sizeof(addr));
816 			lua_pushstring(L, addr);
817 		} else if (t->type == SMP_T_IPV6) {
818 			char addr[INET6_ADDRSTRLEN];
819 			inet_ntop(AF_INET6, (const void *)&ts->key.key, addr, sizeof(addr));
820 			lua_pushstring(L, addr);
821 		} else if (t->type == SMP_T_SINT) {
822 			lua_pushinteger(L, *ts->key.key);
823 		} else if (t->type == SMP_T_STR) {
824 			lua_pushstring(L, (const char *)ts->key.key);
825 		} else {
826 			return hlua_error(L, "Unsupported stick table key type");
827 		}
828 
829 		lua_newtable(L);
830 		hlua_stktable_entry(L, t, ts);
831 		lua_settable(L, -3);
832 		HA_SPIN_LOCK(STK_TABLE_LOCK, &t->lock);
833 		ts->ref_cnt--;
834 	}
835 	HA_SPIN_UNLOCK(STK_TABLE_LOCK, &t->lock);
836 
837 	return 1;
838 }
839 
hlua_fcn_new_listener(lua_State * L,struct listener * lst)840 int hlua_fcn_new_listener(lua_State *L, struct listener *lst)
841 {
842 	lua_newtable(L);
843 
844 	/* Pop a class sesison metatable and affect it to the userdata. */
845 	lua_rawgeti(L, LUA_REGISTRYINDEX, class_listener_ref);
846 	lua_setmetatable(L, -2);
847 
848 	lua_pushlightuserdata(L, lst);
849 	lua_rawseti(L, -2, 0);
850 	return 1;
851 }
852 
hlua_check_listener(lua_State * L,int ud)853 static struct listener *hlua_check_listener(lua_State *L, int ud)
854 {
855 	return hlua_checkudata(L, ud, class_listener_ref);
856 }
857 
hlua_listener_get_stats(lua_State * L)858 int hlua_listener_get_stats(lua_State *L)
859 {
860 	struct listener *li;
861 	int i;
862 
863 	li = hlua_check_listener(L, 1);
864 
865 	if (!li->bind_conf->frontend) {
866 		lua_pushnil(L);
867 		return 1;
868 	}
869 
870 	stats_fill_li_stats(li->bind_conf->frontend, li, STAT_SHLGNDS, stats, STATS_LEN);
871 
872 	lua_newtable(L);
873 	for (i=0; i<ST_F_TOTAL_FIELDS; i++) {
874 		lua_pushstring(L, stat_fields[i].name);
875 		hlua_fcn_pushfield(L, &stats[i]);
876 		lua_settable(L, -3);
877 	}
878 	return 1;
879 
880 }
881 
hlua_fcn_new_server(lua_State * L,struct server * srv)882 int hlua_fcn_new_server(lua_State *L, struct server *srv)
883 {
884 	char buffer[12];
885 
886 	lua_newtable(L);
887 
888 	/* Pop a class sesison metatable and affect it to the userdata. */
889 	lua_rawgeti(L, LUA_REGISTRYINDEX, class_server_ref);
890 	lua_setmetatable(L, -2);
891 
892 	lua_pushlightuserdata(L, srv);
893 	lua_rawseti(L, -2, 0);
894 
895 	/* Add server name. */
896 	lua_pushstring(L, "name");
897 	lua_pushstring(L, srv->id);
898 	lua_settable(L, -3);
899 
900 	/* Add server puid. */
901 	lua_pushstring(L, "puid");
902 	snprintf(buffer, sizeof(buffer), "%d", srv->puid);
903 	lua_pushstring(L, buffer);
904 	lua_settable(L, -3);
905 
906 	return 1;
907 }
908 
hlua_check_server(lua_State * L,int ud)909 static struct server *hlua_check_server(lua_State *L, int ud)
910 {
911 	return hlua_checkudata(L, ud, class_server_ref);
912 }
913 
hlua_server_get_stats(lua_State * L)914 int hlua_server_get_stats(lua_State *L)
915 {
916 	struct server *srv;
917 	int i;
918 
919 	srv = hlua_check_server(L, 1);
920 
921 	if (!srv->proxy) {
922 		lua_pushnil(L);
923 		return 1;
924 	}
925 
926 	stats_fill_sv_stats(srv->proxy, srv, STAT_SHLGNDS, stats, STATS_LEN);
927 
928 	lua_newtable(L);
929 	for (i=0; i<ST_F_TOTAL_FIELDS; i++) {
930 		lua_pushstring(L, stat_fields[i].name);
931 		hlua_fcn_pushfield(L, &stats[i]);
932 		lua_settable(L, -3);
933 	}
934 	return 1;
935 
936 }
937 
hlua_server_get_addr(lua_State * L)938 int hlua_server_get_addr(lua_State *L)
939 {
940 	struct server *srv;
941 	char addr[INET6_ADDRSTRLEN];
942 	luaL_Buffer b;
943 
944 	srv = hlua_check_server(L, 1);
945 
946 	luaL_buffinit(L, &b);
947 
948 	switch (srv->addr.ss_family) {
949 	case AF_INET:
950 		inet_ntop(AF_INET, &((struct sockaddr_in *)&srv->addr)->sin_addr,
951 		          addr, INET_ADDRSTRLEN);
952 		luaL_addstring(&b, addr);
953 		luaL_addstring(&b, ":");
954 		snprintf(addr, INET_ADDRSTRLEN, "%d", srv->svc_port);
955 		luaL_addstring(&b, addr);
956 		break;
957 	case AF_INET6:
958 		inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&srv->addr)->sin6_addr,
959 		          addr, INET6_ADDRSTRLEN);
960 		luaL_addstring(&b, addr);
961 		luaL_addstring(&b, ":");
962 		snprintf(addr, INET_ADDRSTRLEN, "%d", srv->svc_port);
963 		luaL_addstring(&b, addr);
964 		break;
965 	case AF_UNIX:
966 		luaL_addstring(&b, (char *)((struct sockaddr_un *)&srv->addr)->sun_path);
967 		break;
968 	default:
969 		luaL_addstring(&b, "<unknown>");
970 		break;
971 	}
972 
973 	luaL_pushresult(&b);
974 	return 1;
975 }
976 
hlua_server_is_draining(lua_State * L)977 int hlua_server_is_draining(lua_State *L)
978 {
979 	struct server *srv;
980 
981 	srv = hlua_check_server(L, 1);
982 	lua_pushinteger(L, server_is_draining(srv));
983 	return 1;
984 }
985 
hlua_server_set_maxconn(lua_State * L)986 int hlua_server_set_maxconn(lua_State *L)
987 {
988 	struct server *srv;
989 	const char *maxconn;
990 	const char *err;
991 
992 	srv = hlua_check_server(L, 1);
993 	maxconn = luaL_checkstring(L, 2);
994 
995 	HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
996 	err = server_parse_maxconn_change_request(srv, maxconn);
997 	HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
998 	if (!err)
999 		lua_pushnil(L);
1000 	else
1001 		hlua_pushstrippedstring(L, err);
1002 	return 1;
1003 }
1004 
hlua_server_get_maxconn(lua_State * L)1005 int hlua_server_get_maxconn(lua_State *L)
1006 {
1007 	struct server *srv;
1008 
1009 	srv = hlua_check_server(L, 1);
1010 	lua_pushinteger(L, srv->maxconn);
1011 	return 1;
1012 }
1013 
hlua_server_set_weight(lua_State * L)1014 int hlua_server_set_weight(lua_State *L)
1015 {
1016 	struct server *srv;
1017 	const char *weight;
1018 	const char *err;
1019 
1020 	srv = hlua_check_server(L, 1);
1021 	weight = luaL_checkstring(L, 2);
1022 
1023 	HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1024 	err = server_parse_weight_change_request(srv, weight);
1025 	HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1026 	if (!err)
1027 		lua_pushnil(L);
1028 	else
1029 		hlua_pushstrippedstring(L, err);
1030 	return 1;
1031 }
1032 
hlua_server_get_weight(lua_State * L)1033 int hlua_server_get_weight(lua_State *L)
1034 {
1035 	struct server *srv;
1036 
1037 	srv = hlua_check_server(L, 1);
1038 	lua_pushinteger(L, srv->uweight);
1039 	return 1;
1040 }
1041 
hlua_server_set_addr(lua_State * L)1042 int hlua_server_set_addr(lua_State *L)
1043 {
1044 	struct server *srv;
1045 	const char *addr;
1046 	const char *port;
1047 	const char *err;
1048 
1049 	srv = hlua_check_server(L, 1);
1050 	addr = luaL_checkstring(L, 2);
1051 	if (lua_gettop(L) >= 3)
1052 		port = luaL_checkstring(L, 3);
1053 	else
1054 		port = NULL;
1055 
1056 	HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1057 	err = update_server_addr_port(srv, addr, port, "Lua script");
1058 	HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1059 	if (!err)
1060 		lua_pushnil(L);
1061 	else
1062 		hlua_pushstrippedstring(L, err);
1063 	return 1;
1064 }
1065 
hlua_server_shut_sess(lua_State * L)1066 int hlua_server_shut_sess(lua_State *L)
1067 {
1068 	struct server *srv;
1069 
1070 	srv = hlua_check_server(L, 1);
1071 	HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1072 	srv_shutdown_streams(srv, SF_ERR_KILLED);
1073 	HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1074 	return 0;
1075 }
1076 
hlua_server_set_drain(lua_State * L)1077 int hlua_server_set_drain(lua_State *L)
1078 {
1079 	struct server *srv;
1080 
1081 	srv = hlua_check_server(L, 1);
1082 	HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1083 	srv_adm_set_drain(srv);
1084 	HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1085 	return 0;
1086 }
1087 
hlua_server_set_maint(lua_State * L)1088 int hlua_server_set_maint(lua_State *L)
1089 {
1090 	struct server *srv;
1091 
1092 	srv = hlua_check_server(L, 1);
1093 	HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1094 	srv_adm_set_maint(srv);
1095 	HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1096 	return 0;
1097 }
1098 
hlua_server_set_ready(lua_State * L)1099 int hlua_server_set_ready(lua_State *L)
1100 {
1101 	struct server *srv;
1102 
1103 	srv = hlua_check_server(L, 1);
1104 	HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1105 	srv_adm_set_ready(srv);
1106 	HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1107 	return 0;
1108 }
1109 
hlua_server_check_enable(lua_State * L)1110 int hlua_server_check_enable(lua_State *L)
1111 {
1112 	struct server *sv;
1113 
1114 	sv = hlua_check_server(L, 1);
1115 	HA_SPIN_LOCK(SERVER_LOCK, &sv->lock);
1116 	if (sv->check.state & CHK_ST_CONFIGURED) {
1117 		sv->check.state |= CHK_ST_ENABLED;
1118 	}
1119 	HA_SPIN_UNLOCK(SERVER_LOCK, &sv->lock);
1120 	return 0;
1121 }
1122 
hlua_server_check_disable(lua_State * L)1123 int hlua_server_check_disable(lua_State *L)
1124 {
1125 	struct server *sv;
1126 
1127 	sv = hlua_check_server(L, 1);
1128 	HA_SPIN_LOCK(SERVER_LOCK, &sv->lock);
1129 	if (sv->check.state & CHK_ST_CONFIGURED) {
1130 		sv->check.state &= ~CHK_ST_ENABLED;
1131 	}
1132 	HA_SPIN_UNLOCK(SERVER_LOCK, &sv->lock);
1133 	return 0;
1134 }
1135 
hlua_server_check_force_up(lua_State * L)1136 int hlua_server_check_force_up(lua_State *L)
1137 {
1138 	struct server *sv;
1139 
1140 	sv = hlua_check_server(L, 1);
1141 	HA_SPIN_LOCK(SERVER_LOCK, &sv->lock);
1142 	if (!(sv->track)) {
1143 		sv->check.health = sv->check.rise + sv->check.fall - 1;
1144 		srv_set_running(sv, "changed from Lua script", NULL);
1145 	}
1146 	HA_SPIN_UNLOCK(SERVER_LOCK, &sv->lock);
1147 	return 0;
1148 }
1149 
hlua_server_check_force_nolb(lua_State * L)1150 int hlua_server_check_force_nolb(lua_State *L)
1151 {
1152 	struct server *sv;
1153 
1154 	sv = hlua_check_server(L, 1);
1155 	HA_SPIN_LOCK(SERVER_LOCK, &sv->lock);
1156 	if (!(sv->track)) {
1157 		sv->check.health = sv->check.rise + sv->check.fall - 1;
1158 		srv_set_stopping(sv, "changed from Lua script", NULL);
1159 	}
1160 	HA_SPIN_UNLOCK(SERVER_LOCK, &sv->lock);
1161 	return 0;
1162 }
1163 
hlua_server_check_force_down(lua_State * L)1164 int hlua_server_check_force_down(lua_State *L)
1165 {
1166 	struct server *sv;
1167 
1168 	sv = hlua_check_server(L, 1);
1169 	HA_SPIN_LOCK(SERVER_LOCK, &sv->lock);
1170 	if (!(sv->track)) {
1171 		sv->check.health = 0;
1172 		srv_set_stopped(sv, "changed from Lua script", NULL);
1173 	}
1174 	HA_SPIN_UNLOCK(SERVER_LOCK, &sv->lock);
1175 	return 0;
1176 }
1177 
hlua_server_agent_enable(lua_State * L)1178 int hlua_server_agent_enable(lua_State *L)
1179 {
1180 	struct server *sv;
1181 
1182 	sv = hlua_check_server(L, 1);
1183 	HA_SPIN_LOCK(SERVER_LOCK, &sv->lock);
1184 	if (sv->agent.state & CHK_ST_CONFIGURED) {
1185 		sv->agent.state |= CHK_ST_ENABLED;
1186 	}
1187 	HA_SPIN_UNLOCK(SERVER_LOCK, &sv->lock);
1188 	return 0;
1189 }
1190 
hlua_server_agent_disable(lua_State * L)1191 int hlua_server_agent_disable(lua_State *L)
1192 {
1193 	struct server *sv;
1194 
1195 	sv = hlua_check_server(L, 1);
1196 	HA_SPIN_LOCK(SERVER_LOCK, &sv->lock);
1197 	if (sv->agent.state & CHK_ST_CONFIGURED) {
1198 		sv->agent.state &= ~CHK_ST_ENABLED;
1199 	}
1200 	HA_SPIN_UNLOCK(SERVER_LOCK, &sv->lock);
1201 	return 0;
1202 }
1203 
hlua_server_agent_force_up(lua_State * L)1204 int hlua_server_agent_force_up(lua_State *L)
1205 {
1206 	struct server *sv;
1207 
1208 	sv = hlua_check_server(L, 1);
1209 	HA_SPIN_LOCK(SERVER_LOCK, &sv->lock);
1210 	if (sv->agent.state & CHK_ST_ENABLED) {
1211 		sv->agent.health = sv->agent.rise + sv->agent.fall - 1;
1212 		srv_set_running(sv, "changed from Lua script", NULL);
1213 	}
1214 	HA_SPIN_UNLOCK(SERVER_LOCK, &sv->lock);
1215 	return 0;
1216 }
1217 
hlua_server_agent_force_down(lua_State * L)1218 int hlua_server_agent_force_down(lua_State *L)
1219 {
1220 	struct server *sv;
1221 
1222 	sv = hlua_check_server(L, 1);
1223 	HA_SPIN_LOCK(SERVER_LOCK, &sv->lock);
1224 	if (sv->agent.state & CHK_ST_ENABLED) {
1225 		sv->agent.health = 0;
1226 		srv_set_stopped(sv, "changed from Lua script", NULL);
1227 	}
1228 	HA_SPIN_UNLOCK(SERVER_LOCK, &sv->lock);
1229 	return 0;
1230 }
1231 
hlua_fcn_new_proxy(lua_State * L,struct proxy * px)1232 int hlua_fcn_new_proxy(lua_State *L, struct proxy *px)
1233 {
1234 	struct server *srv;
1235 	struct listener *lst;
1236 	int lid;
1237 	char buffer[17];
1238 
1239 	lua_newtable(L);
1240 
1241 	/* Pop a class sesison metatable and affect it to the userdata. */
1242 	lua_rawgeti(L, LUA_REGISTRYINDEX, class_proxy_ref);
1243 	lua_setmetatable(L, -2);
1244 
1245 	lua_pushlightuserdata(L, px);
1246 	lua_rawseti(L, -2, 0);
1247 
1248 	/* Add proxy name. */
1249 	lua_pushstring(L, "name");
1250 	lua_pushstring(L, px->id);
1251 	lua_settable(L, -3);
1252 
1253 	/* Add proxy uuid. */
1254 	lua_pushstring(L, "uuid");
1255 	snprintf(buffer, sizeof(buffer), "%d", px->uuid);
1256 	lua_pushstring(L, buffer);
1257 	lua_settable(L, -3);
1258 
1259 	/* Browse and register servers. */
1260 	lua_pushstring(L, "servers");
1261 	lua_newtable(L);
1262 	for (srv = px->srv; srv; srv = srv->next) {
1263 		lua_pushstring(L, srv->id);
1264 		hlua_fcn_new_server(L, srv);
1265 		lua_settable(L, -3);
1266 	}
1267 	lua_settable(L, -3);
1268 
1269 	/* Browse and register listeners. */
1270 	lua_pushstring(L, "listeners");
1271 	lua_newtable(L);
1272 	lid = 1;
1273 	list_for_each_entry(lst, &px->conf.listeners, by_fe) {
1274 		if (lst->name)
1275 			lua_pushstring(L, lst->name);
1276 		else {
1277 			snprintf(buffer, sizeof(buffer), "sock-%d", lid);
1278 			lid++;
1279 			lua_pushstring(L, buffer);
1280 		}
1281 		hlua_fcn_new_listener(L, lst);
1282 		lua_settable(L, -3);
1283 	}
1284 	lua_settable(L, -3);
1285 
1286 	if (px->table && px->table->id) {
1287 		lua_pushstring(L, "stktable");
1288 		hlua_fcn_new_stktable(L, px->table);
1289 		lua_settable(L, -3);
1290 	}
1291 
1292 	return 1;
1293 }
1294 
hlua_check_proxy(lua_State * L,int ud)1295 static struct proxy *hlua_check_proxy(lua_State *L, int ud)
1296 {
1297 	return hlua_checkudata(L, ud, class_proxy_ref);
1298 }
1299 
hlua_proxy_pause(lua_State * L)1300 int hlua_proxy_pause(lua_State *L)
1301 {
1302 	struct proxy *px;
1303 
1304 	px = hlua_check_proxy(L, 1);
1305 	pause_proxy(px);
1306 	return 0;
1307 }
1308 
hlua_proxy_resume(lua_State * L)1309 int hlua_proxy_resume(lua_State *L)
1310 {
1311 	struct proxy *px;
1312 
1313 	px = hlua_check_proxy(L, 1);
1314 	resume_proxy(px);
1315 	return 0;
1316 }
1317 
hlua_proxy_stop(lua_State * L)1318 int hlua_proxy_stop(lua_State *L)
1319 {
1320 	struct proxy *px;
1321 
1322 	px = hlua_check_proxy(L, 1);
1323 	stop_proxy(px);
1324 	return 0;
1325 }
1326 
hlua_proxy_get_cap(lua_State * L)1327 int hlua_proxy_get_cap(lua_State *L)
1328 {
1329 	struct proxy *px;
1330 	const char *str;
1331 
1332 	px = hlua_check_proxy(L, 1);
1333 	str = proxy_cap_str(px->cap);
1334 	lua_pushstring(L, str);
1335 	return 1;
1336 }
1337 
hlua_proxy_get_stats(lua_State * L)1338 int hlua_proxy_get_stats(lua_State *L)
1339 {
1340 	struct proxy *px;
1341 	int i;
1342 
1343 	px = hlua_check_proxy(L, 1);
1344 	if (px->cap & PR_CAP_BE)
1345 		stats_fill_be_stats(px, STAT_SHLGNDS, stats, STATS_LEN);
1346 	else
1347 		stats_fill_fe_stats(px, stats, STATS_LEN);
1348 	lua_newtable(L);
1349 	for (i=0; i<ST_F_TOTAL_FIELDS; i++) {
1350 		lua_pushstring(L, stat_fields[i].name);
1351 		hlua_fcn_pushfield(L, &stats[i]);
1352 		lua_settable(L, -3);
1353 	}
1354 	return 1;
1355 }
1356 
hlua_proxy_get_mode(lua_State * L)1357 int hlua_proxy_get_mode(lua_State *L)
1358 {
1359 	struct proxy *px;
1360 	const char *str;
1361 
1362 	px = hlua_check_proxy(L, 1);
1363 	str = proxy_mode_str(px->mode);
1364 	lua_pushstring(L, str);
1365 	return 1;
1366 }
1367 
hlua_proxy_shut_bcksess(lua_State * L)1368 int hlua_proxy_shut_bcksess(lua_State *L)
1369 {
1370 	struct proxy *px;
1371 
1372 	px = hlua_check_proxy(L, 1);
1373 	srv_shutdown_backup_streams(px, SF_ERR_KILLED);
1374 	return 0;
1375 }
1376 
hlua_fcn_post_init(lua_State * L)1377 int hlua_fcn_post_init(lua_State *L)
1378 {
1379 	struct proxy *px;
1380 
1381 	/* get core array. */
1382 	if (lua_getglobal(L, "core") != LUA_TTABLE)
1383 		lua_error(L);
1384 
1385 	/* Create proxies entry. */
1386 	lua_pushstring(L, "proxies");
1387 	lua_newtable(L);
1388 
1389 	/* List all proxies. */
1390 	for (px = proxies_list; px; px = px->next) {
1391 		lua_pushstring(L, px->id);
1392 		hlua_fcn_new_proxy(L, px);
1393 		lua_settable(L, -3);
1394 	}
1395 
1396 	/* push "proxies" in "core" */
1397 	lua_settable(L, -3);
1398 
1399 	/* Create proxies entry. */
1400 	lua_pushstring(L, "frontends");
1401 	lua_newtable(L);
1402 
1403 	/* List all proxies. */
1404 	for (px = proxies_list; px; px = px->next) {
1405 		if (!(px->cap & PR_CAP_FE))
1406 			continue;
1407 		lua_pushstring(L, px->id);
1408 		hlua_fcn_new_proxy(L, px);
1409 		lua_settable(L, -3);
1410 	}
1411 
1412 	/* push "frontends" in "core" */
1413 	lua_settable(L, -3);
1414 
1415 	/* Create proxies entry. */
1416 	lua_pushstring(L, "backends");
1417 	lua_newtable(L);
1418 
1419 	/* List all proxies. */
1420 	for (px = proxies_list; px; px = px->next) {
1421 		if (!(px->cap & PR_CAP_BE))
1422 			continue;
1423 		lua_pushstring(L, px->id);
1424 		hlua_fcn_new_proxy(L, px);
1425 		lua_settable(L, -3);
1426 	}
1427 
1428 	/* push "backend" in "core" */
1429 	lua_settable(L, -3);
1430 
1431 	return 1;
1432 }
1433 
1434 /* This Lua function take a string, a list of separators.
1435  * It tokenize the input string using the list of separators
1436  * as separator.
1437  *
1438  * The functionreturns a table filled with tokens.
1439  */
hlua_tokenize(lua_State * L)1440 int hlua_tokenize(lua_State *L)
1441 {
1442 	const char *str;
1443 	const char *sep;
1444 	int index;
1445 	const char *token;
1446 	const char *p;
1447 	const char *c;
1448 	int ignore_empty;
1449 
1450 	ignore_empty = 0;
1451 
1452 	str = luaL_checkstring(L, 1);
1453 	sep = luaL_checkstring(L, 2);
1454 	if (lua_gettop(L) == 3)
1455 		ignore_empty = hlua_checkboolean(L, 3);
1456 
1457 	lua_newtable(L);
1458 	index = 1;
1459 	token = str;
1460 	p = str;
1461 	while(1) {
1462 		for (c = sep; *c != '\0'; c++)
1463 			if (*p == *c)
1464 				break;
1465 		if (*p == *c) {
1466 			if ((!ignore_empty) || (p - token > 0)) {
1467 				lua_pushlstring(L, token, p - token);
1468 				lua_rawseti(L, -2, index);
1469 				index++;
1470 			}
1471 			token = p + 1;
1472 		}
1473 		if (*p == '\0')
1474 			break;
1475 		p++;
1476 	}
1477 
1478 	return 1;
1479 }
1480 
hlua_parse_addr(lua_State * L)1481 int hlua_parse_addr(lua_State *L)
1482 {
1483 	struct hlua_addr *addr;
1484 	const char *str = luaL_checkstring(L, 1);
1485 	unsigned char mask;
1486 
1487 	addr = lua_newuserdata(L, sizeof(struct hlua_addr));
1488 	if (!addr) {
1489 		lua_pushnil(L);
1490 		return 1;
1491 	}
1492 
1493 	if (str2net(str, PAT_MF_NO_DNS, &addr->addr.v4.ip, &addr->addr.v4.mask)) {
1494 		addr->type = AF_INET;
1495 		return 1;
1496 	}
1497 
1498 	if (str62net(str, &addr->addr.v6.ip, &mask)) {
1499 		len2mask6(mask, &addr->addr.v6.mask);
1500 		addr->type = AF_INET6;
1501 		return 1;
1502 	}
1503 
1504 	lua_pop(L, 1);
1505 	lua_pushnil(L);
1506 	return 1;
1507 }
1508 
hlua_match_addr(lua_State * L)1509 int hlua_match_addr(lua_State *L)
1510 {
1511 	struct hlua_addr *addr1;
1512 	struct hlua_addr *addr2;
1513 
1514 	if (!lua_isuserdata(L, 1) ||
1515 	    !lua_isuserdata(L, 2)) {
1516 		lua_pushboolean(L, 0);
1517 		return 1;
1518 	}
1519 
1520 	addr1 = lua_touserdata(L, 1);
1521 	addr2 = lua_touserdata(L, 2);
1522 
1523 	if (addr1->type != addr2->type) {
1524 		lua_pushboolean(L, 0);
1525 		return 1;
1526 	}
1527 
1528 	if (addr1->type == AF_INET) {
1529 		if ((addr1->addr.v4.ip.s_addr & addr2->addr.v4.mask.s_addr) ==
1530 		    (addr2->addr.v4.ip.s_addr & addr1->addr.v4.mask.s_addr)) {
1531 			lua_pushboolean(L, 1);
1532 			return 1;
1533 		}
1534 	} else {
1535 		int i;
1536 
1537 		for (i = 0; i < 16; i += 4) {
1538 			if ((read_u32(&addr1->addr.v6.ip.s6_addr[i]) &
1539 			     read_u32(&addr2->addr.v6.mask.s6_addr[i])) !=
1540 			    (read_u32(&addr2->addr.v6.ip.s6_addr[i]) &
1541 			     read_u32(&addr1->addr.v6.mask.s6_addr[i])))
1542 				break;
1543 		}
1544 		if (i == 16) {
1545 			lua_pushboolean(L, 1);
1546 			return 1;
1547 		}
1548 	}
1549 
1550 	lua_pushboolean(L, 0);
1551 	return 1;
1552 }
1553 
hlua_check_regex(lua_State * L,int ud)1554 static struct my_regex **hlua_check_regex(lua_State *L, int ud)
1555 {
1556 	return (hlua_checkudata(L, ud, class_regex_ref));
1557 }
1558 
hlua_regex_comp(struct lua_State * L)1559 static int hlua_regex_comp(struct lua_State *L)
1560 {
1561 	struct my_regex **regex;
1562 	const char *str;
1563 	int cs;
1564 	char *err;
1565 
1566 	str = luaL_checkstring(L, 1);
1567 	luaL_argcheck(L, lua_isboolean(L, 2), 2, NULL);
1568 	cs = lua_toboolean(L, 2);
1569 
1570 	regex = lua_newuserdata(L, sizeof(*regex));
1571 
1572 	err = NULL;
1573 	if (!(*regex = regex_comp(str, cs, 1, &err))) {
1574 		lua_pushboolean(L, 0); /* status error */
1575 		lua_pushstring(L, err); /* Reason */
1576 		free(err);
1577 		return 2;
1578 	}
1579 
1580 	lua_pushboolean(L, 1); /* Status ok */
1581 
1582 	/* Create object */
1583 	lua_newtable(L);
1584 	lua_pushvalue(L, -3); /* Get the userdata pointer. */
1585 	lua_rawseti(L, -2, 0);
1586 	lua_rawgeti(L, LUA_REGISTRYINDEX, class_regex_ref);
1587 	lua_setmetatable(L, -2);
1588 	return 2;
1589 }
1590 
hlua_regex_exec(struct lua_State * L)1591 static int hlua_regex_exec(struct lua_State *L)
1592 {
1593 	struct my_regex **regex;
1594 	const char *str;
1595 	size_t len;
1596 	struct buffer *tmp;
1597 
1598 	regex = hlua_check_regex(L, 1);
1599 	str = luaL_checklstring(L, 2, &len);
1600 
1601 	if (!*regex) {
1602 		lua_pushboolean(L, 0);
1603 		return 1;
1604 	}
1605 
1606 	/* Copy the string because regex_exec2 require a 'char *'
1607 	 * and not a 'const char *'.
1608 	 */
1609 	tmp = get_trash_chunk();
1610 	if (len >= tmp->size) {
1611 		lua_pushboolean(L, 0);
1612 		return 1;
1613 	}
1614 	memcpy(tmp->area, str, len);
1615 
1616 	lua_pushboolean(L, regex_exec2(*regex, tmp->area, len));
1617 
1618 	return 1;
1619 }
1620 
hlua_regex_match(struct lua_State * L)1621 static int hlua_regex_match(struct lua_State *L)
1622 {
1623 	struct my_regex **regex;
1624 	const char *str;
1625 	size_t len;
1626 	regmatch_t pmatch[20];
1627 	int ret;
1628 	int i;
1629 	struct buffer *tmp;
1630 
1631 	regex = hlua_check_regex(L, 1);
1632 	str = luaL_checklstring(L, 2, &len);
1633 
1634 	if (!*regex) {
1635 		lua_pushboolean(L, 0);
1636 		return 1;
1637 	}
1638 
1639 	/* Copy the string because regex_exec2 require a 'char *'
1640 	 * and not a 'const char *'.
1641 	 */
1642 	tmp = get_trash_chunk();
1643 	if (len >= tmp->size) {
1644 		lua_pushboolean(L, 0);
1645 		return 1;
1646 	}
1647 	memcpy(tmp->area, str, len);
1648 
1649 	ret = regex_exec_match2(*regex, tmp->area, len, 20, pmatch, 0);
1650 	lua_pushboolean(L, ret);
1651 	lua_newtable(L);
1652 	if (ret) {
1653 		for (i = 0; i < 20 && pmatch[i].rm_so != -1; i++) {
1654 			lua_pushlstring(L, str + pmatch[i].rm_so, pmatch[i].rm_eo - pmatch[i].rm_so);
1655 			lua_rawseti(L, -2, i + 1);
1656 		}
1657 	}
1658 	return 2;
1659 }
1660 
hlua_regex_free(struct lua_State * L)1661 static int hlua_regex_free(struct lua_State *L)
1662 {
1663 	struct my_regex **regex;
1664 
1665 	regex = hlua_check_regex(L, 1);
1666 	regex_free(*regex);
1667 	*regex = NULL;
1668 	return 0;
1669 }
1670 
hlua_fcn_reg_core_fcn(lua_State * L)1671 int hlua_fcn_reg_core_fcn(lua_State *L)
1672 {
1673 	if (!hlua_concat_init(L))
1674 		return 0;
1675 
1676 	hlua_class_function(L, "now", hlua_now);
1677 	hlua_class_function(L, "http_date", hlua_http_date);
1678 	hlua_class_function(L, "imf_date", hlua_imf_date);
1679 	hlua_class_function(L, "rfc850_date", hlua_rfc850_date);
1680 	hlua_class_function(L, "asctime_date", hlua_asctime_date);
1681 	hlua_class_function(L, "concat", hlua_concat_new);
1682 	hlua_class_function(L, "get_info", hlua_get_info);
1683 	hlua_class_function(L, "parse_addr", hlua_parse_addr);
1684 	hlua_class_function(L, "match_addr", hlua_match_addr);
1685 	hlua_class_function(L, "tokenize", hlua_tokenize);
1686 
1687 	/* Create regex object. */
1688 	lua_newtable(L);
1689 	hlua_class_function(L, "new", hlua_regex_comp);
1690 
1691 	lua_newtable(L); /* The metatable. */
1692 	lua_pushstring(L, "__index");
1693 	lua_newtable(L);
1694 	hlua_class_function(L, "exec", hlua_regex_exec);
1695 	hlua_class_function(L, "match", hlua_regex_match);
1696 	lua_rawset(L, -3); /* -> META["__index"] = TABLE */
1697 	hlua_class_function(L, "__gc", hlua_regex_free);
1698 
1699 	lua_pushvalue(L, -1); /* Duplicate the metatable reference. */
1700 	class_regex_ref = hlua_register_metatable(L, CLASS_REGEX);
1701 
1702 	lua_setmetatable(L, -2);
1703 	lua_setglobal(L, CLASS_REGEX); /* Create global object called Regex */
1704 
1705 	/* Create stktable object. */
1706 	lua_newtable(L);
1707 	lua_pushstring(L, "__index");
1708 	lua_newtable(L);
1709 	hlua_class_function(L, "info", hlua_stktable_info);
1710 	hlua_class_function(L, "lookup", hlua_stktable_lookup);
1711 	hlua_class_function(L, "dump", hlua_stktable_dump);
1712 	lua_settable(L, -3); /* -> META["__index"] = TABLE */
1713 	class_stktable_ref = hlua_register_metatable(L, CLASS_STKTABLE);
1714 
1715 	/* Create listener object. */
1716 	lua_newtable(L);
1717 	lua_pushstring(L, "__index");
1718 	lua_newtable(L);
1719 	hlua_class_function(L, "get_stats", hlua_listener_get_stats);
1720 	lua_settable(L, -3); /* -> META["__index"] = TABLE */
1721 	class_listener_ref = hlua_register_metatable(L, CLASS_LISTENER);
1722 
1723 	/* Create server object. */
1724 	lua_newtable(L);
1725 	lua_pushstring(L, "__index");
1726 	lua_newtable(L);
1727 	hlua_class_function(L, "is_draining", hlua_server_is_draining);
1728 	hlua_class_function(L, "set_maxconn", hlua_server_set_maxconn);
1729 	hlua_class_function(L, "get_maxconn", hlua_server_get_maxconn);
1730 	hlua_class_function(L, "set_weight", hlua_server_set_weight);
1731 	hlua_class_function(L, "get_weight", hlua_server_get_weight);
1732 	hlua_class_function(L, "set_addr", hlua_server_set_addr);
1733 	hlua_class_function(L, "get_addr", hlua_server_get_addr);
1734 	hlua_class_function(L, "get_stats", hlua_server_get_stats);
1735 	hlua_class_function(L, "shut_sess", hlua_server_shut_sess);
1736 	hlua_class_function(L, "set_drain", hlua_server_set_drain);
1737 	hlua_class_function(L, "set_maint", hlua_server_set_maint);
1738 	hlua_class_function(L, "set_ready", hlua_server_set_ready);
1739 	hlua_class_function(L, "check_enable", hlua_server_check_enable);
1740 	hlua_class_function(L, "check_disable", hlua_server_check_disable);
1741 	hlua_class_function(L, "check_force_up", hlua_server_check_force_up);
1742 	hlua_class_function(L, "check_force_nolb", hlua_server_check_force_nolb);
1743 	hlua_class_function(L, "check_force_down", hlua_server_check_force_down);
1744 	hlua_class_function(L, "agent_enable", hlua_server_agent_enable);
1745 	hlua_class_function(L, "agent_disable", hlua_server_agent_disable);
1746 	hlua_class_function(L, "agent_force_up", hlua_server_agent_force_up);
1747 	hlua_class_function(L, "agent_force_down", hlua_server_agent_force_down);
1748 	lua_settable(L, -3); /* -> META["__index"] = TABLE */
1749 	class_server_ref = hlua_register_metatable(L, CLASS_SERVER);
1750 
1751 	/* Create proxy object. */
1752 	lua_newtable(L);
1753 	lua_pushstring(L, "__index");
1754 	lua_newtable(L);
1755 	hlua_class_function(L, "pause", hlua_proxy_pause);
1756 	hlua_class_function(L, "resume", hlua_proxy_resume);
1757 	hlua_class_function(L, "stop", hlua_proxy_stop);
1758 	hlua_class_function(L, "shut_bcksess", hlua_proxy_shut_bcksess);
1759 	hlua_class_function(L, "get_cap", hlua_proxy_get_cap);
1760 	hlua_class_function(L, "get_mode", hlua_proxy_get_mode);
1761 	hlua_class_function(L, "get_stats", hlua_proxy_get_stats);
1762 	lua_settable(L, -3); /* -> META["__index"] = TABLE */
1763 	class_proxy_ref = hlua_register_metatable(L, CLASS_PROXY);
1764 
1765 	return 5;
1766 }
1767