2
0

loslib.c 11 KB

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