blob: a7fad360b18616e27a059c2243782d45a0822cb8 [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"
Antoine Pitroue033e062010-10-29 10:38:18 +00005#include "structmember.h"
Benjamin Peterson2614cda2010-03-21 22:36:19 +00006#ifdef HAVE_SYS_TYPES_H
Guido van Rossuma9e20242007-03-08 00:43:48 +00007#include <sys/types.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +00008#endif
9#ifdef HAVE_SYS_STAT_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000010#include <sys/stat.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000011#endif
12#ifdef HAVE_FCNTL_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000013#include <fcntl.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000014#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +000015#include <stddef.h> /* For offsetof */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000016#include "_iomodule.h"
Guido van Rossuma9e20242007-03-08 00:43:48 +000017
18/*
19 * Known likely problems:
20 *
21 * - Files larger then 2**32-1
22 * - Files with unicode filenames
23 * - Passing numbers greater than 2**32-1 when an integer is expected
24 * - Making it work on Windows and other oddball platforms
25 *
26 * To Do:
27 *
28 * - autoconfify header file inclusion
Guido van Rossuma9e20242007-03-08 00:43:48 +000029 */
30
31#ifdef MS_WINDOWS
32/* can simulate truncate with Win32 API functions; see file_truncate */
Thomas Hellerfdeee3a2007-07-12 11:21:36 +000033#define HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +000034#define WIN32_LEAN_AND_MEAN
35#include <windows.h>
36#endif
37
Christian Heimesa872de52008-12-05 08:26:55 +000038#if BUFSIZ < (8*1024)
39#define SMALLCHUNK (8*1024)
40#elif (BUFSIZ >= (2 << 25))
41#error "unreasonable BUFSIZ > 64MB defined"
42#else
43#define SMALLCHUNK BUFSIZ
44#endif
45
Guido van Rossuma9e20242007-03-08 00:43:48 +000046typedef struct {
Antoine Pitrouae4b4722010-05-05 16:31:07 +000047 PyObject_HEAD
48 int fd;
49 unsigned int readable : 1;
50 unsigned int writable : 1;
51 signed int seekable : 2; /* -1 means unknown */
52 unsigned int closefd : 1;
Antoine Pitroue033e062010-10-29 10:38:18 +000053 unsigned int deallocating: 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000054 PyObject *weakreflist;
55 PyObject *dict;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000056} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000057
Collin Winteraf334382007-03-08 21:46:15 +000058PyTypeObject PyFileIO_Type;
59
Guido van Rossuma9e20242007-03-08 00:43:48 +000060#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
61
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000062int
63_PyFileIO_closed(PyObject *self)
64{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000065 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000066}
Antoine Pitrou08838b62009-01-21 00:55:13 +000067
Antoine Pitroue033e062010-10-29 10:38:18 +000068/* Because this can call arbitrary code, it shouldn't be called when
69 the refcount is 0 (that is, not directly from tp_dealloc unless
70 the refcount has been temporarily re-incremented). */
71static PyObject *
72fileio_dealloc_warn(fileio *self, PyObject *source)
73{
74 if (self->fd >= 0 && self->closefd) {
75 PyObject *exc, *val, *tb;
76 PyErr_Fetch(&exc, &val, &tb);
77 if (PyErr_WarnFormat(PyExc_ResourceWarning, 1,
78 "unclosed file %R", source)) {
79 /* Spurious errors can appear at shutdown */
80 if (PyErr_ExceptionMatches(PyExc_Warning))
81 PyErr_WriteUnraisable((PyObject *) self);
82 }
83 PyErr_Restore(exc, val, tb);
84 }
85 Py_RETURN_NONE;
86}
87
Antoine Pitrou7fb111b2009-03-04 11:14:01 +000088static PyObject *
89portable_lseek(int fd, PyObject *posobj, int whence);
90
Antoine Pitroua28fcfd2009-03-13 23:42:55 +000091static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
92
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +000093/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +000094static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000095internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +000096{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000097 int err = 0;
98 int save_errno = 0;
99 if (self->fd >= 0) {
100 int fd = self->fd;
101 self->fd = -1;
102 /* fd is accessible and someone else may have closed it */
103 if (_PyVerify_fd(fd)) {
104 Py_BEGIN_ALLOW_THREADS
105 err = close(fd);
106 if (err < 0)
107 save_errno = errno;
108 Py_END_ALLOW_THREADS
109 } else {
110 save_errno = errno;
111 err = -1;
112 }
113 }
114 if (err < 0) {
115 errno = save_errno;
116 PyErr_SetFromErrno(PyExc_IOError);
117 return -1;
118 }
119 return 0;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000120}
121
122static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000123fileio_close(fileio *self)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000124{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000125 if (!self->closefd) {
126 self->fd = -1;
127 Py_RETURN_NONE;
128 }
Antoine Pitroue033e062010-10-29 10:38:18 +0000129 if (self->deallocating) {
130 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
131 if (r)
132 Py_DECREF(r);
133 else
134 PyErr_Clear();
135 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000136 errno = internal_close(self);
137 if (errno < 0)
138 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000139
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000140 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
141 "close", "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000142}
143
144static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000145fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000146{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000147 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000148
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000149 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000150
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000151 self = (fileio *) type->tp_alloc(type, 0);
152 if (self != NULL) {
153 self->fd = -1;
154 self->readable = 0;
155 self->writable = 0;
156 self->seekable = -1;
157 self->closefd = 1;
158 self->weakreflist = NULL;
159 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000160
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000161 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000162}
163
164/* On Unix, open will succeed for directories.
165 In Python, there should be no file objects referring to
166 directories, so we need a check. */
167
168static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000169dircheck(fileio* self, const char *name)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000170{
171#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000172 struct stat buf;
173 if (self->fd < 0)
174 return 0;
175 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
176 char *msg = strerror(EISDIR);
177 PyObject *exc;
178 if (internal_close(self))
179 return -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000180
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000181 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
182 EISDIR, msg, name);
183 PyErr_SetObject(PyExc_IOError, exc);
184 Py_XDECREF(exc);
185 return -1;
186 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000187#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000188 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000189}
190
Benjamin Peterson806d4022009-01-19 15:11:51 +0000191static int
192check_fd(int fd)
193{
194#if defined(HAVE_FSTAT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000195 struct stat buf;
196 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
197 PyObject *exc;
198 char *msg = strerror(EBADF);
199 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
200 EBADF, msg);
201 PyErr_SetObject(PyExc_OSError, exc);
202 Py_XDECREF(exc);
203 return -1;
204 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000205#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000206 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000207}
208
Guido van Rossuma9e20242007-03-08 00:43:48 +0000209
210static int
211fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
212{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000213 fileio *self = (fileio *) oself;
214 static char *kwlist[] = {"file", "mode", "closefd", NULL};
215 const char *name = NULL;
216 PyObject *nameobj, *stringobj = NULL;
217 char *mode = "r";
218 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000219#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000220 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000221#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000222 int ret = 0;
223 int rwa = 0, plus = 0, append = 0;
224 int flags = 0;
225 int fd = -1;
226 int closefd = 1;
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200227 int fd_is_own = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000228
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000229 assert(PyFileIO_Check(oself));
230 if (self->fd >= 0) {
Hynek Schlawack2cc71562012-05-25 10:05:53 +0200231 if (self->closefd) {
232 /* Have to close the existing file first. */
233 if (internal_close(self) < 0)
234 return -1;
235 }
236 else
237 self->fd = -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000238 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000239
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000240 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
241 kwlist, &nameobj, &mode, &closefd))
242 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000243
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000244 if (PyFloat_Check(nameobj)) {
245 PyErr_SetString(PyExc_TypeError,
246 "integer argument expected, got float");
247 return -1;
248 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000249
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000250 fd = PyLong_AsLong(nameobj);
251 if (fd < 0) {
252 if (!PyErr_Occurred()) {
253 PyErr_SetString(PyExc_ValueError,
254 "Negative filedescriptor");
255 return -1;
256 }
257 PyErr_Clear();
258 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000259
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000260#ifdef MS_WINDOWS
Antoine Pitrou13348842012-01-29 18:36:34 +0100261 if (PyUnicode_Check(nameobj)) {
262 int rv = _PyUnicode_HasNULChars(nameobj);
263 if (rv) {
264 if (rv != -1)
265 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
266 return -1;
267 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000268 widename = PyUnicode_AS_UNICODE(nameobj);
Antoine Pitrou13348842012-01-29 18:36:34 +0100269 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000270 if (widename == NULL)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000271#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000272 if (fd < 0)
273 {
Antoine Pitrou13348842012-01-29 18:36:34 +0100274 if (!PyUnicode_FSConverter(nameobj, &stringobj)) {
275 return -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000276 }
Antoine Pitrou13348842012-01-29 18:36:34 +0100277 name = PyBytes_AS_STRING(stringobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000278 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000279
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000280 s = mode;
281 while (*s) {
282 switch (*s++) {
283 case 'r':
284 if (rwa) {
285 bad_mode:
286 PyErr_SetString(PyExc_ValueError,
Georg Brandl28928ae2010-10-21 13:45:52 +0000287 "Must have exactly one of read/write/append "
288 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000289 goto error;
290 }
291 rwa = 1;
292 self->readable = 1;
293 break;
294 case 'w':
295 if (rwa)
296 goto bad_mode;
297 rwa = 1;
298 self->writable = 1;
299 flags |= O_CREAT | O_TRUNC;
300 break;
301 case 'a':
302 if (rwa)
303 goto bad_mode;
304 rwa = 1;
305 self->writable = 1;
306 flags |= O_CREAT;
307 append = 1;
308 break;
309 case 'b':
310 break;
311 case '+':
312 if (plus)
313 goto bad_mode;
314 self->readable = self->writable = 1;
315 plus = 1;
316 break;
317 default:
318 PyErr_Format(PyExc_ValueError,
319 "invalid mode: %.200s", mode);
320 goto error;
321 }
322 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000323
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000324 if (!rwa)
325 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000326
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000327 if (self->readable && self->writable)
328 flags |= O_RDWR;
329 else if (self->readable)
330 flags |= O_RDONLY;
331 else
332 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000333
334#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000335 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000336#endif
337
Walter Dörwald0e411482007-06-06 16:55:38 +0000338#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000339 if (append)
340 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000341#endif
342
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000343 if (fd >= 0) {
344 if (check_fd(fd))
345 goto error;
346 self->fd = fd;
347 self->closefd = closefd;
348 }
349 else {
350 self->closefd = 1;
351 if (!closefd) {
352 PyErr_SetString(PyExc_ValueError,
353 "Cannot use closefd=False with file name");
354 goto error;
355 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000356
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000357 Py_BEGIN_ALLOW_THREADS
358 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000359#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000360 if (widename != NULL)
361 self->fd = _wopen(widename, flags, 0666);
362 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000363#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000364 self->fd = open(name, flags, 0666);
365 Py_END_ALLOW_THREADS
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200366 fd_is_own = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000367 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000368#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000369 if (widename != NULL)
370 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
371 else
Christian Heimes0b489542007-10-31 19:20:48 +0000372#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000373 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
374 goto error;
375 }
Benjamin Peterson430d4692010-10-30 23:13:57 +0000376 if (dircheck(self, name) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000377 goto error;
378 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000379
Victor Stinner89e34362011-01-07 18:47:22 +0000380#if defined(MS_WINDOWS) || defined(__CYGWIN__)
381 /* don't translate newlines (\r\n <=> \n) */
382 _setmode(self->fd, O_BINARY);
383#endif
384
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000385 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
386 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000387
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000388 if (append) {
389 /* For consistent behaviour, we explicitly seek to the
390 end of file (otherwise, it might be done only on the
391 first write()). */
392 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200393 if (pos == NULL)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000394 goto error;
395 Py_DECREF(pos);
396 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000397
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000398 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000399
400 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000401 ret = -1;
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200402 if (!fd_is_own)
403 self->fd = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000404 if (self->fd >= 0)
405 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000406
Guido van Rossuma9e20242007-03-08 00:43:48 +0000407 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000408 Py_CLEAR(stringobj);
409 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000410}
411
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000412static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000413fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000414{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000415 Py_VISIT(self->dict);
416 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000417}
418
419static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000420fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000421{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000422 Py_CLEAR(self->dict);
423 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000424}
425
Guido van Rossuma9e20242007-03-08 00:43:48 +0000426static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000427fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000428{
Antoine Pitroue033e062010-10-29 10:38:18 +0000429 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000430 if (_PyIOBase_finalize((PyObject *) self) < 0)
431 return;
432 _PyObject_GC_UNTRACK(self);
433 if (self->weakreflist != NULL)
434 PyObject_ClearWeakRefs((PyObject *) self);
435 Py_CLEAR(self->dict);
436 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000437}
438
439static PyObject *
440err_closed(void)
441{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000442 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
443 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000444}
445
446static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000447err_mode(char *action)
448{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000449 PyErr_Format(IO_STATE->unsupported_operation,
450 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000451 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000452}
453
454static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000455fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000456{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000457 if (self->fd < 0)
458 return err_closed();
459 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000460}
461
462static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000463fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000464{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000465 if (self->fd < 0)
466 return err_closed();
467 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000468}
469
470static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000471fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000472{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000473 if (self->fd < 0)
474 return err_closed();
475 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000476}
477
478static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000479fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000480{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000481 if (self->fd < 0)
482 return err_closed();
483 if (self->seekable < 0) {
484 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
485 if (pos == NULL) {
486 PyErr_Clear();
487 self->seekable = 0;
488 } else {
489 Py_DECREF(pos);
490 self->seekable = 1;
491 }
492 }
493 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000494}
495
496static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000497fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000498{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000499 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000500 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100501 int err;
Guido van Rossum53807da2007-04-10 19:01:47 +0000502
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000503 if (self->fd < 0)
504 return err_closed();
505 if (!self->readable)
506 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000507
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000508 if (!PyArg_ParseTuple(args, "w*", &pbuf))
509 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000510
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000511 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000512 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000513 Py_BEGIN_ALLOW_THREADS
514 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000515#if defined(MS_WIN64) || defined(MS_WINDOWS)
516 if (len > INT_MAX)
517 len = INT_MAX;
518 n = read(self->fd, pbuf.buf, (int)len);
519#else
Victor Stinner72344792011-01-11 00:04:12 +0000520 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000521#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000522 Py_END_ALLOW_THREADS
523 } else
524 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100525 err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000526 PyBuffer_Release(&pbuf);
527 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100528 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000529 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100530 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000531 PyErr_SetFromErrno(PyExc_IOError);
532 return NULL;
533 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000534
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000535 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000536}
537
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000538static size_t
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000539new_buffersize(fileio *self, size_t currentsize)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000540{
541#ifdef HAVE_FSTAT
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000542 off_t pos, end;
543 struct stat st;
544 if (fstat(self->fd, &st) == 0) {
545 end = st.st_size;
546 pos = lseek(self->fd, 0L, SEEK_CUR);
547 /* Files claiming a size smaller than SMALLCHUNK may
548 actually be streaming pseudo-files. In this case, we
549 apply the more aggressive algorithm below.
550 */
551 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
552 /* Add 1 so if the file were to grow we'd notice. */
553 return currentsize + end - pos + 1;
554 }
555 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000556#endif
Nadeem Vawdad41a98b2011-10-13 13:34:16 +0200557 /* Expand the buffer by an amount proportional to the current size,
558 giving us amortized linear-time behavior. Use a less-than-double
559 growth factor to avoid excessive allocation. */
560 return currentsize + (currentsize >> 3) + 6;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000561}
562
Guido van Rossum7165cb12007-07-10 06:54:34 +0000563static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000564fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000565{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000566 PyObject *result;
567 Py_ssize_t total = 0;
568 int n;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000569
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200570 if (self->fd < 0)
571 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000572 if (!_PyVerify_fd(self->fd))
573 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000574
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000575 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
576 if (result == NULL)
577 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000578
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000579 while (1) {
580 size_t newsize = new_buffersize(self, total);
581 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
582 PyErr_SetString(PyExc_OverflowError,
583 "unbounded read returned more bytes "
584 "than a Python string can hold ");
585 Py_DECREF(result);
586 return NULL;
587 }
Christian Heimesa872de52008-12-05 08:26:55 +0000588
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000589 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
590 if (_PyBytes_Resize(&result, newsize) < 0) {
591 if (total == 0) {
592 Py_DECREF(result);
593 return NULL;
594 }
595 PyErr_Clear();
596 break;
597 }
598 }
599 Py_BEGIN_ALLOW_THREADS
600 errno = 0;
601 n = read(self->fd,
602 PyBytes_AS_STRING(result) + total,
603 newsize - total);
604 Py_END_ALLOW_THREADS
605 if (n == 0)
606 break;
607 if (n < 0) {
Gregory P. Smith51359922012-06-23 23:55:39 -0700608 if (errno == EINTR) {
609 if (PyErr_CheckSignals()) {
610 Py_DECREF(result);
611 return NULL;
612 }
613 continue;
614 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000615 if (total > 0)
616 break;
617 if (errno == EAGAIN) {
618 Py_DECREF(result);
619 Py_RETURN_NONE;
620 }
621 Py_DECREF(result);
622 PyErr_SetFromErrno(PyExc_IOError);
623 return NULL;
624 }
625 total += n;
626 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000627
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000628 if (PyBytes_GET_SIZE(result) > total) {
629 if (_PyBytes_Resize(&result, total) < 0) {
630 /* This should never happen, but just in case */
631 Py_DECREF(result);
632 return NULL;
633 }
634 }
635 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000636}
637
Guido van Rossuma9e20242007-03-08 00:43:48 +0000638static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000639fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000640{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000641 char *ptr;
642 Py_ssize_t n;
643 Py_ssize_t size = -1;
644 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000645
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000646 if (self->fd < 0)
647 return err_closed();
648 if (!self->readable)
649 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000650
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000651 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
652 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000653
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000654 if (size < 0) {
655 return fileio_readall(self);
656 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000657
Victor Stinnerc655a722011-07-05 11:31:49 +0200658#if defined(MS_WIN64) || defined(MS_WINDOWS)
659 if (size > INT_MAX)
660 size = INT_MAX;
661#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000662 bytes = PyBytes_FromStringAndSize(NULL, size);
663 if (bytes == NULL)
664 return NULL;
665 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000666
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000667 if (_PyVerify_fd(self->fd)) {
668 Py_BEGIN_ALLOW_THREADS
669 errno = 0;
Victor Stinnerc655a722011-07-05 11:31:49 +0200670#if defined(MS_WIN64) || defined(MS_WINDOWS)
671 n = read(self->fd, ptr, (int)size);
672#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000673 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200674#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000675 Py_END_ALLOW_THREADS
676 } else
677 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000678
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000679 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100680 int err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000681 Py_DECREF(bytes);
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100682 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000683 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100684 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000685 PyErr_SetFromErrno(PyExc_IOError);
686 return NULL;
687 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000688
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000689 if (n != size) {
690 if (_PyBytes_Resize(&bytes, n) < 0) {
691 Py_DECREF(bytes);
692 return NULL;
693 }
694 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000695
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000696 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000697}
698
699static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000700fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000701{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000702 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000703 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100704 int err;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000705
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000706 if (self->fd < 0)
707 return err_closed();
708 if (!self->writable)
709 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000710
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000711 if (!PyArg_ParseTuple(args, "y*", &pbuf))
712 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000713
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000714 if (_PyVerify_fd(self->fd)) {
715 Py_BEGIN_ALLOW_THREADS
716 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000717 len = pbuf.len;
718#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100719 if (len > 32767 && isatty(self->fd)) {
720 /* Issue #11395: the Windows console returns an error (12: not
721 enough space error) on writing into stdout if stdout mode is
722 binary and the length is greater than 66,000 bytes (or less,
723 depending on heap usage). */
724 len = 32767;
725 }
726 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000727 len = INT_MAX;
728 n = write(self->fd, pbuf.buf, (int)len);
729#else
Victor Stinner72344792011-01-11 00:04:12 +0000730 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000731#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000732 Py_END_ALLOW_THREADS
733 } else
734 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100735 err = errno;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000736
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000737 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000738
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000739 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100740 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000741 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100742 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000743 PyErr_SetFromErrno(PyExc_IOError);
744 return NULL;
745 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000746
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000747 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000748}
749
Guido van Rossum53807da2007-04-10 19:01:47 +0000750/* XXX Windows support below is likely incomplete */
751
Guido van Rossum53807da2007-04-10 19:01:47 +0000752/* Cribbed from posix_lseek() */
753static PyObject *
754portable_lseek(int fd, PyObject *posobj, int whence)
755{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000756 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000757
758#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000759 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
760 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000761#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000762 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000763#endif
764#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000765 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000766#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000767#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000768 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000769#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000770 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000771#endif /* SEEK_SET */
772
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000773 if (posobj == NULL)
774 pos = 0;
775 else {
776 if(PyFloat_Check(posobj)) {
777 PyErr_SetString(PyExc_TypeError, "an integer is required");
778 return NULL;
779 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000780#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000781 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000782#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000783 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000784#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000785 if (PyErr_Occurred())
786 return NULL;
787 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000788
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000789 if (_PyVerify_fd(fd)) {
790 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000791#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000792 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000793#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000794 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000795#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000796 Py_END_ALLOW_THREADS
797 } else
798 res = -1;
799 if (res < 0)
800 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000801
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000802#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000803 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000804#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000805 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000806#endif
807}
808
Guido van Rossuma9e20242007-03-08 00:43:48 +0000809static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000810fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000811{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000812 PyObject *posobj;
813 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000814
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000815 if (self->fd < 0)
816 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000817
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000818 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
819 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000820
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000821 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000822}
823
824static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000825fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000826{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000827 if (self->fd < 0)
828 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000829
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000830 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000831}
832
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000833#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000834static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000835fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000836{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000837 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000838#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000839 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000840#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000841 int ret;
842 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000843
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000844 fd = self->fd;
845 if (fd < 0)
846 return err_closed();
847 if (!self->writable)
848 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000849
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000850 if (!PyArg_ParseTuple(args, "|O", &posobj))
851 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000852
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000853 if (posobj == Py_None || posobj == NULL) {
854 /* Get the current position. */
855 posobj = portable_lseek(fd, NULL, 1);
856 if (posobj == NULL)
857 return NULL;
858 }
859 else {
860 Py_INCREF(posobj);
861 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000862
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000863#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000864 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
865 so don't even try using it. */
866 {
867 PyObject *oldposobj, *tempposobj;
868 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000869
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000870 /* we save the file pointer position */
871 oldposobj = portable_lseek(fd, NULL, 1);
872 if (oldposobj == NULL) {
873 Py_DECREF(posobj);
874 return NULL;
875 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000876
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000877 /* we then move to the truncation position */
878 tempposobj = portable_lseek(fd, posobj, 0);
879 if (tempposobj == NULL) {
880 Py_DECREF(oldposobj);
881 Py_DECREF(posobj);
882 return NULL;
883 }
884 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000885
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000886 /* Truncate. Note that this may grow the file! */
887 Py_BEGIN_ALLOW_THREADS
888 errno = 0;
889 hFile = (HANDLE)_get_osfhandle(fd);
890 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
891 if (ret == 0) {
892 ret = SetEndOfFile(hFile) == 0;
893 if (ret)
894 errno = EACCES;
895 }
896 Py_END_ALLOW_THREADS
897
898 /* we restore the file pointer position in any case */
899 tempposobj = portable_lseek(fd, oldposobj, 0);
900 Py_DECREF(oldposobj);
901 if (tempposobj == NULL) {
902 Py_DECREF(posobj);
903 return NULL;
904 }
905 Py_DECREF(tempposobj);
906 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000907#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000908
909#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000910 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000911#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000912 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000913#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000914 if (PyErr_Occurred()){
915 Py_DECREF(posobj);
916 return NULL;
917 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000918
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000919 Py_BEGIN_ALLOW_THREADS
920 errno = 0;
921 ret = ftruncate(fd, pos);
922 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000923
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000924#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000925
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000926 if (ret != 0) {
927 Py_DECREF(posobj);
928 PyErr_SetFromErrno(PyExc_IOError);
929 return NULL;
930 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000931
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000932 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000933}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000934#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000935
936static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000937mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000938{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000939 if (self->readable) {
940 if (self->writable)
941 return "rb+";
942 else
943 return "rb";
944 }
945 else
946 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000947}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000948
949static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000950fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000951{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000952 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000953
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000954 if (self->fd < 0)
955 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000956
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000957 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
958 if (nameobj == NULL) {
959 if (PyErr_ExceptionMatches(PyExc_AttributeError))
960 PyErr_Clear();
961 else
962 return NULL;
963 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
964 self->fd, mode_string(self));
965 }
966 else {
967 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
968 nameobj, mode_string(self));
969 Py_DECREF(nameobj);
970 }
971 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000972}
973
974static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000975fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000976{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000977 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000978
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000979 if (self->fd < 0)
980 return err_closed();
981 Py_BEGIN_ALLOW_THREADS
982 res = isatty(self->fd);
983 Py_END_ALLOW_THREADS
984 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000985}
986
Antoine Pitrou243757e2010-11-05 21:15:39 +0000987static PyObject *
988fileio_getstate(fileio *self)
989{
990 PyErr_Format(PyExc_TypeError,
991 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
992 return NULL;
993}
994
Guido van Rossuma9e20242007-03-08 00:43:48 +0000995
996PyDoc_STRVAR(fileio_doc,
997"file(name: str[, mode: str]) -> file IO object\n"
998"\n"
999"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001000"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001001"when opened for writing or appending; it will be truncated when\n"
1002"opened for writing. Add a '+' to the mode to allow simultaneous\n"
1003"reading and writing.");
1004
1005PyDoc_STRVAR(read_doc,
1006"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1007"\n"
1008"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001009"In non-blocking mode, returns None if no data is available.\n"
1010"On end-of-file, returns ''.");
1011
1012PyDoc_STRVAR(readall_doc,
1013"readall() -> bytes. read all data from the file, returned as bytes.\n"
1014"\n"
1015"In non-blocking mode, returns as much as is immediately available,\n"
1016"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001017
1018PyDoc_STRVAR(write_doc,
1019"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1020"\n"
1021"Only makes one system call, so not all of the data may be written.\n"
1022"The number of bytes actually written is returned.");
1023
1024PyDoc_STRVAR(fileno_doc,
1025"fileno() -> int. \"file descriptor\".\n"
1026"\n"
1027"This is needed for lower-level file interfaces, such the fcntl module.");
1028
1029PyDoc_STRVAR(seek_doc,
1030"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1031"\n"
1032"Argument offset is a byte count. Optional argument whence defaults to\n"
1033"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1034"(move relative to current position, positive or negative), and 2 (move\n"
1035"relative to end of file, usually negative, although many platforms allow\n"
1036"seeking beyond the end of a file)."
1037"\n"
1038"Note that not all file objects are seekable.");
1039
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001040#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001041PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001042"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001043"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001044"Size defaults to the current file position, as returned by tell()."
1045"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001046#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001047
1048PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001049"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001050
1051PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001052"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001053
1054PyDoc_STRVAR(close_doc,
1055"close() -> None. Close the file.\n"
1056"\n"
1057"A closed file cannot be used for further I/O operations. close() may be\n"
1058"called more than once without error. Changes the fileno to -1.");
1059
1060PyDoc_STRVAR(isatty_doc,
1061"isatty() -> bool. True if the file is connected to a tty device.");
1062
Guido van Rossuma9e20242007-03-08 00:43:48 +00001063PyDoc_STRVAR(seekable_doc,
1064"seekable() -> bool. True if file supports random-access.");
1065
1066PyDoc_STRVAR(readable_doc,
1067"readable() -> bool. True if file was opened in a read mode.");
1068
1069PyDoc_STRVAR(writable_doc,
1070"writable() -> bool. True if file was opened in a write mode.");
1071
1072static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001073 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1074 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1075 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1076 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1077 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1078 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001079#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001080 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001081#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001082 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1083 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1084 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1085 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1086 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1087 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001088 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001089 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001090 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001091};
1092
Guido van Rossum53807da2007-04-10 19:01:47 +00001093/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1094
Guido van Rossumb0428152007-04-08 17:44:42 +00001095static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001096get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001097{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001098 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001099}
1100
1101static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001102get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001103{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001104 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001105}
1106
1107static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001108get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001109{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001110 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001111}
1112
1113static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001114 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1115 {"closefd", (getter)get_closefd, NULL,
1116 "True if the file descriptor will be closed"},
1117 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1118 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001119};
1120
Guido van Rossuma9e20242007-03-08 00:43:48 +00001121PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001122 PyVarObject_HEAD_INIT(NULL, 0)
1123 "_io.FileIO",
1124 sizeof(fileio),
1125 0,
1126 (destructor)fileio_dealloc, /* tp_dealloc */
1127 0, /* tp_print */
1128 0, /* tp_getattr */
1129 0, /* tp_setattr */
1130 0, /* tp_reserved */
1131 (reprfunc)fileio_repr, /* tp_repr */
1132 0, /* tp_as_number */
1133 0, /* tp_as_sequence */
1134 0, /* tp_as_mapping */
1135 0, /* tp_hash */
1136 0, /* tp_call */
1137 0, /* tp_str */
1138 PyObject_GenericGetAttr, /* tp_getattro */
1139 0, /* tp_setattro */
1140 0, /* tp_as_buffer */
1141 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1142 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1143 fileio_doc, /* tp_doc */
1144 (traverseproc)fileio_traverse, /* tp_traverse */
1145 (inquiry)fileio_clear, /* tp_clear */
1146 0, /* tp_richcompare */
1147 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1148 0, /* tp_iter */
1149 0, /* tp_iternext */
1150 fileio_methods, /* tp_methods */
1151 0, /* tp_members */
1152 fileio_getsetlist, /* tp_getset */
1153 0, /* tp_base */
1154 0, /* tp_dict */
1155 0, /* tp_descr_get */
1156 0, /* tp_descr_set */
1157 offsetof(fileio, dict), /* tp_dictoffset */
1158 fileio_init, /* tp_init */
1159 PyType_GenericAlloc, /* tp_alloc */
1160 fileio_new, /* tp_new */
1161 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001162};