blob: 917ad639ec948c549365c50cdd5d2987ff59125d [file] [log] [blame]
Christian Heimes7f39c9f2008-01-25 12:18:43 +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 */
Antoine Pitrou19690592009-06-12 20:14:08 +00009#include "_iomodule.h"
Christian Heimes7f39c9f2008-01-25 12:18:43 +000010
11/*
12 * Known likely problems:
13 *
14 * - Files larger then 2**32-1
15 * - Files with unicode filenames
16 * - Passing numbers greater than 2**32-1 when an integer is expected
17 * - Making it work on Windows and other oddball platforms
18 *
19 * To Do:
20 *
21 * - autoconfify header file inclusion
22 */
23
24#ifdef MS_WINDOWS
25/* can simulate truncate with Win32 API functions; see file_truncate */
26#define HAVE_FTRUNCATE
27#define WIN32_LEAN_AND_MEAN
28#include <windows.h>
29#endif
30
Antoine Pitrou19690592009-06-12 20:14:08 +000031#if BUFSIZ < (8*1024)
32#define SMALLCHUNK (8*1024)
33#elif (BUFSIZ >= (2 << 25))
34#error "unreasonable BUFSIZ > 64MB defined"
35#else
36#define SMALLCHUNK BUFSIZ
37#endif
38
39#if SIZEOF_INT < 4
40#define BIGCHUNK (512 * 32)
41#else
42#define BIGCHUNK (512 * 1024)
43#endif
44
Christian Heimes7f39c9f2008-01-25 12:18:43 +000045typedef struct {
46 PyObject_HEAD
47 int fd;
48 unsigned readable : 1;
49 unsigned writable : 1;
50 int seekable : 2; /* -1 means unknown */
51 int closefd : 1;
52 PyObject *weakreflist;
Antoine Pitrou19690592009-06-12 20:14:08 +000053 PyObject *dict;
54} fileio;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000055
56PyTypeObject PyFileIO_Type;
57
58#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
59
Antoine Pitrou19690592009-06-12 20:14:08 +000060int
61_PyFileIO_closed(PyObject *self)
62{
63 return ((fileio *)self)->fd < 0;
64}
65
Antoine Pitroue741cc62009-01-21 00:45:36 +000066static PyObject *
67portable_lseek(int fd, PyObject *posobj, int whence);
68
Antoine Pitrou19690592009-06-12 20:14:08 +000069static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
70
71/* Returns 0 on success, -1 with exception set on failure. */
Christian Heimes7f39c9f2008-01-25 12:18:43 +000072static int
Antoine Pitrou19690592009-06-12 20:14:08 +000073internal_close(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +000074{
Antoine Pitrou19690592009-06-12 20:14:08 +000075 int err = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000076 int save_errno = 0;
77 if (self->fd >= 0) {
78 int fd = self->fd;
79 self->fd = -1;
Antoine Pitrou19690592009-06-12 20:14:08 +000080 /* fd is accessible and someone else may have closed it */
81 if (_PyVerify_fd(fd)) {
82 Py_BEGIN_ALLOW_THREADS
83 err = close(fd);
84 if (err < 0)
85 save_errno = errno;
86 Py_END_ALLOW_THREADS
87 } else {
Christian Heimes7f39c9f2008-01-25 12:18:43 +000088 save_errno = errno;
Antoine Pitrou19690592009-06-12 20:14:08 +000089 err = -1;
90 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +000091 }
Antoine Pitrou19690592009-06-12 20:14:08 +000092 if (err < 0) {
93 errno = save_errno;
94 PyErr_SetFromErrno(PyExc_IOError);
95 return -1;
96 }
97 return 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000098}
99
100static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000101fileio_close(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000102{
103 if (!self->closefd) {
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +0000104 self->fd = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000105 Py_RETURN_NONE;
106 }
107 errno = internal_close(self);
Antoine Pitrou19690592009-06-12 20:14:08 +0000108 if (errno < 0)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000109 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000110
Antoine Pitrou19690592009-06-12 20:14:08 +0000111 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
112 "close", "O", self);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000113}
114
115static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000116fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000117{
Antoine Pitrou19690592009-06-12 20:14:08 +0000118 fileio *self;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000119
120 assert(type != NULL && type->tp_alloc != NULL);
121
Antoine Pitrou19690592009-06-12 20:14:08 +0000122 self = (fileio *) type->tp_alloc(type, 0);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000123 if (self != NULL) {
124 self->fd = -1;
Christian Heimesab5f8792008-10-30 21:26:15 +0000125 self->readable = 0;
126 self->writable = 0;
127 self->seekable = -1;
128 self->closefd = 1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000129 self->weakreflist = NULL;
130 }
131
132 return (PyObject *) self;
133}
134
135/* On Unix, open will succeed for directories.
136 In Python, there should be no file objects referring to
137 directories, so we need a check. */
138
139static int
Antoine Pitrou19690592009-06-12 20:14:08 +0000140dircheck(fileio* self, const char *name)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000141{
142#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
143 struct stat buf;
144 if (self->fd < 0)
145 return 0;
146 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000147 char *msg = strerror(EISDIR);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000148 PyObject *exc;
Antoine Pitrou19690592009-06-12 20:14:08 +0000149 if (internal_close(self))
150 return -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000151
Benjamin Peterson7af65562008-12-29 17:56:58 +0000152 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
153 EISDIR, msg, name);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000154 PyErr_SetObject(PyExc_IOError, exc);
155 Py_XDECREF(exc);
156 return -1;
157 }
158#endif
159 return 0;
160}
161
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000162static int
163check_fd(int fd)
164{
165#if defined(HAVE_FSTAT)
166 struct stat buf;
Kristján Valur Jónsson6a743d32009-02-10 13:32:24 +0000167 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000168 PyObject *exc;
169 char *msg = strerror(EBADF);
170 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
171 EBADF, msg);
172 PyErr_SetObject(PyExc_OSError, exc);
173 Py_XDECREF(exc);
174 return -1;
175 }
176#endif
177 return 0;
178}
179
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000180
181static int
182fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
183{
Antoine Pitrou19690592009-06-12 20:14:08 +0000184 fileio *self = (fileio *) oself;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000185 static char *kwlist[] = {"file", "mode", "closefd", NULL};
Antoine Pitrou19690592009-06-12 20:14:08 +0000186 const char *name = NULL;
187 PyObject *nameobj, *stringobj = NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000188 char *mode = "r";
189 char *s;
190#ifdef MS_WINDOWS
191 Py_UNICODE *widename = NULL;
192#endif
193 int ret = 0;
194 int rwa = 0, plus = 0, append = 0;
195 int flags = 0;
196 int fd = -1;
197 int closefd = 1;
198
199 assert(PyFileIO_Check(oself));
200 if (self->fd >= 0) {
201 /* Have to close the existing file first. */
202 if (internal_close(self) < 0)
203 return -1;
204 }
205
Antoine Pitrou19690592009-06-12 20:14:08 +0000206 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
207 kwlist, &nameobj, &mode, &closefd))
208 return -1;
209
210 if (PyFloat_Check(nameobj)) {
211 PyErr_SetString(PyExc_TypeError,
212 "integer argument expected, got float");
213 return -1;
214 }
215
216 fd = PyLong_AsLong(nameobj);
217 if (fd < 0) {
218 if (!PyErr_Occurred()) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000219 PyErr_SetString(PyExc_ValueError,
220 "Negative filedescriptor");
221 return -1;
222 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000223 PyErr_Clear();
Antoine Pitrou19690592009-06-12 20:14:08 +0000224 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000225
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +0000226#ifdef MS_WINDOWS
Antoine Pitrou19690592009-06-12 20:14:08 +0000227 if (GetVersion() < 0x80000000) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000228 /* On NT, so wide API available */
Antoine Pitrou19690592009-06-12 20:14:08 +0000229 if (PyUnicode_Check(nameobj))
230 widename = PyUnicode_AS_UNICODE(nameobj);
231 }
232 if (widename == NULL)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000233#endif
Antoine Pitrou19690592009-06-12 20:14:08 +0000234 if (fd < 0)
235 {
236 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
237 Py_ssize_t namelen;
238 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
239 return -1;
240 }
241 else {
242 PyObject *u = PyUnicode_FromObject(nameobj);
243
244 if (u == NULL)
245 return -1;
246
247 stringobj = PyUnicode_AsEncodedString(
248 u, Py_FileSystemDefaultEncoding, "surrogateescape");
249 Py_DECREF(u);
250 if (stringobj == NULL)
251 return -1;
252 if (!PyBytes_Check(stringobj)) {
253 PyErr_SetString(PyExc_TypeError,
254 "encoder failed to return bytes");
255 goto error;
256 }
257 name = PyBytes_AS_STRING(stringobj);
258 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000259 }
260
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000261 s = mode;
262 while (*s) {
263 switch (*s++) {
264 case 'r':
265 if (rwa) {
266 bad_mode:
267 PyErr_SetString(PyExc_ValueError,
268 "Must have exactly one of read/write/append mode");
269 goto error;
270 }
271 rwa = 1;
272 self->readable = 1;
273 break;
274 case 'w':
275 if (rwa)
276 goto bad_mode;
277 rwa = 1;
278 self->writable = 1;
279 flags |= O_CREAT | O_TRUNC;
280 break;
281 case 'a':
282 if (rwa)
283 goto bad_mode;
284 rwa = 1;
285 self->writable = 1;
286 flags |= O_CREAT;
287 append = 1;
288 break;
Benjamin Petersonbfc51562008-11-22 01:59:15 +0000289 case 'b':
290 break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000291 case '+':
292 if (plus)
293 goto bad_mode;
294 self->readable = self->writable = 1;
295 plus = 1;
296 break;
297 default:
298 PyErr_Format(PyExc_ValueError,
299 "invalid mode: %.200s", mode);
300 goto error;
301 }
302 }
303
304 if (!rwa)
305 goto bad_mode;
306
307 if (self->readable && self->writable)
308 flags |= O_RDWR;
309 else if (self->readable)
310 flags |= O_RDONLY;
311 else
312 flags |= O_WRONLY;
313
314#ifdef O_BINARY
315 flags |= O_BINARY;
316#endif
317
318#ifdef O_APPEND
319 if (append)
320 flags |= O_APPEND;
321#endif
322
323 if (fd >= 0) {
Antoine Pitrou19690592009-06-12 20:14:08 +0000324 if (check_fd(fd))
325 goto error;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000326 self->fd = fd;
327 self->closefd = closefd;
328 }
329 else {
330 self->closefd = 1;
331 if (!closefd) {
332 PyErr_SetString(PyExc_ValueError,
Amaury Forgeot d'Arc9f616f42008-10-29 23:15:57 +0000333 "Cannot use closefd=False with file name");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000334 goto error;
335 }
336
337 Py_BEGIN_ALLOW_THREADS
338 errno = 0;
339#ifdef MS_WINDOWS
340 if (widename != NULL)
341 self->fd = _wopen(widename, flags, 0666);
342 else
343#endif
344 self->fd = open(name, flags, 0666);
345 Py_END_ALLOW_THREADS
Benjamin Petersonf22c26e2008-09-01 14:13:43 +0000346 if (self->fd < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000347#ifdef MS_WINDOWS
Hirokazu Yamamoto99a1b202009-01-01 15:45:39 +0000348 if (widename != NULL)
349 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
350 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000351#endif
Hirokazu Yamamoto99a1b202009-01-01 15:45:39 +0000352 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000353 goto error;
354 }
Benjamin Peterson7af65562008-12-29 17:56:58 +0000355 if(dircheck(self, name) < 0)
Benjamin Petersonf22c26e2008-09-01 14:13:43 +0000356 goto error;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000357 }
358
Antoine Pitrou19690592009-06-12 20:14:08 +0000359 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
360 goto error;
361
Antoine Pitroue741cc62009-01-21 00:45:36 +0000362 if (append) {
363 /* For consistent behaviour, we explicitly seek to the
364 end of file (otherwise, it might be done only on the
365 first write()). */
366 PyObject *pos = portable_lseek(self->fd, NULL, 2);
367 if (pos == NULL)
368 goto error;
369 Py_DECREF(pos);
370 }
371
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000372 goto done;
373
374 error:
375 ret = -1;
376
377 done:
Antoine Pitrou19690592009-06-12 20:14:08 +0000378 Py_CLEAR(stringobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000379 return ret;
380}
381
Antoine Pitrou19690592009-06-12 20:14:08 +0000382static int
383fileio_traverse(fileio *self, visitproc visit, void *arg)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000384{
Antoine Pitrou19690592009-06-12 20:14:08 +0000385 Py_VISIT(self->dict);
386 return 0;
387}
388
389static int
390fileio_clear(fileio *self)
391{
392 Py_CLEAR(self->dict);
393 return 0;
394}
395
396static void
397fileio_dealloc(fileio *self)
398{
399 if (_PyIOBase_finalize((PyObject *) self) < 0)
400 return;
401 _PyObject_GC_UNTRACK(self);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000402 if (self->weakreflist != NULL)
403 PyObject_ClearWeakRefs((PyObject *) self);
Antoine Pitrou19690592009-06-12 20:14:08 +0000404 Py_CLEAR(self->dict);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000405 Py_TYPE(self)->tp_free((PyObject *)self);
406}
407
408static PyObject *
409err_closed(void)
410{
411 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
412 return NULL;
413}
414
415static PyObject *
416err_mode(char *action)
417{
418 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
419 return NULL;
420}
421
422static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000423fileio_fileno(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000424{
425 if (self->fd < 0)
426 return err_closed();
427 return PyInt_FromLong((long) self->fd);
428}
429
430static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000431fileio_readable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000432{
433 if (self->fd < 0)
434 return err_closed();
435 return PyBool_FromLong((long) self->readable);
436}
437
438static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000439fileio_writable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000440{
441 if (self->fd < 0)
442 return err_closed();
443 return PyBool_FromLong((long) self->writable);
444}
445
446static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000447fileio_seekable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000448{
449 if (self->fd < 0)
450 return err_closed();
451 if (self->seekable < 0) {
Antoine Pitrou19690592009-06-12 20:14:08 +0000452 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
453 if (pos == NULL) {
454 PyErr_Clear();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000455 self->seekable = 0;
Antoine Pitrou19690592009-06-12 20:14:08 +0000456 } else {
457 Py_DECREF(pos);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000458 self->seekable = 1;
Antoine Pitrou19690592009-06-12 20:14:08 +0000459 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000460 }
461 return PyBool_FromLong((long) self->seekable);
462}
463
464static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000465fileio_readinto(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000466{
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000467 Py_buffer pbuf;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000468 Py_ssize_t n;
469
470 if (self->fd < 0)
471 return err_closed();
472 if (!self->readable)
473 return err_mode("reading");
474
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000475 if (!PyArg_ParseTuple(args, "w*", &pbuf))
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000476 return NULL;
477
Antoine Pitrou19690592009-06-12 20:14:08 +0000478 if (_PyVerify_fd(self->fd)) {
479 Py_BEGIN_ALLOW_THREADS
480 errno = 0;
481 n = read(self->fd, pbuf.buf, pbuf.len);
482 Py_END_ALLOW_THREADS
483 } else
484 n = -1;
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000485 PyBuffer_Release(&pbuf);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000486 if (n < 0) {
487 if (errno == EAGAIN)
488 Py_RETURN_NONE;
489 PyErr_SetFromErrno(PyExc_IOError);
490 return NULL;
491 }
492
493 return PyLong_FromSsize_t(n);
494}
495
Antoine Pitrou19690592009-06-12 20:14:08 +0000496static size_t
497new_buffersize(fileio *self, size_t currentsize)
498{
499#ifdef HAVE_FSTAT
500 off_t pos, end;
501 struct stat st;
502 if (fstat(self->fd, &st) == 0) {
503 end = st.st_size;
504 pos = lseek(self->fd, 0L, SEEK_CUR);
505 /* Files claiming a size smaller than SMALLCHUNK may
506 actually be streaming pseudo-files. In this case, we
507 apply the more aggressive algorithm below.
508 */
509 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
510 /* Add 1 so if the file were to grow we'd notice. */
511 return currentsize + end - pos + 1;
512 }
513 }
514#endif
515 if (currentsize > SMALLCHUNK) {
516 /* Keep doubling until we reach BIGCHUNK;
517 then keep adding BIGCHUNK. */
518 if (currentsize <= BIGCHUNK)
519 return currentsize + currentsize;
520 else
521 return currentsize + BIGCHUNK;
522 }
523 return currentsize + SMALLCHUNK;
524}
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000525
526static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000527fileio_readall(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000528{
529 PyObject *result;
530 Py_ssize_t total = 0;
531 int n;
532
Antoine Pitrou19690592009-06-12 20:14:08 +0000533 if (!_PyVerify_fd(self->fd))
534 return PyErr_SetFromErrno(PyExc_IOError);
535
536 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000537 if (result == NULL)
538 return NULL;
539
540 while (1) {
Antoine Pitrou19690592009-06-12 20:14:08 +0000541 size_t newsize = new_buffersize(self, total);
542 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
543 PyErr_SetString(PyExc_OverflowError,
544 "unbounded read returned more bytes "
545 "than a Python string can hold ");
546 Py_DECREF(result);
547 return NULL;
548 }
549
550 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
551 if (_PyBytes_Resize(&result, newsize) < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000552 if (total == 0) {
553 Py_DECREF(result);
554 return NULL;
555 }
556 PyErr_Clear();
557 break;
558 }
559 }
560 Py_BEGIN_ALLOW_THREADS
561 errno = 0;
562 n = read(self->fd,
Antoine Pitrou19690592009-06-12 20:14:08 +0000563 PyBytes_AS_STRING(result) + total,
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000564 newsize - total);
565 Py_END_ALLOW_THREADS
566 if (n == 0)
567 break;
568 if (n < 0) {
569 if (total > 0)
570 break;
571 if (errno == EAGAIN) {
572 Py_DECREF(result);
573 Py_RETURN_NONE;
574 }
575 Py_DECREF(result);
576 PyErr_SetFromErrno(PyExc_IOError);
577 return NULL;
578 }
579 total += n;
580 }
581
Antoine Pitrou19690592009-06-12 20:14:08 +0000582 if (PyBytes_GET_SIZE(result) > total) {
583 if (_PyBytes_Resize(&result, total) < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000584 /* This should never happen, but just in case */
585 Py_DECREF(result);
586 return NULL;
587 }
588 }
589 return result;
590}
591
592static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000593fileio_read(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000594{
595 char *ptr;
596 Py_ssize_t n;
597 Py_ssize_t size = -1;
598 PyObject *bytes;
599
600 if (self->fd < 0)
601 return err_closed();
602 if (!self->readable)
603 return err_mode("reading");
604
605 if (!PyArg_ParseTuple(args, "|n", &size))
606 return NULL;
607
608 if (size < 0) {
609 return fileio_readall(self);
610 }
611
Antoine Pitrou19690592009-06-12 20:14:08 +0000612 bytes = PyBytes_FromStringAndSize(NULL, size);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000613 if (bytes == NULL)
614 return NULL;
Antoine Pitrou19690592009-06-12 20:14:08 +0000615 ptr = PyBytes_AS_STRING(bytes);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000616
Antoine Pitrou19690592009-06-12 20:14:08 +0000617 if (_PyVerify_fd(self->fd)) {
618 Py_BEGIN_ALLOW_THREADS
619 errno = 0;
620 n = read(self->fd, ptr, size);
621 Py_END_ALLOW_THREADS
622 } else
623 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000624
625 if (n < 0) {
Antoine Pitrou19690592009-06-12 20:14:08 +0000626 Py_DECREF(bytes);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000627 if (errno == EAGAIN)
628 Py_RETURN_NONE;
629 PyErr_SetFromErrno(PyExc_IOError);
630 return NULL;
631 }
632
633 if (n != size) {
Antoine Pitrou19690592009-06-12 20:14:08 +0000634 if (_PyBytes_Resize(&bytes, n) < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000635 Py_DECREF(bytes);
636 return NULL;
637 }
638 }
639
640 return (PyObject *) bytes;
641}
642
643static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000644fileio_write(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000645{
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000646 Py_buffer pbuf;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000647 Py_ssize_t n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000648
649 if (self->fd < 0)
650 return err_closed();
651 if (!self->writable)
652 return err_mode("writing");
653
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000654 if (!PyArg_ParseTuple(args, "s*", &pbuf))
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000655 return NULL;
656
Antoine Pitrou19690592009-06-12 20:14:08 +0000657 if (_PyVerify_fd(self->fd)) {
658 Py_BEGIN_ALLOW_THREADS
659 errno = 0;
660 n = write(self->fd, pbuf.buf, pbuf.len);
661 Py_END_ALLOW_THREADS
662 } else
663 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000664
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000665 PyBuffer_Release(&pbuf);
666
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000667 if (n < 0) {
668 if (errno == EAGAIN)
669 Py_RETURN_NONE;
670 PyErr_SetFromErrno(PyExc_IOError);
671 return NULL;
672 }
673
674 return PyLong_FromSsize_t(n);
675}
676
677/* XXX Windows support below is likely incomplete */
678
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000679/* Cribbed from posix_lseek() */
680static PyObject *
681portable_lseek(int fd, PyObject *posobj, int whence)
682{
683 Py_off_t pos, res;
684
685#ifdef SEEK_SET
686 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
687 switch (whence) {
688#if SEEK_SET != 0
689 case 0: whence = SEEK_SET; break;
690#endif
691#if SEEK_CUR != 1
692 case 1: whence = SEEK_CUR; break;
693#endif
Benjamin Peterson8024cec2009-01-20 14:31:08 +0000694#if SEEK_END != 2
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000695 case 2: whence = SEEK_END; break;
696#endif
697 }
698#endif /* SEEK_SET */
699
700 if (posobj == NULL)
701 pos = 0;
702 else {
703 if(PyFloat_Check(posobj)) {
704 PyErr_SetString(PyExc_TypeError, "an integer is required");
705 return NULL;
706 }
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000707#if defined(HAVE_LARGEFILE_SUPPORT)
708 pos = PyLong_AsLongLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000709#else
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000710 pos = PyLong_AsLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000711#endif
712 if (PyErr_Occurred())
713 return NULL;
714 }
715
Antoine Pitrou19690592009-06-12 20:14:08 +0000716 if (_PyVerify_fd(fd)) {
717 Py_BEGIN_ALLOW_THREADS
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000718#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrou19690592009-06-12 20:14:08 +0000719 res = _lseeki64(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000720#else
Antoine Pitrou19690592009-06-12 20:14:08 +0000721 res = lseek(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000722#endif
Antoine Pitrou19690592009-06-12 20:14:08 +0000723 Py_END_ALLOW_THREADS
724 } else
725 res = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000726 if (res < 0)
727 return PyErr_SetFromErrno(PyExc_IOError);
728
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000729#if defined(HAVE_LARGEFILE_SUPPORT)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000730 return PyLong_FromLongLong(res);
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000731#else
732 return PyLong_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000733#endif
734}
735
736static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000737fileio_seek(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000738{
739 PyObject *posobj;
740 int whence = 0;
741
742 if (self->fd < 0)
743 return err_closed();
744
745 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
746 return NULL;
747
748 return portable_lseek(self->fd, posobj, whence);
749}
750
751static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000752fileio_tell(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000753{
754 if (self->fd < 0)
755 return err_closed();
756
757 return portable_lseek(self->fd, NULL, 1);
758}
759
760#ifdef HAVE_FTRUNCATE
761static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000762fileio_truncate(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000763{
764 PyObject *posobj = NULL;
765 Py_off_t pos;
766 int ret;
767 int fd;
768
769 fd = self->fd;
770 if (fd < 0)
771 return err_closed();
772 if (!self->writable)
773 return err_mode("writing");
774
775 if (!PyArg_ParseTuple(args, "|O", &posobj))
776 return NULL;
777
778 if (posobj == Py_None || posobj == NULL) {
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000779 /* Get the current position. */
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000780 posobj = portable_lseek(fd, NULL, 1);
781 if (posobj == NULL)
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000782 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000783 }
784 else {
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000785 /* Move to the position to be truncated. */
786 posobj = portable_lseek(fd, posobj, 0);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000787 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000788 if (posobj == NULL)
789 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000790
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000791#if defined(HAVE_LARGEFILE_SUPPORT)
792 pos = PyLong_AsLongLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000793#else
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000794 pos = PyLong_AsLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000795#endif
Antoine Pitrou19690592009-06-12 20:14:08 +0000796 if (pos == -1 && PyErr_Occurred())
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000797 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000798
799#ifdef MS_WINDOWS
800 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
801 so don't even try using it. */
802 {
803 HANDLE hFile;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000804
805 /* Truncate. Note that this may grow the file! */
806 Py_BEGIN_ALLOW_THREADS
807 errno = 0;
808 hFile = (HANDLE)_get_osfhandle(fd);
809 ret = hFile == (HANDLE)-1;
810 if (ret == 0) {
811 ret = SetEndOfFile(hFile) == 0;
812 if (ret)
813 errno = EACCES;
814 }
815 Py_END_ALLOW_THREADS
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000816 }
817#else
818 Py_BEGIN_ALLOW_THREADS
819 errno = 0;
820 ret = ftruncate(fd, pos);
821 Py_END_ALLOW_THREADS
822#endif /* !MS_WINDOWS */
823
824 if (ret != 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000825 PyErr_SetFromErrno(PyExc_IOError);
826 return NULL;
827 }
828
829 return posobj;
830}
831#endif
832
833static char *
Antoine Pitrou19690592009-06-12 20:14:08 +0000834mode_string(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000835{
836 if (self->readable) {
837 if (self->writable)
Benjamin Petersonbfc51562008-11-22 01:59:15 +0000838 return "rb+";
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000839 else
Benjamin Petersonbfc51562008-11-22 01:59:15 +0000840 return "rb";
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000841 }
842 else
Benjamin Petersonbfc51562008-11-22 01:59:15 +0000843 return "wb";
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000844}
845
846static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000847fileio_repr(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000848{
Antoine Pitrou19690592009-06-12 20:14:08 +0000849 PyObject *nameobj, *res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000850
Antoine Pitrou19690592009-06-12 20:14:08 +0000851 if (self->fd < 0)
852 return PyString_FromFormat("<_io.FileIO [closed]>");
853
854 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
855 if (nameobj == NULL) {
856 if (PyErr_ExceptionMatches(PyExc_AttributeError))
857 PyErr_Clear();
858 else
859 return NULL;
860 res = PyString_FromFormat("<_io.FileIO fd=%d mode='%s'>",
861 self->fd, mode_string(self));
862 }
863 else {
864 PyObject *repr = PyObject_Repr(nameobj);
865 Py_DECREF(nameobj);
866 if (repr == NULL)
867 return NULL;
868 res = PyString_FromFormat("<_io.FileIO name=%s mode='%s'>",
869 PyString_AS_STRING(repr),
870 mode_string(self));
871 Py_DECREF(repr);
872 }
873 return res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000874}
875
876static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000877fileio_isatty(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000878{
879 long res;
880
881 if (self->fd < 0)
882 return err_closed();
883 Py_BEGIN_ALLOW_THREADS
884 res = isatty(self->fd);
885 Py_END_ALLOW_THREADS
886 return PyBool_FromLong(res);
887}
888
889
890PyDoc_STRVAR(fileio_doc,
891"file(name: str[, mode: str]) -> file IO object\n"
892"\n"
893"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
894"writing or appending. The file will be created if it doesn't exist\n"
895"when opened for writing or appending; it will be truncated when\n"
896"opened for writing. Add a '+' to the mode to allow simultaneous\n"
897"reading and writing.");
898
899PyDoc_STRVAR(read_doc,
900"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
901"\n"
902"Only makes one system call, so less data may be returned than requested\n"
903"In non-blocking mode, returns None if no data is available.\n"
904"On end-of-file, returns ''.");
905
906PyDoc_STRVAR(readall_doc,
907"readall() -> bytes. read all data from the file, returned as bytes.\n"
908"\n"
909"In non-blocking mode, returns as much as is immediately available,\n"
910"or None if no data is available. On end-of-file, returns ''.");
911
912PyDoc_STRVAR(write_doc,
913"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
914"\n"
915"Only makes one system call, so not all of the data may be written.\n"
916"The number of bytes actually written is returned.");
917
918PyDoc_STRVAR(fileno_doc,
919"fileno() -> int. \"file descriptor\".\n"
920"\n"
921"This is needed for lower-level file interfaces, such the fcntl module.");
922
923PyDoc_STRVAR(seek_doc,
924"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
925"\n"
926"Argument offset is a byte count. Optional argument whence defaults to\n"
927"0 (offset from start of file, offset should be >= 0); other values are 1\n"
928"(move relative to current position, positive or negative), and 2 (move\n"
929"relative to end of file, usually negative, although many platforms allow\n"
930"seeking beyond the end of a file)."
931"\n"
932"Note that not all file objects are seekable.");
933
934#ifdef HAVE_FTRUNCATE
935PyDoc_STRVAR(truncate_doc,
936"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
937"\n"
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000938"Size defaults to the current file position, as returned by tell()."
939"The current file position is changed to the value of size.");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000940#endif
941
942PyDoc_STRVAR(tell_doc,
943"tell() -> int. Current file position");
944
945PyDoc_STRVAR(readinto_doc,
Antoine Pitrou19690592009-06-12 20:14:08 +0000946"readinto() -> Same as RawIOBase.readinto().");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000947
948PyDoc_STRVAR(close_doc,
949"close() -> None. Close the file.\n"
950"\n"
951"A closed file cannot be used for further I/O operations. close() may be\n"
952"called more than once without error. Changes the fileno to -1.");
953
954PyDoc_STRVAR(isatty_doc,
955"isatty() -> bool. True if the file is connected to a tty device.");
956
957PyDoc_STRVAR(seekable_doc,
958"seekable() -> bool. True if file supports random-access.");
959
960PyDoc_STRVAR(readable_doc,
961"readable() -> bool. True if file was opened in a read mode.");
962
963PyDoc_STRVAR(writable_doc,
964"writable() -> bool. True if file was opened in a write mode.");
965
966static PyMethodDef fileio_methods[] = {
967 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
968 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
969 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
970 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
971 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
972 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
973#ifdef HAVE_FTRUNCATE
974 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
975#endif
976 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
977 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
978 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
979 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
980 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
981 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
982 {NULL, NULL} /* sentinel */
983};
984
985/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
986
987static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000988get_closed(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000989{
990 return PyBool_FromLong((long)(self->fd < 0));
991}
992
993static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000994get_closefd(fileio *self, void *closure)
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +0000995{
996 return PyBool_FromLong((long)(self->closefd));
997}
998
999static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001000get_mode(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001001{
Antoine Pitrou19690592009-06-12 20:14:08 +00001002 return PyUnicode_FromString(mode_string(self));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001003}
1004
1005static PyGetSetDef fileio_getsetlist[] = {
1006 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001007 {"closefd", (getter)get_closefd, NULL,
1008 "True if the file descriptor will be closed"},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001009 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
Antoine Pitrou19690592009-06-12 20:14:08 +00001010 {NULL},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001011};
1012
1013PyTypeObject PyFileIO_Type = {
Hirokazu Yamamoto09979a12008-09-23 16:11:09 +00001014 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou19690592009-06-12 20:14:08 +00001015 "_io.FileIO",
1016 sizeof(fileio),
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001017 0,
1018 (destructor)fileio_dealloc, /* tp_dealloc */
1019 0, /* tp_print */
1020 0, /* tp_getattr */
1021 0, /* tp_setattr */
Antoine Pitrou19690592009-06-12 20:14:08 +00001022 0, /* tp_reserved */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001023 (reprfunc)fileio_repr, /* tp_repr */
1024 0, /* tp_as_number */
1025 0, /* tp_as_sequence */
1026 0, /* tp_as_mapping */
1027 0, /* tp_hash */
1028 0, /* tp_call */
1029 0, /* tp_str */
1030 PyObject_GenericGetAttr, /* tp_getattro */
1031 0, /* tp_setattro */
1032 0, /* tp_as_buffer */
Antoine Pitrou19690592009-06-12 20:14:08 +00001033 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1034 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001035 fileio_doc, /* tp_doc */
Antoine Pitrou19690592009-06-12 20:14:08 +00001036 (traverseproc)fileio_traverse, /* tp_traverse */
1037 (inquiry)fileio_clear, /* tp_clear */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001038 0, /* tp_richcompare */
Antoine Pitrou19690592009-06-12 20:14:08 +00001039 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001040 0, /* tp_iter */
1041 0, /* tp_iternext */
1042 fileio_methods, /* tp_methods */
1043 0, /* tp_members */
1044 fileio_getsetlist, /* tp_getset */
1045 0, /* tp_base */
1046 0, /* tp_dict */
1047 0, /* tp_descr_get */
1048 0, /* tp_descr_set */
Antoine Pitrou19690592009-06-12 20:14:08 +00001049 offsetof(fileio, dict), /* tp_dictoffset */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001050 fileio_init, /* tp_init */
1051 PyType_GenericAlloc, /* tp_alloc */
1052 fileio_new, /* tp_new */
Antoine Pitrou19690592009-06-12 20:14:08 +00001053 PyObject_GC_Del, /* tp_free */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001054};