loslib.c revision 1.10
1/* $NetBSD: loslib.c,v 1.10 2017/04/26 13:17:33 mbalmer Exp $ */ 2 3/* 4** Id: loslib.c,v 1.65 2016/07/18 17:58:58 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 (only 1-char options) */ 36#define L_STRFTIMEC89 "aAbBcdHIjmMpSUwWxXyYZ%" 37 38/* options for ISO C 99 and POSIX */ 39#define L_STRFTIMEC99 "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \ 40 "||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy" /* two-char options */ 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" /* two-char options */ 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 71static 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 143static 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 155static 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 161static 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 168static 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 179static 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 185static 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 199static void setfield (lua_State *L, const char *key, int value) { 200 lua_pushinteger(L, value); 201 lua_setfield(L, -2, key); 202} 203 204static 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*/ 215static 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 228static 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 241static 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 262static const char *checkoption (lua_State *L, const char *conv, 263 ptrdiff_t convlen, char *buff) { 264 const char *option = LUA_STRFTIMEOPTIONS; 265 int oplen = 1; /* length of options being checked */ 266 for (; *option != '\0' && oplen <= convlen; option += oplen) { 267 if (*option == '|') /* next block? */ 268 oplen++; /* will check options with next length (+1) */ 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 285static int os_date (lua_State *L) { 286 size_t slen; 287 const char *s = luaL_optlstring(L, 1, "%c", &slen); 288 time_t t = luaL_opt(L, l_checktime, 2, time(NULL)); 289 const char *se = s + slen; /* 's' end */ 290 struct tm tmr, *stm; 291 if (*s == '!') { /* UTC? */ 292 stm = l_gmtime(&t, &tmr); 293 s++; /* skip '!' */ 294 } 295 else 296 stm = l_localtime(&t, &tmr); 297 if (stm == NULL) /* invalid date? */ 298 luaL_error(L, "time result cannot be represented in this installation"); 299 if (strcmp(s, "*t") == 0) { 300 lua_createtable(L, 0, 9); /* 9 = number of fields */ 301 setallfields(L, stm); 302 } 303 else { 304 char cc[4]; /* buffer for individual conversion specifiers */ 305 luaL_Buffer b; 306 cc[0] = '%'; 307 luaL_buffinit(L, &b); 308 while (s < se) { 309 if (*s != '%') /* not a conversion specifier? */ 310 luaL_addchar(&b, *s++); 311 else { 312 size_t reslen; 313 char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT); 314 s++; /* skip '%' */ 315 s = checkoption(L, s, se - s, cc + 1); /* copy specifier to 'cc' */ 316 reslen = strftime(buff, SIZETIMEFMT, cc, stm); 317 luaL_addsize(&b, reslen); 318 } 319 } 320 luaL_pushresult(&b); 321 } 322 return 1; 323} 324 325 326static int os_time (lua_State *L) { 327 time_t t; 328 if (lua_isnoneornil(L, 1)) /* called without args? */ 329 t = time(NULL); /* get current time */ 330 else { 331 struct tm ts; 332 luaL_checktype(L, 1, LUA_TTABLE); 333 lua_settop(L, 1); /* make sure table is at the top */ 334 ts.tm_sec = getfield(L, "sec", 0, 0); 335 ts.tm_min = getfield(L, "min", 0, 0); 336 ts.tm_hour = getfield(L, "hour", 12, 0); 337 ts.tm_mday = getfield(L, "day", -1, 0); 338 ts.tm_mon = getfield(L, "month", -1, 1); 339 ts.tm_year = getfield(L, "year", -1, 1900); 340 ts.tm_isdst = getboolfield(L, "isdst"); 341 t = mktime(&ts); 342 setallfields(L, &ts); /* update fields with normalized values */ 343 } 344 if (t != (time_t)(l_timet)t || t == (time_t)(-1)) 345 luaL_error(L, "time result cannot be represented in this installation"); 346 l_pushtime(L, t); 347 return 1; 348} 349 350 351static int os_difftime (lua_State *L) { 352 time_t t1 = l_checktime(L, 1); 353 time_t t2 = l_checktime(L, 2); 354 lua_pushnumber(L, (lua_Number)difftime(t1, t2)); 355 return 1; 356} 357 358/* }====================================================== */ 359 360 361static int os_setlocale (lua_State *L) { 362 static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, 363 LC_NUMERIC, LC_TIME}; 364 static const char *const catnames[] = {"all", "collate", "ctype", "monetary", 365 "numeric", "time", NULL}; 366 const char *l = luaL_optstring(L, 1, NULL); 367 int op = luaL_checkoption(L, 2, "all", catnames); 368 lua_pushstring(L, setlocale(cat[op], l)); 369 return 1; 370} 371 372 373static int os_exit (lua_State *L) { 374 int status; 375 if (lua_isboolean(L, 1)) 376 status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE); 377 else 378 status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS); 379 if (lua_toboolean(L, 2)) 380 lua_close(L); 381 if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */ 382 return 0; 383} 384 385 386static const luaL_Reg syslib[] = { 387 {"clock", os_clock}, 388 {"date", os_date}, 389 {"difftime", os_difftime}, 390 {"execute", os_execute}, 391 {"exit", os_exit}, 392 {"getenv", os_getenv}, 393 {"remove", os_remove}, 394 {"rename", os_rename}, 395 {"setlocale", os_setlocale}, 396 {"time", os_time}, 397 {"tmpname", os_tmpname}, 398 {NULL, NULL} 399}; 400 401/* }====================================================== */ 402 403 404 405LUAMOD_API int luaopen_os (lua_State *L) { 406 luaL_newlib(L, syslib); 407 return 1; 408} 409 410