blob: adbf01b60caf621a2d1d0c3b84d6d84a4fe3e811 [file] [log] [blame]
Guido van Rossuma9e20242007-03-08 00:43:48 +00001/* Author: Daniel Stutzbach */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
5#include <sys/types.h>
6#include <sys/stat.h>
7#include <fcntl.h>
8#include <stddef.h> /* For offsetof */
9
10/*
11 * Known likely problems:
12 *
13 * - Files larger then 2**32-1
14 * - Files with unicode filenames
15 * - Passing numbers greater than 2**32-1 when an integer is expected
16 * - Making it work on Windows and other oddball platforms
17 *
18 * To Do:
19 *
20 * - autoconfify header file inclusion
21 * - Make the ABC RawIO type and inherit from it.
22 *
23 * Unanswered questions:
24 *
25 * - Add mode, name, and closed properties a la Python 2 file objects?
26 * - Do we need a (*close)() in the struct like Python 2 file objects,
27 * for not-quite-ordinary-file objects?
28 */
29
30#ifdef MS_WINDOWS
31/* can simulate truncate with Win32 API functions; see file_truncate */
32#define HAVE_FTRUNCATE
33#define WIN32_LEAN_AND_MEAN
34#include <windows.h>
35#endif
36
37typedef struct {
38 PyObject_HEAD
39 int fd;
40 int own_fd; /* 1 means we should close fd */
41 int readable;
42 int writable;
43 int seekable; /* -1 means unknown */
44 PyObject *weakreflist;
45} PyFileIOObject;
46
Collin Winteraf334382007-03-08 21:46:15 +000047PyTypeObject PyFileIO_Type;
48
Guido van Rossuma9e20242007-03-08 00:43:48 +000049#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
50
51/* Note: if this function is changed so that it can return a true value,
52 * then we need a separate function for __exit__
53 */
54static PyObject *
55fileio_close(PyFileIOObject *self)
56{
57 if (self->fd >= 0) {
58 Py_BEGIN_ALLOW_THREADS
59 errno = 0;
60 close(self->fd);
61 Py_END_ALLOW_THREADS
62 if (errno < 0) {
63 PyErr_SetFromErrno(PyExc_IOError);
64 return NULL;
65 }
66 self->fd = -1;
67 }
68
69 Py_RETURN_NONE;
70}
71
72static PyObject *
73fileio_new(PyTypeObject *type, PyObject *args, PyObject *kews)
74{
75 PyFileIOObject *self;
76
77 assert(type != NULL && type->tp_alloc != NULL);
78
79 self = (PyFileIOObject *) type->tp_alloc(type, 0);
80 if (self != NULL) {
81 self->fd = -1;
82 self->weakreflist = NULL;
83 self->own_fd = 1;
84 self->seekable = -1;
85 }
86
87 return (PyObject *) self;
88}
89
90/* On Unix, open will succeed for directories.
91 In Python, there should be no file objects referring to
92 directories, so we need a check. */
93
94static int
95dircheck(PyFileIOObject* self)
96{
97#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
98 struct stat buf;
99 if (self->fd < 0)
100 return 0;
101 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
102#ifdef HAVE_STRERROR
103 char *msg = strerror(EISDIR);
104#else
105 char *msg = "Is a directory";
106#endif
107 PyObject *exc;
108 PyObject *closeresult = fileio_close(self);
109 Py_DECREF(closeresult);
110
111 exc = PyObject_CallFunction(PyExc_IOError, "(is)",
112 EISDIR, msg);
113 PyErr_SetObject(PyExc_IOError, exc);
114 Py_XDECREF(exc);
115 return -1;
116 }
117#endif
118 return 0;
119}
120
121
122static int
123fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
124{
125 PyFileIOObject *self = (PyFileIOObject *) oself;
126 static char *kwlist[] = {"filename", "mode", NULL};
127 char *name = NULL;
128 char *mode = "r";
129 char *s;
130 int wideargument = 0;
131 int ret = 0;
132 int rwa = 0, plus = 0, append = 0;
133 int flags = 0;
134
135 assert(PyFileIO_Check(oself));
136 if (self->fd >= 0)
137 {
138 /* Have to close the existing file first. */
139 PyObject *closeresult = fileio_close(self);
140 if (closeresult == NULL)
141 return -1;
142 Py_DECREF(closeresult);
143 }
144
145#ifdef Py_WIN_WIDE_FILENAMES
146 if (GetVersion() < 0x80000000) { /* On NT, so wide API available */
147 PyObject *po;
148 if (PyArg_ParseTupleAndKeywords(args, kwds, "U|s:fileio",
149 kwlist, &po, &mode)) {
150 wideargument = 1;
151 } else {
152 /* Drop the argument parsing error as narrow
153 strings are also valid. */
154 PyErr_Clear();
155 }
156
157 PyErr_SetString(PyExc_NotImplementedError,
158 "Windows wide filenames are not yet supported");
159 goto error;
160 }
161#endif
162
163 if (!wideargument) {
164 if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|s:fileio",
165 kwlist,
166 Py_FileSystemDefaultEncoding,
167 &name, &mode))
168 goto error;
169 }
170
171 self->readable = self->writable = 0;
172 s = mode;
173 while (*s) {
174 switch (*s++) {
175 case 'r':
176 if (rwa) {
177 bad_mode:
178 PyErr_SetString(PyExc_ValueError,
179 "Must have exactly one of read/write/append mode");
180 goto error;
181 }
182 rwa = 1;
183 self->readable = 1;
184 break;
185 case 'w':
186 if (rwa)
187 goto bad_mode;
188 rwa = 1;
189 self->writable = 1;
190 flags |= O_CREAT | O_TRUNC;
191 break;
192 case 'a':
193 if (rwa)
194 goto bad_mode;
195 rwa = 1;
196 self->writable = 1;
197 flags |= O_CREAT;
198 append = 1;
199 break;
200 case '+':
201 if (plus)
202 goto bad_mode;
203 self->readable = self->writable = 1;
204 plus = 1;
205 break;
206 default:
207 PyErr_Format(PyExc_ValueError,
208 "invalid mode: %.200s", mode);
209 goto error;
210 }
211 }
212
213 if (!rwa)
214 goto bad_mode;
215
216 if (self->readable && self->writable)
217 flags |= O_RDWR;
218 else if (self->readable)
219 flags |= O_RDONLY;
220 else
221 flags |= O_WRONLY;
222
223#ifdef O_BINARY
224 flags |= O_BINARY;
225#endif
226
227 Py_BEGIN_ALLOW_THREADS
228 errno = 0;
229 self->fd = open(name, flags, 0666);
230 Py_END_ALLOW_THREADS
231 if (self->fd < 0 || dircheck(self) < 0) {
232 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
233 goto error;
234 }
235
236 goto done;
237
238 error:
239 ret = -1;
240
241 done:
242 PyMem_Free(name);
243 return ret;
244}
245
246static void
247fileio_dealloc(PyFileIOObject *self)
248{
249 if (self->weakreflist != NULL)
250 PyObject_ClearWeakRefs((PyObject *) self);
251
252 if (self->fd >= 0 && self->own_fd) {
253 PyObject *closeresult = fileio_close(self);
254 if (closeresult == NULL) {
255#ifdef HAVE_STRERROR
256 PySys_WriteStderr("close failed: [Errno %d] %s\n", errno, strerror(errno));
257#else
258 PySys_WriteStderr("close failed: [Errno %d]\n", errno);
259#endif
260 } else
261 Py_DECREF(closeresult);
262 }
263
264 self->ob_type->tp_free((PyObject *)self);
265}
266
267static PyObject *
268err_closed(void)
269{
270 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
271 return NULL;
272}
273
274static PyObject *
275fileio_fileno(PyFileIOObject *self)
276{
277 if (self->fd < 0)
278 return err_closed();
279 return PyInt_FromLong((long) self->fd);
280}
281
282static PyObject *
283fileio_readable(PyFileIOObject *self)
284{
285 if (self->fd < 0)
286 return err_closed();
287 return PyInt_FromLong((long) self->readable);
288}
289
290static PyObject *
291fileio_writable(PyFileIOObject *self)
292{
293 if (self->fd < 0)
294 return err_closed();
295 return PyInt_FromLong((long) self->writable);
296}
297
298static PyObject *
299fileio_seekable(PyFileIOObject *self)
300{
301 if (self->fd < 0)
302 return err_closed();
303 if (self->seekable < 0) {
304 int ret;
305 Py_BEGIN_ALLOW_THREADS
306 ret = lseek(self->fd, 0, SEEK_CUR);
307 Py_END_ALLOW_THREADS
308 if (ret < 0)
309 self->seekable = 0;
310 else
311 self->seekable = 1;
312 }
313 return PyInt_FromLong((long) self->seekable);
314}
315
316static PyObject *
317fileio_readinto(PyFileIOObject *self, PyObject *args)
318{
319 char *ptr;
320 Py_ssize_t n;
321
322 if (self->fd < 0)
323 return err_closed();
324 if (!PyArg_ParseTuple(args, "w#", &ptr, &n))
325 return NULL;
326
327 Py_BEGIN_ALLOW_THREADS
328 errno = 0;
329 n = read(self->fd, ptr, n);
330 Py_END_ALLOW_THREADS
331 if (n < 0) {
332 if (errno == EAGAIN)
333 Py_RETURN_NONE;
334 PyErr_SetFromErrno(PyExc_IOError);
335 return NULL;
336 }
337
338 return PyInt_FromLong(n);
339}
340
341static PyObject *
342fileio_read(PyFileIOObject *self, PyObject *args)
343{
344 char *ptr;
345 Py_ssize_t n, size;
346 PyObject *bytes;
347
348 if (self->fd < 0)
349 return err_closed();
350
351 if (!PyArg_ParseTuple(args, "i", &size))
352 return NULL;
353
354 bytes = PyBytes_FromStringAndSize(NULL, size);
355 if (bytes == NULL)
356 return NULL;
357 ptr = PyBytes_AsString(bytes);
358
359 Py_BEGIN_ALLOW_THREADS
360 errno = 0;
361 n = read(self->fd, ptr, size);
362 Py_END_ALLOW_THREADS
363
364 if (n < 0) {
365 if (errno == EAGAIN)
366 Py_RETURN_NONE;
367 PyErr_SetFromErrno(PyExc_IOError);
368 return NULL;
369 }
370
371 if (n != size) {
372 if (PyBytes_Resize(bytes, n) < 0) {
373 Py_DECREF(bytes);
374 return NULL;
375 }
376 }
377
378 return (PyObject *) bytes;
379}
380
381static PyObject *
382fileio_write(PyFileIOObject *self, PyObject *args)
383{
384 Py_ssize_t n;
385 char *ptr;
386
387 if (self->fd < 0)
388 return err_closed();
389 if (!PyArg_ParseTuple(args, "s#", &ptr, &n))
390 return NULL;
391
392 Py_BEGIN_ALLOW_THREADS
393 errno = 0;
394 n = write(self->fd, ptr, n);
395 Py_END_ALLOW_THREADS
396
397 if (n < 0) {
398 if (errno == EAGAIN)
399 Py_RETURN_NONE;
400 PyErr_SetFromErrno(PyExc_IOError);
401 return NULL;
402 }
403
404 return PyInt_FromLong(n);
405}
406
407static PyObject *
408fileio_seek(PyFileIOObject *self, PyObject *args)
409{
410 Py_ssize_t offset;
411 Py_ssize_t whence = 0;
412
413 if (self->fd < 0)
414 return err_closed();
415
416 if (!PyArg_ParseTuple(args, "i|i", &offset, &whence))
417 return NULL;
418
419 Py_BEGIN_ALLOW_THREADS
420 errno = 0;
421 offset = lseek(self->fd, offset, whence);
422 Py_END_ALLOW_THREADS
423
424 if (offset < 0) {
425 PyErr_SetFromErrno(PyExc_IOError);
426 return NULL;
427 }
428
429 Py_RETURN_NONE;
430}
431
432static PyObject *
433fileio_tell(PyFileIOObject *self, PyObject *args)
434{
435 Py_ssize_t offset;
436
437 if (self->fd < 0)
438 return err_closed();
439
440 Py_BEGIN_ALLOW_THREADS
441 errno = 0;
442 offset = lseek(self->fd, 0, SEEK_CUR);
443 Py_END_ALLOW_THREADS
444
445 if (offset < 0) {
446 PyErr_SetFromErrno(PyExc_IOError);
447 return NULL;
448 }
449
450 return PyInt_FromLong(offset);
451}
452
453#ifdef HAVE_FTRUNCATE
454static PyObject *
455fileio_truncate(PyFileIOObject *self, PyObject *args)
456{
457 Py_ssize_t length;
458 int ret;
459
460 if (self->fd < 0)
461 return err_closed();
462
463 /* Setup default value */
464 Py_BEGIN_ALLOW_THREADS
465 errno = 0;
466 length = lseek(self->fd, 0, SEEK_CUR);
467 Py_END_ALLOW_THREADS
468
469 if (length < 0) {
470 PyErr_SetFromErrno(PyExc_IOError);
471 return NULL;
472 }
473
474 if (!PyArg_ParseTuple(args, "|i", &length))
475 return NULL;
476
477#ifdef MS_WINDOWS
478 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
479 so don't even try using it. */
480 {
481 HANDLE hFile;
482 Py_ssize_t initialpos;
483
484 /* Have to move current pos to desired endpoint on Windows. */
485 Py_BEGIN_ALLOW_THREADS
486 errno = 0;
487 ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
488 Py_END_ALLOW_THREADS
489 if (ret)
490 goto onioerror;
491
492 /* Truncate. Note that this may grow the file! */
493 Py_BEGIN_ALLOW_THREADS
494 errno = 0;
495 hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
496 ret = hFile == (HANDLE)-1;
497 if (ret == 0) {
498 ret = SetEndOfFile(hFile) == 0;
499 if (ret)
500 errno = EACCES;
501 }
502 Py_END_ALLOW_THREADS
503 if (ret)
504 goto onioerror;
505 }
506#else
507 Py_BEGIN_ALLOW_THREADS
508 errno = 0;
509 ret = ftruncate(self->fd, length);
510 Py_END_ALLOW_THREADS
511#endif /* !MS_WINDOWS */
512
513 if (ret < 0) {
514 onioerror:
515 PyErr_SetFromErrno(PyExc_IOError);
516 return NULL;
517 }
518
519 /* Return to initial position */
520 Py_BEGIN_ALLOW_THREADS
521 errno = 0;
522 ret = lseek(self->fd, length, SEEK_SET);
523 Py_END_ALLOW_THREADS
524 if (ret < 0)
525 goto onioerror;
526
527 Py_RETURN_NONE;
528}
529#endif
530
531static PyObject *
532fileio_repr(PyFileIOObject *self)
533{
534 PyObject *ret = NULL;
535
536 ret = PyString_FromFormat("<%s file at %p>",
537 self->fd < 0 ? "closed" : "open",
538 self);
539 return ret;
540}
541
542static PyObject *
543fileio_isatty(PyFileIOObject *self)
544{
545 long res;
546
547 if (self->fd < 0)
548 return err_closed();
549 Py_BEGIN_ALLOW_THREADS
550 res = isatty(self->fd);
551 Py_END_ALLOW_THREADS
552 return PyBool_FromLong(res);
553}
554
555static PyObject *
556fileio_self(PyFileIOObject *self)
557{
558 if (self->fd < 0)
559 return err_closed();
560 Py_INCREF(self);
561 return (PyObject *)self;
562}
563
564PyDoc_STRVAR(fileio_doc,
565"file(name: str[, mode: str]) -> file IO object\n"
566"\n"
567"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
568"writing or appending. The file will be created if it doesn't exist\n"
569"when opened for writing or appending; it will be truncated when\n"
570"opened for writing. Add a '+' to the mode to allow simultaneous\n"
571"reading and writing.");
572
573PyDoc_STRVAR(read_doc,
574"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
575"\n"
576"Only makes one system call, so less data may be returned than requested\n"
577"In non-blocking mode, returns None if no data is available. On\n"
578"end-of-file, returns 0.");
579
580PyDoc_STRVAR(write_doc,
581"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
582"\n"
583"Only makes one system call, so not all of the data may be written.\n"
584"The number of bytes actually written is returned.");
585
586PyDoc_STRVAR(fileno_doc,
587"fileno() -> int. \"file descriptor\".\n"
588"\n"
589"This is needed for lower-level file interfaces, such the fcntl module.");
590
591PyDoc_STRVAR(seek_doc,
592"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
593"\n"
594"Argument offset is a byte count. Optional argument whence defaults to\n"
595"0 (offset from start of file, offset should be >= 0); other values are 1\n"
596"(move relative to current position, positive or negative), and 2 (move\n"
597"relative to end of file, usually negative, although many platforms allow\n"
598"seeking beyond the end of a file)."
599"\n"
600"Note that not all file objects are seekable.");
601
602PyDoc_STRVAR(truncate_doc,
603"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
604"\n"
605"Size defaults to the current file position, as returned by tell().");
606
607PyDoc_STRVAR(tell_doc,
608"tell() -> int. Current file position");
609
610PyDoc_STRVAR(readinto_doc,
611"readinto() -> Undocumented. Don't use this; it may go away.");
612
613PyDoc_STRVAR(close_doc,
614"close() -> None. Close the file.\n"
615"\n"
616"A closed file cannot be used for further I/O operations. close() may be\n"
617"called more than once without error. Changes the fileno to -1.");
618
619PyDoc_STRVAR(isatty_doc,
620"isatty() -> bool. True if the file is connected to a tty device.");
621
622PyDoc_STRVAR(enter_doc,
623"__enter__() -> self.");
624
625PyDoc_STRVAR(exit_doc,
626"__exit__(*excinfo) -> None. Closes the file.");
627
628PyDoc_STRVAR(seekable_doc,
629"seekable() -> bool. True if file supports random-access.");
630
631PyDoc_STRVAR(readable_doc,
632"readable() -> bool. True if file was opened in a read mode.");
633
634PyDoc_STRVAR(writable_doc,
635"writable() -> bool. True if file was opened in a write mode.");
636
637static PyMethodDef fileio_methods[] = {
638 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
639 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
640 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
641 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
642 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
643 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
644 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
645 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
646 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
647 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
648 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
649 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
650 {"__enter__",(PyCFunction)fileio_self, METH_NOARGS, enter_doc},
651 {"__exit__", (PyCFunction)fileio_close, METH_VARARGS, exit_doc},
652 {NULL, NULL} /* sentinel */
653};
654
655PyTypeObject PyFileIO_Type = {
656 PyObject_HEAD_INIT(&PyType_Type)
657 0,
658 "FileIO",
659 sizeof(PyFileIOObject),
660 0,
661 (destructor)fileio_dealloc, /* tp_dealloc */
662 0, /* tp_print */
663 0, /* tp_getattr */
664 0, /* tp_setattr */
665 0, /* tp_compare */
666 (reprfunc)fileio_repr, /* tp_repr */
667 0, /* tp_as_number */
668 0, /* tp_as_sequence */
669 0, /* tp_as_mapping */
670 0, /* tp_hash */
671 0, /* tp_call */
672 0, /* tp_str */
673 PyObject_GenericGetAttr, /* tp_getattro */
674 0, /* tp_setattro */
675 0, /* tp_as_buffer */
676 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
677 fileio_doc, /* tp_doc */
678 0, /* tp_traverse */
679 0, /* tp_clear */
680 0, /* tp_richcompare */
681 offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */
682 0, /* tp_iter */
683 0, /* tp_iternext */
684 fileio_methods, /* tp_methods */
685 0, /* tp_members */
686 0, /* tp_getset */
687 0, /* tp_base */
688 0, /* tp_dict */
689 0, /* tp_descr_get */
690 0, /* tp_descr_set */
691 0, /* tp_dictoffset */
692 fileio_init, /* tp_init */
693 PyType_GenericAlloc, /* tp_alloc */
694 fileio_new, /* tp_new */
695 PyObject_Del, /* tp_free */
696};
697
698static PyMethodDef module_methods[] = {
699 {NULL, NULL}
700};
701
702PyMODINIT_FUNC
703init_fileio(void)
704{
705 PyObject *m; /* a module object */
706
707 m = Py_InitModule3("_fileio", module_methods,
708 "Fast implementation of io.FileIO.");
709 if (m == NULL)
710 return;
711 if (PyType_Ready(&PyFileIO_Type) < 0)
712 return;
713 Py_INCREF(&PyFileIO_Type);
714 PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type);
715}