1 /* $NetBSD: loslib.c,v 1.11 2018/08/04 17:30:01 alnsn Exp $ */ 2 3 /* 4 ** Id: loslib.c,v 1.65.1.1 2017/04/19 17:29:57 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 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, 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 285 static 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 return luaL_error(L, 299 "time result cannot be represented in this installation"); 300 if (strcmp(s, "*t") == 0) { 301 lua_createtable(L, 0, 9); /* 9 = number of fields */ 302 setallfields(L, stm); 303 } 304 else { 305 char cc[4]; /* buffer for individual conversion specifiers */ 306 luaL_Buffer b; 307 cc[0] = '%'; 308 luaL_buffinit(L, &b); 309 while (s < se) { 310 if (*s != '%') /* not a conversion specifier? */ 311 luaL_addchar(&b, *s++); 312 else { 313 size_t reslen; 314 char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT); 315 s++; /* skip '%' */ 316 s = checkoption(L, s, se - s, cc + 1); /* copy specifier to 'cc' */ 317 reslen = strftime(buff, SIZETIMEFMT, cc, stm); 318 luaL_addsize(&b, reslen); 319 } 320 } 321 luaL_pushresult(&b); 322 } 323 return 1; 324 } 325 326 327 static int os_time (lua_State *L) { 328 time_t t; 329 if (lua_isnoneornil(L, 1)) /* called without args? */ 330 t = time(NULL); /* get current time */ 331 else { 332 struct tm ts; 333 luaL_checktype(L, 1, LUA_TTABLE); 334 lua_settop(L, 1); /* make sure table is at the top */ 335 ts.tm_sec = getfield(L, "sec", 0, 0); 336 ts.tm_min = getfield(L, "min", 0, 0); 337 ts.tm_hour = getfield(L, "hour", 12, 0); 338 ts.tm_mday = getfield(L, "day", -1, 0); 339 ts.tm_mon = getfield(L, "month", -1, 1); 340 ts.tm_year = getfield(L, "year", -1, 1900); 341 ts.tm_isdst = getboolfield(L, "isdst"); 342 t = mktime(&ts); 343 setallfields(L, &ts); /* update fields with normalized values */ 344 } 345 if (t != (time_t)(l_timet)t || t == (time_t)(-1)) 346 return luaL_error(L, 347 "time result cannot be represented in this installation"); 348 l_pushtime(L, t); 349 return 1; 350 } 351 352 353 static int os_difftime (lua_State *L) { 354 time_t t1 = l_checktime(L, 1); 355 time_t t2 = l_checktime(L, 2); 356 lua_pushnumber(L, (lua_Number)difftime(t1, t2)); 357 return 1; 358 } 359 360 /* }====================================================== */ 361 362 363 static int os_setlocale (lua_State *L) { 364 static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, 365 LC_NUMERIC, LC_TIME}; 366 static const char *const catnames[] = {"all", "collate", "ctype", "monetary", 367 "numeric", "time", NULL}; 368 const char *l = luaL_optstring(L, 1, NULL); 369 int op = luaL_checkoption(L, 2, "all", catnames); 370 lua_pushstring(L, setlocale(cat[op], l)); 371 return 1; 372 } 373 374 375 static int os_exit (lua_State *L) { 376 int status; 377 if (lua_isboolean(L, 1)) 378 status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE); 379 else 380 status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS); 381 if (lua_toboolean(L, 2)) 382 lua_close(L); 383 if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */ 384 return 0; 385 } 386 387 388 static const luaL_Reg syslib[] = { 389 {"clock", os_clock}, 390 {"date", os_date}, 391 {"difftime", os_difftime}, 392 {"execute", os_execute}, 393 {"exit", os_exit}, 394 {"getenv", os_getenv}, 395 {"remove", os_remove}, 396 {"rename", os_rename}, 397 {"setlocale", os_setlocale}, 398 {"time", os_time}, 399 {"tmpname", os_tmpname}, 400 {NULL, NULL} 401 }; 402 403 /* }====================================================== */ 404 405 406 407 LUAMOD_API int luaopen_os (lua_State *L) { 408 luaL_newlib(L, syslib); 409 return 1; 410 } 411 412