loslib.c revision 1.4
1/*	$NetBSD: loslib.c,v 1.4 2015/10/08 13:21:00 mbalmer Exp $	*/
2
3/*
4** Id: loslib.c,v 1.57 2015/04/10 17:41:04 roberto Exp
5** Standard Operating System library
6** See Copyright Notice in lua.h
7*/
8
9#define loslib_c
10#define LUA_LIB
11
12#include "lprefix.h"
13
14
15#include <errno.h>
16#include <locale.h>
17#include <stdlib.h>
18#include <string.h>
19#include <time.h>
20
21#include "lua.h"
22
23#include "lauxlib.h"
24#include "lualib.h"
25
26
27/*
28** {==================================================================
29** list of valid conversion specifiers for the 'strftime' function
30** ===================================================================
31*/
32#if !defined(LUA_STRFTIMEOPTIONS)	/* { */
33
34#if defined(LUA_USE_C89)
35#define LUA_STRFTIMEOPTIONS	{ "aAbBcdHIjmMpSUwWxXyYz%", "" }
36#else  /* C99 specification */
37#define LUA_STRFTIMEOPTIONS \
38	{ "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%", "", \
39	  "E", "cCxXyY",  \
40	  "O", "deHImMSuUVwWy" }
41#endif
42
43#endif					/* } */
44/* }================================================================== */
45
46
47/*
48** {==================================================================
49** Configuration for time-related stuff
50** ===================================================================
51*/
52
53#if !defined(l_time_t)		/* { */
54/*
55** type to represent time_t in Lua
56*/
57#define l_timet			lua_Integer
58#define l_pushtime(L,t)		lua_pushinteger(L,(lua_Integer)(t))
59#define l_checktime(L,a)	((time_t)luaL_checkinteger(L,a))
60
61#endif				/* } */
62
63
64#if !defined(l_gmtime)		/* { */
65/*
66** By default, Lua uses gmtime/localtime, except when POSIX is available,
67** where it uses gmtime_r/localtime_r
68*/
69
70#if defined(LUA_USE_POSIX)	/* { */
71
72#define l_gmtime(t,r)		gmtime_r(t,r)
73#define l_localtime(t,r)	localtime_r(t,r)
74
75#else				/* }{ */
76
77/* ISO C definitions */
78#define l_gmtime(t,r)		((void)(r)->tm_sec, gmtime(t))
79#define l_localtime(t,r)  	((void)(r)->tm_sec, localtime(t))
80
81#endif				/* } */
82
83#endif				/* } */
84
85/* }================================================================== */
86
87
88/*
89** {==================================================================
90** Configuration for 'tmpnam':
91** By default, Lua uses tmpnam except when POSIX is available, where
92** it uses mkstemp.
93** ===================================================================
94*/
95#if !defined(lua_tmpnam)	/* { */
96
97#if defined(LUA_USE_POSIX)	/* { */
98
99#include <unistd.h>
100
101#define LUA_TMPNAMBUFSIZE	32
102
103#if !defined(LUA_TMPNAMTEMPLATE)
104#define LUA_TMPNAMTEMPLATE	"/tmp/lua_XXXXXX"
105#endif
106
107#define lua_tmpnam(b,e) { \
108        strcpy(b, LUA_TMPNAMTEMPLATE); \
109        e = mkstemp(b); \
110        if (e != -1) close(e); \
111        e = (e == -1); }
112
113#else				/* }{ */
114
115/* ISO C definitions */
116#define LUA_TMPNAMBUFSIZE	L_tmpnam
117#define lua_tmpnam(b,e)		{ e = (tmpnam(b) == NULL); }
118
119#endif				/* } */
120
121#endif				/* } */
122/* }================================================================== */
123
124
125
126
127static int os_execute (lua_State *L) {
128  const char *cmd = luaL_optstring(L, 1, NULL);
129  int stat = system(cmd);
130  if (cmd != NULL)
131    return luaL_execresult(L, stat);
132  else {
133    lua_pushboolean(L, stat);  /* true if there is a shell */
134    return 1;
135  }
136}
137
138
139static int os_remove (lua_State *L) {
140  const char *filename = luaL_checkstring(L, 1);
141  return luaL_fileresult(L, remove(filename) == 0, filename);
142}
143
144
145static int os_rename (lua_State *L) {
146  const char *fromname = luaL_checkstring(L, 1);
147  const char *toname = luaL_checkstring(L, 2);
148  return luaL_fileresult(L, rename(fromname, toname) == 0, NULL);
149}
150
151
152static int os_tmpname (lua_State *L) {
153  char buff[LUA_TMPNAMBUFSIZE];
154  int err;
155  lua_tmpnam(buff, err);
156  if (err)
157    return luaL_error(L, "unable to generate a unique filename");
158  lua_pushstring(L, buff);
159  return 1;
160}
161
162
163static int os_getenv (lua_State *L) {
164  lua_pushstring(L, getenv(luaL_checkstring(L, 1)));  /* if NULL push nil */
165  return 1;
166}
167
168
169static int os_clock (lua_State *L) {
170  lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
171  return 1;
172}
173
174
175/*
176** {======================================================
177** Time/Date operations
178** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
179**   wday=%w+1, yday=%j, isdst=? }
180** =======================================================
181*/
182
183static void setfield (lua_State *L, const char *key, int value) {
184  lua_pushinteger(L, value);
185  lua_setfield(L, -2, key);
186}
187
188static void setboolfield (lua_State *L, const char *key, int value) {
189  if (value < 0)  /* undefined? */
190    return;  /* does not set field */
191  lua_pushboolean(L, value);
192  lua_setfield(L, -2, key);
193}
194
195static int getboolfield (lua_State *L, const char *key) {
196  int res;
197  res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);
198  lua_pop(L, 1);
199  return res;
200}
201
202
203static int getfield (lua_State *L, const char *key, int d) {
204  int res, isnum;
205  lua_getfield(L, -1, key);
206  res = (int)lua_tointegerx(L, -1, &isnum);
207  if (!isnum) {
208    if (d < 0)
209      return luaL_error(L, "field '%s' missing in date table", key);
210    res = d;
211  }
212  lua_pop(L, 1);
213  return res;
214}
215
216
217static const char *checkoption (lua_State *L, const char *conv, char *buff) {
218  static const char *const options[] = LUA_STRFTIMEOPTIONS;
219  unsigned int i;
220  for (i = 0; i < sizeof(options)/sizeof(options[0]); i += 2) {
221    if (*conv != '\0' && strchr(options[i], *conv) != NULL) {
222      buff[1] = *conv;
223      if (*options[i + 1] == '\0') {  /* one-char conversion specifier? */
224        buff[2] = '\0';  /* end buffer */
225        return conv + 1;
226      }
227      else if (*(conv + 1) != '\0' &&
228               strchr(options[i + 1], *(conv + 1)) != NULL) {
229        buff[2] = *(conv + 1);  /* valid two-char conversion specifier */
230        buff[3] = '\0';  /* end buffer */
231        return conv + 2;
232      }
233    }
234  }
235  luaL_argerror(L, 1,
236    lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv));
237  return conv;  /* to avoid warnings */
238}
239
240
241static int os_date (lua_State *L) {
242  const char *s = luaL_optstring(L, 1, "%c");
243  time_t t = luaL_opt(L, l_checktime, 2, time(NULL));
244  struct tm tmr, *stm;
245  if (*s == '!') {  /* UTC? */
246    stm = l_gmtime(&t, &tmr);
247    s++;  /* skip '!' */
248  }
249  else
250    stm = l_localtime(&t, &tmr);
251  if (stm == NULL)  /* invalid date? */
252    lua_pushnil(L);
253  else if (strcmp(s, "*t") == 0) {
254    lua_createtable(L, 0, 9);  /* 9 = number of fields */
255    setfield(L, "sec", stm->tm_sec);
256    setfield(L, "min", stm->tm_min);
257    setfield(L, "hour", stm->tm_hour);
258    setfield(L, "day", stm->tm_mday);
259    setfield(L, "month", stm->tm_mon+1);
260    setfield(L, "year", stm->tm_year+1900);
261    setfield(L, "wday", stm->tm_wday+1);
262    setfield(L, "yday", stm->tm_yday+1);
263    setboolfield(L, "isdst", stm->tm_isdst);
264  }
265  else {
266    char cc[4];
267    luaL_Buffer b;
268    cc[0] = '%';
269    luaL_buffinit(L, &b);
270    while (*s) {
271      if (*s != '%')  /* no conversion specifier? */
272        luaL_addchar(&b, *s++);
273      else {
274        size_t reslen;
275        char buff[200];  /* should be big enough for any conversion result */
276        s = checkoption(L, s + 1, cc);
277        reslen = strftime(buff, sizeof(buff), cc, stm);
278        luaL_addlstring(&b, buff, reslen);
279      }
280    }
281    luaL_pushresult(&b);
282  }
283  return 1;
284}
285
286
287static int os_time (lua_State *L) {
288  time_t t;
289  if (lua_isnoneornil(L, 1))  /* called without args? */
290    t = time(NULL);  /* get current time */
291  else {
292    struct tm ts;
293    luaL_checktype(L, 1, LUA_TTABLE);
294    lua_settop(L, 1);  /* make sure table is at the top */
295    ts.tm_sec = getfield(L, "sec", 0);
296    ts.tm_min = getfield(L, "min", 0);
297    ts.tm_hour = getfield(L, "hour", 12);
298    ts.tm_mday = getfield(L, "day", -1);
299    ts.tm_mon = getfield(L, "month", -1) - 1;
300    ts.tm_year = getfield(L, "year", -1) - 1900;
301    ts.tm_isdst = getboolfield(L, "isdst");
302    t = mktime(&ts);
303  }
304  if (t != (time_t)(l_timet)t)
305    luaL_error(L, "time result cannot be represented in this Lua installation");
306  else if (t == (time_t)(-1))
307    lua_pushnil(L);
308  else
309    l_pushtime(L, t);
310  return 1;
311}
312
313
314static int os_difftime (lua_State *L) {
315  time_t t1 = l_checktime(L, 1);
316  time_t t2 = l_checktime(L, 2);
317  lua_pushnumber(L, (lua_Number)difftime(t1, t2));
318  return 1;
319}
320
321/* }====================================================== */
322
323
324static int os_setlocale (lua_State *L) {
325  static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
326                      LC_NUMERIC, LC_TIME};
327  static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
328     "numeric", "time", NULL};
329  const char *l = luaL_optstring(L, 1, NULL);
330  int op = luaL_checkoption(L, 2, "all", catnames);
331  lua_pushstring(L, setlocale(cat[op], l));
332  return 1;
333}
334
335
336static int os_exit (lua_State *L) {
337  int status;
338  if (lua_isboolean(L, 1))
339    status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);
340  else
341    status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);
342  if (lua_toboolean(L, 2))
343    lua_close(L);
344  if (L) exit(status);  /* 'if' to avoid warnings for unreachable 'return' */
345  return 0;
346}
347
348
349static const luaL_Reg syslib[] = {
350  {"clock",     os_clock},
351  {"date",      os_date},
352  {"difftime",  os_difftime},
353  {"execute",   os_execute},
354  {"exit",      os_exit},
355  {"getenv",    os_getenv},
356  {"remove",    os_remove},
357  {"rename",    os_rename},
358  {"setlocale", os_setlocale},
359  {"time",      os_time},
360  {"tmpname",   os_tmpname},
361  {NULL, NULL}
362};
363
364/* }====================================================== */
365
366
367
368LUAMOD_API int luaopen_os (lua_State *L) {
369  luaL_newlib(L, syslib);
370  return 1;
371}
372
373