xref: /netbsd-src/external/mit/lua/dist/src/loslib.c (revision e89934bbf778a6d6d6894877c4da59d0c7835b0f)
1 /*	$NetBSD: loslib.c,v 1.8 2016/09/08 21:19:44 salazar Exp $	*/
2 
3 /*
4 ** Id: loslib.c,v 1.64 2016/04/18 13:06:55 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 ** options are grouped by length; group of length 2 start with '||'.
31 ** ===================================================================
32 */
33 #if !defined(LUA_STRFTIMEOPTIONS)	/* { */
34 
35 /* options for ANSI C 89 */
36 #define L_STRFTIMEC89		"aAbBcdHIjmMpSUwWxXyYZ%"
37 
38 /* options for ISO C 99 and POSIX */
39 #define L_STRFTIMEC99 "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \
40 	"||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy"
41 
42 /* options for Windows */
43 #define L_STRFTIMEWIN "aAbBcdHIjmMpSUwWxXyYzZ%" \
44 	"||" "#c#x#d#H#I#j#m#M#S#U#w#W#y#Y"
45 
46 #if defined(LUA_USE_WINDOWS)
47 #define LUA_STRFTIMEOPTIONS	L_STRFTIMEWIN
48 #elif defined(LUA_USE_C89)
49 #define LUA_STRFTIMEOPTIONS	L_STRFTIMEC89
50 #else  /* C99 specification */
51 #define LUA_STRFTIMEOPTIONS	L_STRFTIMEC99
52 #endif
53 
54 #endif					/* } */
55 /* }================================================================== */
56 
57 
58 /*
59 ** {==================================================================
60 ** Configuration for time-related stuff
61 ** ===================================================================
62 */
63 
64 #if !defined(l_time_t)		/* { */
65 /*
66 ** type to represent time_t in Lua
67 */
68 #define l_timet			lua_Integer
69 #define l_pushtime(L,t)		lua_pushinteger(L,(lua_Integer)(t))
70 
71 static time_t l_checktime (lua_State *L, int arg) {
72   lua_Integer t = luaL_checkinteger(L, arg);
73   luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds");
74   return (time_t)t;
75 }
76 
77 #endif				/* } */
78 
79 
80 #if !defined(l_gmtime)		/* { */
81 /*
82 ** By default, Lua uses gmtime/localtime, except when POSIX is available,
83 ** where it uses gmtime_r/localtime_r
84 */
85 
86 #if defined(LUA_USE_POSIX)	/* { */
87 
88 #define l_gmtime(t,r)		gmtime_r(t,r)
89 #define l_localtime(t,r)	localtime_r(t,r)
90 
91 #else				/* }{ */
92 
93 /* ISO C definitions */
94 #define l_gmtime(t,r)		((void)(r)->tm_sec, gmtime(t))
95 #define l_localtime(t,r)  	((void)(r)->tm_sec, localtime(t))
96 
97 #endif				/* } */
98 
99 #endif				/* } */
100 
101 /* }================================================================== */
102 
103 
104 /*
105 ** {==================================================================
106 ** Configuration for 'tmpnam':
107 ** By default, Lua uses tmpnam except when POSIX is available, where
108 ** it uses mkstemp.
109 ** ===================================================================
110 */
111 #if !defined(lua_tmpnam)	/* { */
112 
113 #if defined(LUA_USE_POSIX)	/* { */
114 
115 #include <unistd.h>
116 
117 #define LUA_TMPNAMBUFSIZE	32
118 
119 #if !defined(LUA_TMPNAMTEMPLATE)
120 #define LUA_TMPNAMTEMPLATE	"/tmp/lua_XXXXXX"
121 #endif
122 
123 #define lua_tmpnam(b,e) { \
124         strcpy(b, LUA_TMPNAMTEMPLATE); \
125         e = mkstemp(b); \
126         if (e != -1) close(e); \
127         e = (e == -1); }
128 
129 #else				/* }{ */
130 
131 /* ISO C definitions */
132 #define LUA_TMPNAMBUFSIZE	L_tmpnam
133 #define lua_tmpnam(b,e)		{ e = (tmpnam(b) == NULL); }
134 
135 #endif				/* } */
136 
137 #endif				/* } */
138 /* }================================================================== */
139 
140 
141 
142 
143 static int os_execute (lua_State *L) {
144   const char *cmd = luaL_optstring(L, 1, NULL);
145   int stat = system(cmd);
146   if (cmd != NULL)
147     return luaL_execresult(L, stat);
148   else {
149     lua_pushboolean(L, stat);  /* true if there is a shell */
150     return 1;
151   }
152 }
153 
154 
155 static int os_remove (lua_State *L) {
156   const char *filename = luaL_checkstring(L, 1);
157   return luaL_fileresult(L, remove(filename) == 0, filename);
158 }
159 
160 
161 static int os_rename (lua_State *L) {
162   const char *fromname = luaL_checkstring(L, 1);
163   const char *toname = luaL_checkstring(L, 2);
164   return luaL_fileresult(L, rename(fromname, toname) == 0, NULL);
165 }
166 
167 
168 static int os_tmpname (lua_State *L) {
169   char buff[LUA_TMPNAMBUFSIZE];
170   int err;
171   lua_tmpnam(buff, err);
172   if (err)
173     return luaL_error(L, "unable to generate a unique filename");
174   lua_pushstring(L, buff);
175   return 1;
176 }
177 
178 
179 static int os_getenv (lua_State *L) {
180   lua_pushstring(L, getenv(luaL_checkstring(L, 1)));  /* if NULL push nil */
181   return 1;
182 }
183 
184 
185 static int os_clock (lua_State *L) {
186   lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
187   return 1;
188 }
189 
190 
191 /*
192 ** {======================================================
193 ** Time/Date operations
194 ** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
195 **   wday=%w+1, yday=%j, isdst=? }
196 ** =======================================================
197 */
198 
199 static void setfield (lua_State *L, const char *key, int value) {
200   lua_pushinteger(L, value);
201   lua_setfield(L, -2, key);
202 }
203 
204 static void setboolfield (lua_State *L, const char *key, int value) {
205   if (value < 0)  /* undefined? */
206     return;  /* does not set field */
207   lua_pushboolean(L, value);
208   lua_setfield(L, -2, key);
209 }
210 
211 
212 /*
213 ** Set all fields from structure 'tm' in the table on top of the stack
214 */
215 static void setallfields (lua_State *L, struct tm *stm) {
216   setfield(L, "sec", stm->tm_sec);
217   setfield(L, "min", stm->tm_min);
218   setfield(L, "hour", stm->tm_hour);
219   setfield(L, "day", stm->tm_mday);
220   setfield(L, "month", stm->tm_mon + 1);
221   setfield(L, "year", stm->tm_year + 1900);
222   setfield(L, "wday", stm->tm_wday + 1);
223   setfield(L, "yday", stm->tm_yday + 1);
224   setboolfield(L, "isdst", stm->tm_isdst);
225 }
226 
227 
228 static int getboolfield (lua_State *L, const char *key) {
229   int res;
230   res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);
231   lua_pop(L, 1);
232   return res;
233 }
234 
235 
236 /* maximum value for date fields (to avoid arithmetic overflows with 'int') */
237 #if !defined(L_MAXDATEFIELD)
238 #define L_MAXDATEFIELD	(INT_MAX / 2)
239 #endif
240 
241 static int getfield (lua_State *L, const char *key, int d, int delta) {
242   int isnum;
243   int t = lua_getfield(L, -1, key);  /* get field and its type */
244   lua_Integer res = lua_tointegerx(L, -1, &isnum);
245   if (!isnum) {  /* field is not an integer? */
246     if (t != LUA_TNIL)  /* some other value? */
247       return luaL_error(L, "field '%s' is not an integer", key);
248     else if (d < 0)  /* absent field; no default? */
249       return luaL_error(L, "field '%s' missing in date table", key);
250     res = d;
251   }
252   else {
253     if (!(-L_MAXDATEFIELD <= res && res <= L_MAXDATEFIELD))
254       return luaL_error(L, "field '%s' is out-of-bound", key);
255     res -= delta;
256   }
257   lua_pop(L, 1);
258   return (int)res;
259 }
260 
261 
262 static const char *checkoption (lua_State *L, const char *conv, char *buff) {
263   const char *option;
264   int oplen = 1;
265   int convlen = (int)strlen(conv);
266   for (option = LUA_STRFTIMEOPTIONS; *option != '\0' && oplen <= convlen; option += oplen) {
267     if (*option == '|')  /* next block? */
268       oplen++;  /* next length */
269     else if (memcmp(conv, option, oplen) == 0) {  /* match? */
270       memcpy(buff, conv, oplen);  /* copy valid option to buffer */
271       buff[oplen] = '\0';
272       return conv + oplen;  /* return next item */
273     }
274   }
275   luaL_argerror(L, 1,
276     lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv));
277   return conv;  /* to avoid warnings */
278 }
279 
280 
281 /* maximum size for an individual 'strftime' item */
282 #define SIZETIMEFMT	250
283 
284 
285 static int os_date (lua_State *L) {
286   const char *s = luaL_optstring(L, 1, "%c");
287   time_t t = luaL_opt(L, l_checktime, 2, time(NULL));
288   struct tm tmr, *stm;
289   if (*s == '!') {  /* UTC? */
290     stm = l_gmtime(&t, &tmr);
291     s++;  /* skip '!' */
292   }
293   else
294     stm = l_localtime(&t, &tmr);
295   if (stm == NULL)  /* invalid date? */
296     luaL_error(L, "time result cannot be represented in this installation");
297   if (strcmp(s, "*t") == 0) {
298     lua_createtable(L, 0, 9);  /* 9 = number of fields */
299     setallfields(L, stm);
300   }
301   else {
302     char cc[4];  /* buffer for individual conversion specifiers */
303     luaL_Buffer b;
304     cc[0] = '%';
305     luaL_buffinit(L, &b);
306     while (*s) {
307       if (*s != '%')  /* not a conversion specifier? */
308         luaL_addchar(&b, *s++);
309       else {
310         size_t reslen;
311         char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT);
312         s = checkoption(L, s + 1, cc + 1);  /* copy specifier to 'cc' */
313         reslen = strftime(buff, SIZETIMEFMT, cc, stm);
314         luaL_addsize(&b, reslen);
315       }
316     }
317     luaL_pushresult(&b);
318   }
319   return 1;
320 }
321 
322 
323 static int os_time (lua_State *L) {
324   time_t t;
325   if (lua_isnoneornil(L, 1))  /* called without args? */
326     t = time(NULL);  /* get current time */
327   else {
328     struct tm ts;
329     luaL_checktype(L, 1, LUA_TTABLE);
330     lua_settop(L, 1);  /* make sure table is at the top */
331     ts.tm_sec = getfield(L, "sec", 0, 0);
332     ts.tm_min = getfield(L, "min", 0, 0);
333     ts.tm_hour = getfield(L, "hour", 12, 0);
334     ts.tm_mday = getfield(L, "day", -1, 0);
335     ts.tm_mon = getfield(L, "month", -1, 1);
336     ts.tm_year = getfield(L, "year", -1, 1900);
337     ts.tm_isdst = getboolfield(L, "isdst");
338     t = mktime(&ts);
339     setallfields(L, &ts);  /* update fields with normalized values */
340   }
341   if (t != (time_t)(l_timet)t || t == (time_t)(-1))
342     luaL_error(L, "time result cannot be represented in this installation");
343   l_pushtime(L, t);
344   return 1;
345 }
346 
347 
348 static int os_difftime (lua_State *L) {
349   time_t t1 = l_checktime(L, 1);
350   time_t t2 = l_checktime(L, 2);
351   lua_pushnumber(L, (lua_Number)difftime(t1, t2));
352   return 1;
353 }
354 
355 /* }====================================================== */
356 
357 
358 static int os_setlocale (lua_State *L) {
359   static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
360                       LC_NUMERIC, LC_TIME};
361   static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
362      "numeric", "time", NULL};
363   const char *l = luaL_optstring(L, 1, NULL);
364   int op = luaL_checkoption(L, 2, "all", catnames);
365   lua_pushstring(L, setlocale(cat[op], l));
366   return 1;
367 }
368 
369 
370 static int os_exit (lua_State *L) {
371   int status;
372   if (lua_isboolean(L, 1))
373     status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);
374   else
375     status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);
376   if (lua_toboolean(L, 2))
377     lua_close(L);
378   if (L) exit(status);  /* 'if' to avoid warnings for unreachable 'return' */
379   return 0;
380 }
381 
382 
383 static const luaL_Reg syslib[] = {
384   {"clock",     os_clock},
385   {"date",      os_date},
386   {"difftime",  os_difftime},
387   {"execute",   os_execute},
388   {"exit",      os_exit},
389   {"getenv",    os_getenv},
390   {"remove",    os_remove},
391   {"rename",    os_rename},
392   {"setlocale", os_setlocale},
393   {"time",      os_time},
394   {"tmpname",   os_tmpname},
395   {NULL, NULL}
396 };
397 
398 /* }====================================================== */
399 
400 
401 
402 LUAMOD_API int luaopen_os (lua_State *L) {
403   luaL_newlib(L, syslib);
404   return 1;
405 }
406 
407