1 /*
2 ** $Id: liolib.c,v 2.112.1.1 2013/04/12 18:48:47 roberto Exp $
3 ** Standard I/O (and system) library
4 ** See Copyright Notice in lua.h
5 */
6
7
8 /*
9 ** This definition must come before the inclusion of 'stdio.h'; it
10 ** should not affect non-POSIX systems
11 */
12 #if !defined(_FILE_OFFSET_BITS)
13 #define _LARGEFILE_SOURCE 1
14 #define _FILE_OFFSET_BITS 64
15 #endif
16
17
18 #include <errno.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22
23 #define liolib_c
24 #define LUA_LIB
25
26 #include "lua.h"
27
28 #include "lauxlib.h"
29 #include "lualib.h"
30
31
32 #if !defined(lua_checkmode)
33
34 /*
35 ** Check whether 'mode' matches '[rwa]%+?b?'.
36 ** Change this macro to accept other modes for 'fopen' besides
37 ** the standard ones.
38 */
39 #define lua_checkmode(mode) \
40 (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && \
41 (*mode != '+' || ++mode) && /* skip if char is '+' */ \
42 (*mode != 'b' || ++mode) && /* skip if char is 'b' */ \
43 (*mode == '\0'))
44
45 #endif
46
47 /*
48 ** {======================================================
49 ** lua_popen spawns a new process connected to the current
50 ** one through the file streams.
51 ** =======================================================
52 */
53
54 #if !defined(lua_popen) /* { */
55
56 #if defined(LUA_USE_POPEN) /* { */
57
58 #define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m))
59 #define lua_pclose(L,file) ((void)L, pclose(file))
60
61 #elif defined(LUA_WIN) /* }{ */
62
63 #define lua_popen(L,c,m) ((void)L, _popen(c,m))
64 #define lua_pclose(L,file) ((void)L, _pclose(file))
65
66
67 #else /* }{ */
68
69 #define lua_popen(L,c,m) ((void)((void)c, m), \
70 luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
71 #define lua_pclose(L,file) ((void)((void)L, file), -1)
72
73
74 #endif /* } */
75
76 #endif /* } */
77
78 /* }====================================================== */
79
80
81 /*
82 ** {======================================================
83 ** lua_fseek: configuration for longer offsets
84 ** =======================================================
85 */
86
87 #if !defined(lua_fseek) && !defined(LUA_ANSI) /* { */
88
89 #if defined(LUA_USE_POSIX) /* { */
90
91 #define l_fseek(f,o,w) fseeko(f,o,w)
92 #define l_ftell(f) ftello(f)
93 #define l_seeknum off_t
94
95 #elif defined(LUA_WIN) && !defined(_CRTIMP_TYPEINFO) \
96 && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
97 /* Windows (but not DDK) and Visual C++ 2005 or higher */
98
99 #define l_fseek(f,o,w) _fseeki64(f,o,w)
100 #define l_ftell(f) _ftelli64(f)
101 #define l_seeknum __int64
102
103 #endif /* } */
104
105 #endif /* } */
106
107
108 #if !defined(l_fseek) /* default definitions */
109 #define l_fseek(f,o,w) fseek(f,o,w)
110 #define l_ftell(f) ftell(f)
111 #define l_seeknum long
112 #endif
113
114 /* }====================================================== */
115
116
117 #define IO_PREFIX "_IO_"
118 #define IO_INPUT (IO_PREFIX "input")
119 #define IO_OUTPUT (IO_PREFIX "output")
120
121
122 typedef luaL_Stream LStream;
123
124
125 #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
126
127 #define isclosed(p) ((p)->closef == NULL)
128
129
io_type(lua_State * L)130 static int io_type (lua_State *L) {
131 LStream *p;
132 luaL_checkany(L, 1);
133 p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
134 if (p == NULL)
135 lua_pushnil(L); /* not a file */
136 else if (isclosed(p))
137 lua_pushliteral(L, "closed file");
138 else
139 lua_pushliteral(L, "file");
140 return 1;
141 }
142
143
f_tostring(lua_State * L)144 static int f_tostring (lua_State *L) {
145 LStream *p = tolstream(L);
146 if (isclosed(p))
147 lua_pushliteral(L, "file (closed)");
148 else
149 lua_pushfstring(L, "file (%p)", p->f);
150 return 1;
151 }
152
153
tofile(lua_State * L)154 static FILE *tofile (lua_State *L) {
155 LStream *p = tolstream(L);
156 if (isclosed(p))
157 luaL_error(L, "attempt to use a closed file");
158 lua_assert(p->f);
159 return p->f;
160 }
161
162
163 /*
164 ** When creating file handles, always creates a `closed' file handle
165 ** before opening the actual file; so, if there is a memory error, the
166 ** file is not left opened.
167 */
newprefile(lua_State * L)168 static LStream *newprefile (lua_State *L) {
169 LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
170 p->closef = NULL; /* mark file handle as 'closed' */
171 luaL_setmetatable(L, LUA_FILEHANDLE);
172 return p;
173 }
174
175
aux_close(lua_State * L)176 static int aux_close (lua_State *L) {
177 LStream *p = tolstream(L);
178 lua_CFunction cf = p->closef;
179 p->closef = NULL; /* mark stream as closed */
180 return (*cf)(L); /* close it */
181 }
182
183
io_close(lua_State * L)184 static int io_close (lua_State *L) {
185 if (lua_isnone(L, 1)) /* no argument? */
186 lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */
187 tofile(L); /* make sure argument is an open stream */
188 return aux_close(L);
189 }
190
191
f_gc(lua_State * L)192 static int f_gc (lua_State *L) {
193 LStream *p = tolstream(L);
194 if (!isclosed(p) && p->f != NULL)
195 aux_close(L); /* ignore closed and incompletely open files */
196 return 0;
197 }
198
199
200 /*
201 ** function to close regular files
202 */
io_fclose(lua_State * L)203 static int io_fclose (lua_State *L) {
204 LStream *p = tolstream(L);
205 int res = fclose(p->f);
206 return luaL_fileresult(L, (res == 0), NULL);
207 }
208
209
newfile(lua_State * L)210 static LStream *newfile (lua_State *L) {
211 LStream *p = newprefile(L);
212 p->f = NULL;
213 p->closef = &io_fclose;
214 return p;
215 }
216
217
opencheck(lua_State * L,const char * fname,const char * mode)218 static void opencheck (lua_State *L, const char *fname, const char *mode) {
219 LStream *p = newfile(L);
220 p->f = fopen(fname, mode);
221 if (p->f == NULL)
222 luaL_error(L, "cannot open file " LUA_QS " (%s)", fname, strerror(errno));
223 }
224
225
io_open(lua_State * L)226 static int io_open (lua_State *L) {
227 const char *filename = luaL_checkstring(L, 1);
228 const char *mode = luaL_optstring(L, 2, "r");
229 LStream *p = newfile(L);
230 const char *md = mode; /* to traverse/check mode */
231 luaL_argcheck(L, lua_checkmode(md), 2, "invalid mode");
232 p->f = fopen(filename, mode);
233 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
234 }
235
236
237 /*
238 ** function to close 'popen' files
239 */
io_pclose(lua_State * L)240 static int io_pclose (lua_State *L) {
241 LStream *p = tolstream(L);
242 return luaL_execresult(L, lua_pclose(L, p->f));
243 }
244
245
io_popen(lua_State * L)246 static int io_popen (lua_State *L) {
247 const char *filename = luaL_checkstring(L, 1);
248 const char *mode = luaL_optstring(L, 2, "r");
249 LStream *p = newprefile(L);
250 p->f = lua_popen(L, filename, mode);
251 p->closef = &io_pclose;
252 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
253 }
254
255
256 #ifndef SYSLINUX
io_tmpfile(lua_State * L)257 static int io_tmpfile (lua_State *L) {
258 LStream *p = newfile(L);
259 p->f = tmpfile();
260 return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
261 }
262 #endif
263
264
getiofile(lua_State * L,const char * findex)265 static FILE *getiofile (lua_State *L, const char *findex) {
266 LStream *p;
267 lua_getfield(L, LUA_REGISTRYINDEX, findex);
268 p = (LStream *)lua_touserdata(L, -1);
269 if (isclosed(p))
270 luaL_error(L, "standard %s file is closed", findex + strlen(IO_PREFIX));
271 return p->f;
272 }
273
274
g_iofile(lua_State * L,const char * f,const char * mode)275 static int g_iofile (lua_State *L, const char *f, const char *mode) {
276 if (!lua_isnoneornil(L, 1)) {
277 const char *filename = lua_tostring(L, 1);
278 if (filename)
279 opencheck(L, filename, mode);
280 else {
281 tofile(L); /* check that it's a valid file handle */
282 lua_pushvalue(L, 1);
283 }
284 lua_setfield(L, LUA_REGISTRYINDEX, f);
285 }
286 /* return current value */
287 lua_getfield(L, LUA_REGISTRYINDEX, f);
288 return 1;
289 }
290
291
io_input(lua_State * L)292 static int io_input (lua_State *L) {
293 return g_iofile(L, IO_INPUT, "r");
294 }
295
296
io_output(lua_State * L)297 static int io_output (lua_State *L) {
298 return g_iofile(L, IO_OUTPUT, "w");
299 }
300
301
302 static int io_readline (lua_State *L);
303
304
aux_lines(lua_State * L,int toclose)305 static void aux_lines (lua_State *L, int toclose) {
306 int i;
307 int n = lua_gettop(L) - 1; /* number of arguments to read */
308 /* ensure that arguments will fit here and into 'io_readline' stack */
309 luaL_argcheck(L, n <= LUA_MINSTACK - 3, LUA_MINSTACK - 3, "too many options");
310 lua_pushvalue(L, 1); /* file handle */
311 lua_pushinteger(L, n); /* number of arguments to read */
312 lua_pushboolean(L, toclose); /* close/not close file when finished */
313 for (i = 1; i <= n; i++) lua_pushvalue(L, i + 1); /* copy arguments */
314 lua_pushcclosure(L, io_readline, 3 + n);
315 }
316
317
f_lines(lua_State * L)318 static int f_lines (lua_State *L) {
319 tofile(L); /* check that it's a valid file handle */
320 aux_lines(L, 0);
321 return 1;
322 }
323
324
io_lines(lua_State * L)325 static int io_lines (lua_State *L) {
326 int toclose;
327 if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
328 if (lua_isnil(L, 1)) { /* no file name? */
329 lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
330 lua_replace(L, 1); /* put it at index 1 */
331 tofile(L); /* check that it's a valid file handle */
332 toclose = 0; /* do not close it after iteration */
333 }
334 else { /* open a new file */
335 const char *filename = luaL_checkstring(L, 1);
336 opencheck(L, filename, "r");
337 lua_replace(L, 1); /* put file at index 1 */
338 toclose = 1; /* close it after iteration */
339 }
340 aux_lines(L, toclose);
341 return 1;
342 }
343
344
345 /*
346 ** {======================================================
347 ** READ
348 ** =======================================================
349 */
350
351
352 #ifndef SYSLINUX
read_number(lua_State * L,FILE * f)353 static int read_number (lua_State *L, FILE *f) {
354 lua_Number d;
355 if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
356 lua_pushnumber(L, d);
357 return 1;
358 }
359 else {
360 lua_pushnil(L); /* "result" to be removed */
361 return 0; /* read fails */
362 }
363 }
364
365
test_eof(lua_State * L,FILE * f)366 static int test_eof (lua_State *L, FILE *f) {
367 int c = getc(f);
368 ungetc(c, f);
369 lua_pushlstring(L, NULL, 0);
370 return (c != EOF);
371 }
372 #else
test_eof(lua_State * L,FILE * f)373 static int test_eof (lua_State *L, FILE *f) {
374 (void)f;
375 lua_pushlstring(L, NULL, 0);
376 return 1;
377 }
378 #endif
379
380
read_line(lua_State * L,FILE * f,int chop)381 static int read_line (lua_State *L, FILE *f, int chop) {
382 luaL_Buffer b;
383 luaL_buffinit(L, &b);
384 for (;;) {
385 size_t l;
386 char *p = luaL_prepbuffer(&b);
387 if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
388 luaL_pushresult(&b); /* close buffer */
389 return (lua_rawlen(L, -1) > 0); /* check whether read something */
390 }
391 l = strlen(p);
392 if (l == 0 || p[l-1] != '\n')
393 luaL_addsize(&b, l);
394 else {
395 luaL_addsize(&b, l - chop); /* chop 'eol' if needed */
396 luaL_pushresult(&b); /* close buffer */
397 return 1; /* read at least an `eol' */
398 }
399 }
400 }
401
402
403 #define MAX_SIZE_T (~(size_t)0)
404
read_all(lua_State * L,FILE * f)405 static void read_all (lua_State *L, FILE *f) {
406 size_t rlen = LUAL_BUFFERSIZE; /* how much to read in each cycle */
407 luaL_Buffer b;
408 luaL_buffinit(L, &b);
409 for (;;) {
410 char *p = luaL_prepbuffsize(&b, rlen);
411 size_t nr = fread(p, sizeof(char), rlen, f);
412 luaL_addsize(&b, nr);
413 if (nr < rlen) break; /* eof? */
414 else if (rlen <= (MAX_SIZE_T / 4)) /* avoid buffers too large */
415 rlen *= 2; /* double buffer size at each iteration */
416 }
417 luaL_pushresult(&b); /* close buffer */
418 }
419
420
read_chars(lua_State * L,FILE * f,size_t n)421 static int read_chars (lua_State *L, FILE *f, size_t n) {
422 size_t nr; /* number of chars actually read */
423 char *p;
424 luaL_Buffer b;
425 luaL_buffinit(L, &b);
426 p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
427 nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
428 luaL_addsize(&b, nr);
429 luaL_pushresult(&b); /* close buffer */
430 return (nr > 0); /* true iff read something */
431 }
432
433
g_read(lua_State * L,FILE * f,int first)434 static int g_read (lua_State *L, FILE *f, int first) {
435 int nargs = lua_gettop(L) - 1;
436 int success;
437 int n;
438 clearerr(f);
439 if (nargs == 0) { /* no arguments? */
440 success = read_line(L, f, 1);
441 n = first+1; /* to return 1 result */
442 }
443 else { /* ensure stack space for all results and for auxlib's buffer */
444 luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
445 success = 1;
446 for (n = first; nargs-- && success; n++) {
447 if (lua_type(L, n) == LUA_TNUMBER) {
448 size_t l = (size_t)lua_tointeger(L, n);
449 success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
450 }
451 else {
452 const char *p = lua_tostring(L, n);
453 luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
454 switch (p[1]) {
455 case 'n': /* number */
456 #ifndef SYSLINUX
457 success = read_number(L, f);
458 #else
459 return luaL_argerror(L, n, "\"*number\" not supported");
460 #endif
461 break;
462 case 'l': /* line */
463 success = read_line(L, f, 1);
464 break;
465 case 'L': /* line with end-of-line */
466 success = read_line(L, f, 0);
467 break;
468 case 'a': /* file */
469 read_all(L, f); /* read entire file */
470 success = 1; /* always success */
471 break;
472 default:
473 return luaL_argerror(L, n, "invalid format");
474 }
475 }
476 }
477 }
478 if (ferror(f))
479 return luaL_fileresult(L, 0, NULL);
480 if (!success) {
481 lua_pop(L, 1); /* remove last result */
482 lua_pushnil(L); /* push nil instead */
483 }
484 return n - first;
485 }
486
487
io_read(lua_State * L)488 static int io_read (lua_State *L) {
489 return g_read(L, getiofile(L, IO_INPUT), 1);
490 }
491
492
f_read(lua_State * L)493 static int f_read (lua_State *L) {
494 return g_read(L, tofile(L), 2);
495 }
496
497
io_readline(lua_State * L)498 static int io_readline (lua_State *L) {
499 LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
500 int i;
501 int n = (int)lua_tointeger(L, lua_upvalueindex(2));
502 if (isclosed(p)) /* file is already closed? */
503 return luaL_error(L, "file is already closed");
504 lua_settop(L , 1);
505 for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
506 lua_pushvalue(L, lua_upvalueindex(3 + i));
507 n = g_read(L, p->f, 2); /* 'n' is number of results */
508 lua_assert(n > 0); /* should return at least a nil */
509 if (!lua_isnil(L, -n)) /* read at least one value? */
510 return n; /* return them */
511 else { /* first result is nil: EOF or error */
512 if (n > 1) { /* is there error information? */
513 /* 2nd result is error message */
514 return luaL_error(L, "%s", lua_tostring(L, -n + 1));
515 }
516 if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
517 lua_settop(L, 0);
518 lua_pushvalue(L, lua_upvalueindex(1));
519 aux_close(L); /* close it */
520 }
521 return 0;
522 }
523 }
524
525 /* }====================================================== */
526
527
g_write(lua_State * L,FILE * f,int arg)528 static int g_write (lua_State *L, FILE *f, int arg) {
529 int nargs = lua_gettop(L) - arg;
530 int status = 1;
531 for (; nargs--; arg++) {
532 if (lua_type(L, arg) == LUA_TNUMBER) {
533 /* optimization: could be done exactly as for strings */
534 status = status &&
535 fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
536 }
537 else {
538 size_t l;
539 const char *s = luaL_checklstring(L, arg, &l);
540 status = status && (fwrite(s, sizeof(char), l, f) == l);
541 }
542 }
543 if (status) return 1; /* file handle already on stack top */
544 else return luaL_fileresult(L, status, NULL);
545 }
546
547
io_write(lua_State * L)548 static int io_write (lua_State *L) {
549 return g_write(L, getiofile(L, IO_OUTPUT), 1);
550 }
551
552
f_write(lua_State * L)553 static int f_write (lua_State *L) {
554 FILE *f = tofile(L);
555 lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
556 return g_write(L, f, 2);
557 }
558
559
560 #ifndef SYSLINUX
f_seek(lua_State * L)561 static int f_seek (lua_State *L) {
562 static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
563 static const char *const modenames[] = {"set", "cur", "end", NULL};
564 FILE *f = tofile(L);
565 int op = luaL_checkoption(L, 2, "cur", modenames);
566 lua_Number p3 = luaL_optnumber(L, 3, 0);
567 l_seeknum offset = (l_seeknum)p3;
568 luaL_argcheck(L, (lua_Number)offset == p3, 3,
569 "not an integer in proper range");
570 op = l_fseek(f, offset, mode[op]);
571 if (op)
572 return luaL_fileresult(L, 0, NULL); /* error */
573 else {
574 lua_pushnumber(L, (lua_Number)l_ftell(f));
575 return 1;
576 }
577 }
578
579
f_setvbuf(lua_State * L)580 static int f_setvbuf (lua_State *L) {
581 static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
582 static const char *const modenames[] = {"no", "full", "line", NULL};
583 FILE *f = tofile(L);
584 int op = luaL_checkoption(L, 2, NULL, modenames);
585 lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
586 int res = setvbuf(f, NULL, mode[op], sz);
587 return luaL_fileresult(L, res == 0, NULL);
588 }
589 #endif
590
591
592
io_flush(lua_State * L)593 static int io_flush (lua_State *L) {
594 return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
595 }
596
597
f_flush(lua_State * L)598 static int f_flush (lua_State *L) {
599 return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
600 }
601
602
603 /*
604 ** functions for 'io' library
605 */
606 static const luaL_Reg iolib[] = {
607 {"close", io_close},
608 {"flush", io_flush},
609 {"input", io_input},
610 {"lines", io_lines},
611 {"open", io_open},
612 {"output", io_output},
613 {"popen", io_popen},
614 {"read", io_read},
615 #ifndef SYSLINUX
616 {"tmpfile", io_tmpfile},
617 #endif
618 {"type", io_type},
619 {"write", io_write},
620 {NULL, NULL}
621 };
622
623
624 /*
625 ** methods for file handles
626 */
627 static const luaL_Reg flib[] = {
628 {"close", io_close},
629 {"flush", f_flush},
630 {"lines", f_lines},
631 {"read", f_read},
632 #ifndef SYSLINUX
633 {"seek", f_seek},
634 {"setvbuf", f_setvbuf},
635 #endif
636 {"write", f_write},
637 {"__gc", f_gc},
638 {"__tostring", f_tostring},
639 {NULL, NULL}
640 };
641
642
createmeta(lua_State * L)643 static void createmeta (lua_State *L) {
644 luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
645 lua_pushvalue(L, -1); /* push metatable */
646 lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
647 luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */
648 lua_pop(L, 1); /* pop new metatable */
649 }
650
651
652 /*
653 ** function to (not) close the standard files stdin, stdout, and stderr
654 */
io_noclose(lua_State * L)655 static int io_noclose (lua_State *L) {
656 LStream *p = tolstream(L);
657 p->closef = &io_noclose; /* keep file opened */
658 lua_pushnil(L);
659 lua_pushliteral(L, "cannot close standard file");
660 return 2;
661 }
662
663
createstdfile(lua_State * L,FILE * f,const char * k,const char * fname)664 static void createstdfile (lua_State *L, FILE *f, const char *k,
665 const char *fname) {
666 LStream *p = newprefile(L);
667 p->f = f;
668 p->closef = &io_noclose;
669 if (k != NULL) {
670 lua_pushvalue(L, -1);
671 lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
672 }
673 lua_setfield(L, -2, fname); /* add file to module */
674 }
675
676
luaopen_io(lua_State * L)677 LUAMOD_API int luaopen_io (lua_State *L) {
678 luaL_newlib(L, iolib); /* new module */
679 createmeta(L);
680 /* create (and set) default files */
681 createstdfile(L, stdin, IO_INPUT, "stdin");
682 createstdfile(L, stdout, IO_OUTPUT, "stdout");
683 createstdfile(L, stderr, NULL, "stderr");
684 return 1;
685 }
686
687