liolib.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. /*
  2. ** $Id: liolib.c,v 1.131 2002/02/08 22:39:56 roberto Exp roberto $
  3. ** Standard I/O (and system) library
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <errno.h>
  7. #include <locale.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <time.h>
  12. #include "lua.h"
  13. #include "lauxlib.h"
  14. #include "luadebug.h"
  15. #include "lualib.h"
  16. /*
  17. ** {======================================================
  18. ** FILE Operations
  19. ** =======================================================
  20. */
  21. #ifdef POPEN
  22. /* FILE *popen();
  23. int pclose(); */
  24. #define CLOSEFILE(L, f) ((pclose(f) == -1) ? fclose(f) : 0)
  25. #else
  26. /* no support for popen */
  27. #define popen(x,y) NULL /* that is, popen always fails */
  28. #define CLOSEFILE(L, f) (fclose(f))
  29. #endif
  30. #define INFILE 0
  31. #define OUTFILE 1
  32. #define NOFILE 2
  33. #define FILEHANDLE "FileHandle"
  34. #define CLOSEDFILEHANDLE "ClosedFileHandle"
  35. static const char *const filenames[] = {"_INPUT", "_OUTPUT"};
  36. static const char *const basicfiles[] = {"stdin", "stdout"};
  37. static int pushresult (lua_State *L, int i) {
  38. if (i) {
  39. lua_pushnumber(L, 1);
  40. return 1;
  41. }
  42. else {
  43. lua_pushnil(L);
  44. lua_pushstring(L, strerror(errno));
  45. lua_pushnumber(L, errno);
  46. return 3;
  47. }
  48. }
  49. static int checkfile (lua_State *L, int findex, const char *tname) {
  50. int res;
  51. lua_getmetatable(L, findex);
  52. lua_pushstring(L, tname);
  53. lua_rawget(L, LUA_REGISTRYINDEX);
  54. res = lua_equal(L, -1, -2);
  55. lua_pop(L, 2);
  56. return res;
  57. }
  58. /* temporary?? should be in auxlib... */
  59. static void *luaL_check_userdata (lua_State *L, int findex, const char *tn) {
  60. luaL_arg_check(L, checkfile(L, findex, tn), findex, "bad file");
  61. return lua_touserdata(L, findex);
  62. }
  63. static FILE *getopthandle (lua_State *L, int inout) {
  64. FILE *p = (FILE *)(lua_touserdata(L, 1));
  65. if (p != NULL) { /* is it a userdata ? */
  66. if (!checkfile(L, 1, FILEHANDLE)) { /* not a valid file handle? */
  67. if (checkfile(L, 1, CLOSEDFILEHANDLE))
  68. luaL_argerror(L, 1, "file is closed");
  69. else
  70. luaL_argerror(L, 1, "(invalid value)");
  71. }
  72. lua_pushvalue(L, 1); lua_remove(L, 1); /* move it to stack top */
  73. }
  74. else { /* try global value */
  75. lua_getglobal(L, filenames[inout]);
  76. if (!checkfile(L, -1, FILEHANDLE))
  77. luaL_verror(L, "global variable `%.10s' is not a valid file handle",
  78. filenames[inout]);
  79. p = (FILE *)(lua_touserdata(L, -1));
  80. }
  81. return p; /* leave handle at stack top to avoid GC */
  82. }
  83. static void newfile (lua_State *L, FILE *f) {
  84. lua_newuserdatabox(L, f);
  85. lua_pushliteral(L, FILEHANDLE);
  86. lua_rawget(L, LUA_REGISTRYINDEX);
  87. lua_setmetatable(L, -2);
  88. }
  89. static void newfilewithname (lua_State *L, FILE *f, const char *name) {
  90. lua_pushstring(L, name);
  91. newfile(L, f);
  92. lua_settable(L, -3);
  93. }
  94. static int setnewfile (lua_State *L, FILE *f, int inout) {
  95. if (f == NULL)
  96. return pushresult(L, 0);
  97. else {
  98. newfile(L, f);
  99. if (inout != NOFILE) {
  100. lua_pushvalue(L, -1);
  101. lua_setglobal(L, filenames[inout]);
  102. }
  103. return 1;
  104. }
  105. }
  106. static void resetfile (lua_State *L, int inout) {
  107. lua_getglobal(L, "io");
  108. lua_pushstring(L, basicfiles[inout]);
  109. lua_gettable(L, -2);
  110. lua_setglobal(L, filenames[inout]);
  111. lua_pop(L, 1);
  112. }
  113. static int io_close (lua_State *L) {
  114. FILE *f = (FILE *)(luaL_check_userdata(L, 1, FILEHANDLE));
  115. int status = 1;
  116. if (f != stdin && f != stdout && f != stderr) {
  117. lua_settop(L, 1); /* make sure file is on top */
  118. lua_pushliteral(L, CLOSEDFILEHANDLE);
  119. lua_rawget(L, LUA_REGISTRYINDEX);
  120. lua_setmetatable(L, 1);
  121. status = (CLOSEFILE(L, f) == 0);
  122. }
  123. return pushresult(L, status);
  124. }
  125. static int file_collect (lua_State *L) {
  126. FILE *f = (FILE *)(luaL_check_userdata(L, 1, FILEHANDLE));
  127. if (f != stdin && f != stdout && f != stderr)
  128. CLOSEFILE(L, f);
  129. return 0;
  130. }
  131. static int io_open (lua_State *L) {
  132. FILE *f = fopen(luaL_check_string(L, 1), luaL_check_string(L, 2));
  133. return setnewfile(L, f, NOFILE);
  134. }
  135. static int io_tmpfile (lua_State *L) {
  136. return setnewfile(L, tmpfile(), NOFILE);
  137. }
  138. static int io_fromto (lua_State *L, int inout, const char *mode) {
  139. FILE *current;
  140. if (lua_isnone(L, 1)) {
  141. getopthandle(L, inout);
  142. resetfile(L, inout);
  143. return io_close(L);
  144. }
  145. else {
  146. const char *s = luaL_check_string(L, 1);
  147. current = (*s == '|') ? popen(s+1, mode) : fopen(s, mode);
  148. return setnewfile(L, current, inout);
  149. }
  150. }
  151. static int io_readfrom (lua_State *L) {
  152. return io_fromto(L, INFILE, "r");
  153. }
  154. static int io_writeto (lua_State *L) {
  155. return io_fromto(L, OUTFILE, "w");
  156. }
  157. static int io_appendto (lua_State *L) {
  158. FILE *current = fopen(luaL_check_string(L, 1), "a");
  159. return setnewfile(L, current, OUTFILE);
  160. }
  161. /*
  162. ** {======================================================
  163. ** READ
  164. ** =======================================================
  165. */
  166. #ifndef LUA_MAXUNTIL
  167. #define LUA_MAXUNTIL 100
  168. #endif
  169. /*
  170. ** Knuth-Morris-Pratt algorithm for string searching
  171. ** (based on `Algorithms in MODULA-3', Robert Sedgewick;
  172. ** Addison-Wesley, 1993.)
  173. */
  174. static void prep_read_until (int next[], const char *p, int pl) {
  175. int i = 0;
  176. int j = -1;
  177. next[0] = -1;
  178. while (i < pl) {
  179. if (j == -1 || p[i] == p[j]) {
  180. i++; j++; next[i] = j;
  181. }
  182. else j = next[j];
  183. }
  184. }
  185. static int read_until (lua_State *L, FILE *f, const char *p, int pl) {
  186. int c;
  187. int j;
  188. int next[LUA_MAXUNTIL+1];
  189. luaL_Buffer b;
  190. luaL_buffinit(L, &b);
  191. prep_read_until(next, p, pl);
  192. j = 0;
  193. while ((c = getc(f)) != EOF) {
  194. NoRead:
  195. if (c == p[j]) {
  196. j++; /* go to next char in pattern */
  197. if (j == pl) { /* complete match? */
  198. luaL_pushresult(&b); /* close buffer */
  199. return 1; /* always success */
  200. }
  201. }
  202. else if (j == 0)
  203. luaL_putchar(&b, c);
  204. else { /* match fail */
  205. luaL_addlstring(&b, p, j - next[j]); /* put failed part on result */
  206. j = next[j]; /* backtrack pattern index */
  207. goto NoRead; /* repeat without reading next char */
  208. }
  209. }
  210. /* end of file without a match */
  211. luaL_addlstring(&b, p, j); /* put failed part on result */
  212. luaL_pushresult(&b); /* close buffer */
  213. return (lua_strlen(L, -1) > 0);
  214. }
  215. static int read_number (lua_State *L, FILE *f) {
  216. lua_Number d;
  217. if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
  218. lua_pushnumber(L, d);
  219. return 1;
  220. }
  221. else return 0; /* read fails */
  222. }
  223. static int test_eof (lua_State *L, FILE *f) {
  224. int c = getc(f);
  225. ungetc(c, f);
  226. lua_pushlstring(L, NULL, 0);
  227. return (c != EOF);
  228. }
  229. static int read_chars (lua_State *L, FILE *f, size_t n) {
  230. size_t rlen; /* how much to read */
  231. size_t nr; /* number of chars actually read */
  232. luaL_Buffer b;
  233. luaL_buffinit(L, &b);
  234. rlen = LUAL_BUFFERSIZE; /* try to read that much each time */
  235. do {
  236. char *p = luaL_prepbuffer(&b);
  237. if (rlen > n) rlen = n; /* cannot read more than asked */
  238. nr = fread(p, sizeof(char), rlen, f);
  239. luaL_addsize(&b, nr);
  240. n -= nr; /* still have to read `n' chars */
  241. } while (n > 0 && nr == rlen); /* until end of count or eof */
  242. luaL_pushresult(&b); /* close buffer */
  243. return (n == 0 || lua_strlen(L, -1) > 0);
  244. }
  245. static int io_read (lua_State *L) {
  246. FILE *f = getopthandle(L, INFILE);
  247. int nargs = lua_gettop(L) - 1;
  248. int success;
  249. int n;
  250. if (nargs == 0) { /* no arguments? */
  251. success = read_until(L, f, "\n", 1); /* read until \n (a line) */
  252. n = 2; /* will return n-1 results */
  253. }
  254. else { /* ensure stack space for all results and for auxlib's buffer */
  255. luaL_check_stack(L, nargs+LUA_MINSTACK, "too many arguments");
  256. success = 1;
  257. for (n = 1; n<=nargs && success; n++) {
  258. if (lua_type(L, n) == LUA_TNUMBER) {
  259. size_t l = (size_t)lua_tonumber(L, n);
  260. success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
  261. }
  262. else {
  263. const char *p = lua_tostring(L, n);
  264. if (!p || p[0] != '*')
  265. lua_error(L, "invalid `read' option");
  266. switch (p[1]) {
  267. case 'n': /* number */
  268. success = read_number(L, f);
  269. break;
  270. case 'l': /* line */
  271. success = read_until(L, f, "\n", 1); /* read until \n */
  272. break;
  273. case 'a': /* file */
  274. read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */
  275. success = 1; /* always success */
  276. break;
  277. case 'w': /* word */
  278. lua_error(L, "obsolete option `*w'");
  279. break;
  280. case 'u': { /* read until */
  281. size_t pl = lua_strlen(L, n) - 2;
  282. luaL_arg_check(L, 0 < pl && pl <= LUA_MAXUNTIL, n,
  283. "invalid read-until length");
  284. success = read_until(L, f, p+2, (int)(pl));
  285. break;
  286. }
  287. default:
  288. luaL_argerror(L, n, "invalid format");
  289. success = 0; /* to avoid warnings */
  290. }
  291. }
  292. }
  293. }
  294. if (!success) {
  295. lua_pop(L, 1); /* remove last result */
  296. lua_pushnil(L); /* push nil instead */
  297. }
  298. return n - 1;
  299. }
  300. /* }====================================================== */
  301. static int io_write (lua_State *L) {
  302. FILE *f = getopthandle(L, OUTFILE);
  303. int nargs = lua_gettop(L)-1;
  304. int arg;
  305. int status = 1;
  306. for (arg=1; arg<=nargs; arg++) {
  307. if (lua_type(L, arg) == LUA_TNUMBER) {
  308. /* optimization: could be done exactly as for strings */
  309. status = status &&
  310. fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
  311. }
  312. else {
  313. size_t l;
  314. const char *s = luaL_check_lstr(L, arg, &l);
  315. status = status && (fwrite(s, sizeof(char), l, f) == l);
  316. }
  317. }
  318. pushresult(L, status);
  319. return 1;
  320. }
  321. static int io_seek (lua_State *L) {
  322. static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  323. static const char *const modenames[] = {"set", "cur", "end", NULL};
  324. FILE *f = (FILE *)(luaL_check_userdata(L, 1, FILEHANDLE));
  325. int op = luaL_findstring(luaL_opt_string(L, 2, "cur"), modenames);
  326. long offset = luaL_opt_long(L, 3, 0);
  327. luaL_arg_check(L, op != -1, 2, "invalid mode");
  328. op = fseek(f, offset, mode[op]);
  329. if (op)
  330. return pushresult(L, 0); /* error */
  331. else {
  332. lua_pushnumber(L, ftell(f));
  333. return 1;
  334. }
  335. }
  336. static int io_flush (lua_State *L) {
  337. FILE *f = (lua_isnone(L, 1)) ? (FILE *)(NULL) :
  338. (FILE *)(luaL_check_userdata(L, 1, FILEHANDLE));
  339. return pushresult(L, fflush(f) == 0);
  340. }
  341. static const luaL_reg iolib[] = {
  342. {"appendto", io_appendto},
  343. {"close", io_close},
  344. {"flush", io_flush},
  345. {"open", io_open},
  346. {"read", io_read},
  347. {"readfrom", io_readfrom},
  348. {"seek", io_seek},
  349. {"tmpfile", io_tmpfile},
  350. {"write", io_write},
  351. {"writeto", io_writeto},
  352. {NULL, NULL}
  353. };
  354. /* }====================================================== */
  355. /*
  356. ** {======================================================
  357. ** Other O.S. Operations
  358. ** =======================================================
  359. */
  360. static int io_execute (lua_State *L) {
  361. lua_pushnumber(L, system(luaL_check_string(L, 1)));
  362. return 1;
  363. }
  364. static int io_remove (lua_State *L) {
  365. return pushresult(L, remove(luaL_check_string(L, 1)) == 0);
  366. }
  367. static int io_rename (lua_State *L) {
  368. return pushresult(L, rename(luaL_check_string(L, 1),
  369. luaL_check_string(L, 2)) == 0);
  370. }
  371. static int io_tmpname (lua_State *L) {
  372. char buff[L_tmpnam];
  373. if (tmpnam(buff) != buff)
  374. lua_error(L, "unable to generate a unique filename");
  375. lua_pushstring(L, buff);
  376. return 1;
  377. }
  378. static int io_getenv (lua_State *L) {
  379. lua_pushstring(L, getenv(luaL_check_string(L, 1))); /* if NULL push nil */
  380. return 1;
  381. }
  382. static int io_clock (lua_State *L) {
  383. lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
  384. return 1;
  385. }
  386. /*
  387. ** {======================================================
  388. ** Time/Date operations
  389. ** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
  390. ** wday=%w+1, yday=%j, isdst=? }
  391. ** =======================================================
  392. */
  393. static void setfield (lua_State *L, const char *key, int value) {
  394. lua_pushstring(L, key);
  395. lua_pushnumber(L, value);
  396. lua_rawset(L, -3);
  397. }
  398. static int getfield (lua_State *L, const char *key, int d) {
  399. int res;
  400. lua_pushstring(L, key);
  401. lua_gettable(L, -2);
  402. if (lua_isnumber(L, -1))
  403. res = (int)(lua_tonumber(L, -1));
  404. else {
  405. if (d == -2)
  406. luaL_verror(L, "field `%.20s' missing in date table", key);
  407. res = d;
  408. }
  409. lua_pop(L, 1);
  410. return res;
  411. }
  412. static int io_date (lua_State *L) {
  413. const char *s = luaL_opt_string(L, 1, "%c");
  414. time_t t = (time_t)(luaL_opt_number(L, 2, -1));
  415. struct tm *stm;
  416. if (t == (time_t)(-1)) /* no time given? */
  417. t = time(NULL); /* use current time */
  418. if (*s == '!') { /* UTC? */
  419. stm = gmtime(&t);
  420. s++; /* skip `!' */
  421. }
  422. else
  423. stm = localtime(&t);
  424. if (stm == NULL) /* invalid date? */
  425. lua_pushnil(L);
  426. else if (strcmp(s, "*t") == 0) {
  427. lua_newtable(L);
  428. setfield(L, "sec", stm->tm_sec);
  429. setfield(L, "min", stm->tm_min);
  430. setfield(L, "hour", stm->tm_hour);
  431. setfield(L, "day", stm->tm_mday);
  432. setfield(L, "month", stm->tm_mon+1);
  433. setfield(L, "year", stm->tm_year+1900);
  434. setfield(L, "wday", stm->tm_wday+1);
  435. setfield(L, "yday", stm->tm_yday+1);
  436. setfield(L, "isdst", stm->tm_isdst);
  437. }
  438. else {
  439. char b[256];
  440. if (strftime(b, sizeof(b), s, stm))
  441. lua_pushstring(L, b);
  442. else
  443. lua_error(L, "invalid `date' format");
  444. }
  445. return 1;
  446. }
  447. static int io_time (lua_State *L) {
  448. if (lua_isnone(L, 1)) /* called without args? */
  449. lua_pushnumber(L, time(NULL)); /* return current time */
  450. else {
  451. time_t t;
  452. struct tm ts;
  453. luaL_check_type(L, 1, LUA_TTABLE);
  454. lua_settop(L, 1); /* make sure table is at the top */
  455. ts.tm_sec = getfield(L, "sec", 0);
  456. ts.tm_min = getfield(L, "min", 0);
  457. ts.tm_hour = getfield(L, "hour", 12);
  458. ts.tm_mday = getfield(L, "day", -2);
  459. ts.tm_mon = getfield(L, "month", -2)-1;
  460. ts.tm_year = getfield(L, "year", -2)-1900;
  461. ts.tm_isdst = getfield(L, "isdst", -1);
  462. t = mktime(&ts);
  463. if (t == (time_t)(-1))
  464. lua_pushnil(L);
  465. else
  466. lua_pushnumber(L, t);
  467. }
  468. return 1;
  469. }
  470. static int io_difftime (lua_State *L) {
  471. lua_pushnumber(L, difftime((time_t)(luaL_check_number(L, 1)),
  472. (time_t)(luaL_opt_number(L, 2, 0))));
  473. return 1;
  474. }
  475. /* }====================================================== */
  476. static int io_setloc (lua_State *L) {
  477. static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
  478. LC_NUMERIC, LC_TIME};
  479. static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
  480. "numeric", "time", NULL};
  481. const char *l = lua_tostring(L, 1);
  482. int op = luaL_findstring(luaL_opt_string(L, 2, "all"), catnames);
  483. luaL_arg_check(L, l || lua_isnil(L, 1) || lua_isnone(L, 1), 1,
  484. "string expected");
  485. luaL_arg_check(L, op != -1, 2, "invalid option");
  486. lua_pushstring(L, setlocale(cat[op], l));
  487. return 1;
  488. }
  489. static int io_exit (lua_State *L) {
  490. exit(luaL_opt_int(L, 1, EXIT_SUCCESS));
  491. return 0; /* to avoid warnings */
  492. }
  493. static const luaL_reg syslib[] = {
  494. {"clock", io_clock},
  495. {"date", io_date},
  496. {"difftime", io_difftime},
  497. {"execute", io_execute},
  498. {"exit", io_exit},
  499. {"getenv", io_getenv},
  500. {"remove", io_remove},
  501. {"rename", io_rename},
  502. {"setlocale", io_setloc},
  503. {"time", io_time},
  504. {"tmpname", io_tmpname},
  505. {NULL, NULL}
  506. };
  507. /* }====================================================== */
  508. LUALIB_API int lua_iolibopen (lua_State *L) {
  509. lua_pushliteral(L, FILEHANDLE);
  510. lua_newtable(L); /* meta table for FILEHANDLE */
  511. /* close files when collected */
  512. lua_pushliteral(L, "__gc");
  513. lua_pushcfunction(L, file_collect);
  514. lua_rawset(L, -3);
  515. /* put new metatable into registry */
  516. lua_rawset(L, LUA_REGISTRYINDEX);
  517. /* meta table for CLOSEDFILEHANDLE */
  518. lua_pushliteral(L, CLOSEDFILEHANDLE);
  519. lua_newtable(L);
  520. lua_rawset(L, LUA_REGISTRYINDEX);
  521. luaL_opennamedlib(L, "os", syslib);
  522. lua_pushliteral(L, "io");
  523. lua_newtable(L);
  524. luaL_openlib(L, iolib);
  525. /* predefined file handles */
  526. newfilewithname(L, stdin, basicfiles[INFILE]);
  527. newfilewithname(L, stdout, basicfiles[OUTFILE]);
  528. newfilewithname(L, stderr, "stderr");
  529. lua_settable(L, LUA_GLOBALSINDEX);
  530. resetfile(L, INFILE);
  531. resetfile(L, OUTFILE);
  532. return 0;
  533. }