blob: a35ccfafe06e443ede5880db0e957e96fcb46f7b [file] [log] [blame]
Thierry Fournierfb0b5462016-01-21 09:28:58 +01001/* All the functions in this file runs with aLua stack, and can
2 * return with a longjmp. All of these function must be launched
3 * in an environment able to catch a longjmp, otherwise a
4 * critical error can be raised.
5 */
6#include <lauxlib.h>
7#include <lua.h>
8#include <lualib.h>
9
Thierry Fournierb1f46562016-01-21 09:46:15 +010010#include <common/time.h>
11
12/* This function return the current date at epoch format in milliseconds. */
13int hlua_now(lua_State *L)
14{
15 lua_newtable(L);
16 lua_pushstring(L, "sec");
17 lua_pushinteger(L, now.tv_sec);
18 lua_rawset(L, -3);
19 lua_pushstring(L, "usec");
20 lua_pushinteger(L, now.tv_usec);
21 lua_rawset(L, -3);
22 return 1;
23}
24
Thierry Fournier1550d5d2016-01-21 09:35:41 +010025/* This functions expects a Lua string as HTTP date, parse it and
26 * returns an integer containing the epoch format of the date, or
27 * nil if the parsing fails.
28 */
29static int hlua_parse_date(lua_State *L, int (*fcn)(const char *, int, struct tm*))
30{
31 const char *str;
32 size_t len;
33 struct tm tm;
34 time_t time;
35
36 str = luaL_checklstring(L, 1, &len);
37
38 if (!fcn(str, len, &tm)) {
39 lua_pushnil(L);
40 return 1;
41 }
42
43 /* This function considers the content of the broken-down time
44 * is exprimed in the UTC timezone. timegm don't care about
45 * the gnu variable tm_gmtoff. If gmtoff is set, or if you know
46 * the timezone from the broken-down time, it must be fixed
47 * after the conversion.
48 */
49 time = timegm(&tm);
50 if (time == -1) {
51 lua_pushnil(L);
52 return 1;
53 }
54
55 lua_pushinteger(L, (int)time);
56 return 1;
57}
58static int hlua_http_date(lua_State *L)
59{
60 return hlua_parse_date(L, parse_http_date);
61}
62static int hlua_imf_date(lua_State *L)
63{
64 return hlua_parse_date(L, parse_imf_date);
65}
66static int hlua_rfc850_date(lua_State *L)
67{
68 return hlua_parse_date(L, parse_rfc850_date);
69}
70static int hlua_asctime_date(lua_State *L)
71{
72 return hlua_parse_date(L, parse_asctime_date);
73}
74
Thierry Fournierfb0b5462016-01-21 09:28:58 +010075static void hlua_array_add_fcn(lua_State *L, const char *name,
76 int (*function)(lua_State *L))
77{
78 lua_pushstring(L, name);
79 lua_pushcclosure(L, function, 0);
80 lua_rawset(L, -3);
81}
82
83int hlua_fcn_reg_core_fcn(lua_State *L)
84{
Thierry Fournierb1f46562016-01-21 09:46:15 +010085 hlua_array_add_fcn(L, "now", hlua_now);
Thierry Fournier1550d5d2016-01-21 09:35:41 +010086 hlua_array_add_fcn(L, "http_date", hlua_http_date);
87 hlua_array_add_fcn(L, "imf_date", hlua_imf_date);
88 hlua_array_add_fcn(L, "rfc850_date", hlua_rfc850_date);
89 hlua_array_add_fcn(L, "asctime_date", hlua_asctime_date);
90 return 5;
Thierry Fournierfb0b5462016-01-21 09:28:58 +010091}