loslib.c 12 KB

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