loslib.c 10 KB

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