blob: f39f8b0d879558752717874ea79b06e5f9bc3c82 [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;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000227
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000228 assert(PyFileIO_Check(oself));
229 if (self->fd >= 0) {
230 /* Have to close the existing file first. */
231 if (internal_close(self) < 0)
232 return -1;
233 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000234
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000235 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
236 kwlist, &nameobj, &mode, &closefd))
237 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000238
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000239 if (PyFloat_Check(nameobj)) {
240 PyErr_SetString(PyExc_TypeError,
241 "integer argument expected, got float");
242 return -1;
243 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000244
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000245 fd = PyLong_AsLong(nameobj);
246 if (fd < 0) {
247 if (!PyErr_Occurred()) {
248 PyErr_SetString(PyExc_ValueError,
249 "Negative filedescriptor");
250 return -1;
251 }
252 PyErr_Clear();
253 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000254
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000255#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000256 if (PyUnicode_Check(nameobj))
257 widename = PyUnicode_AS_UNICODE(nameobj);
258 if (widename == NULL)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000259#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000260 if (fd < 0)
261 {
262 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
263 Py_ssize_t namelen;
264 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
265 return -1;
266 }
267 else {
268 PyObject *u = PyUnicode_FromObject(nameobj);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000269
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000270 if (u == NULL)
271 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000272
Victor Stinnerae6265f2010-05-15 16:27:27 +0000273 stringobj = PyUnicode_EncodeFSDefault(u);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000274 Py_DECREF(u);
275 if (stringobj == NULL)
276 return -1;
277 if (!PyBytes_Check(stringobj)) {
278 PyErr_SetString(PyExc_TypeError,
279 "encoder failed to return bytes");
280 goto error;
281 }
282 name = PyBytes_AS_STRING(stringobj);
283 }
284 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000285
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000286 s = mode;
287 while (*s) {
288 switch (*s++) {
289 case 'r':
290 if (rwa) {
291 bad_mode:
292 PyErr_SetString(PyExc_ValueError,
Georg Brandl28928ae2010-10-21 13:45:52 +0000293 "Must have exactly one of read/write/append "
294 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000295 goto error;
296 }
297 rwa = 1;
298 self->readable = 1;
299 break;
300 case 'w':
301 if (rwa)
302 goto bad_mode;
303 rwa = 1;
304 self->writable = 1;
305 flags |= O_CREAT | O_TRUNC;
306 break;
307 case 'a':
308 if (rwa)
309 goto bad_mode;
310 rwa = 1;
311 self->writable = 1;
312 flags |= O_CREAT;
313 append = 1;
314 break;
315 case 'b':
316 break;
317 case '+':
318 if (plus)
319 goto bad_mode;
320 self->readable = self->writable = 1;
321 plus = 1;
322 break;
323 default:
324 PyErr_Format(PyExc_ValueError,
325 "invalid mode: %.200s", mode);
326 goto error;
327 }
328 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000329
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000330 if (!rwa)
331 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000332
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000333 if (self->readable && self->writable)
334 flags |= O_RDWR;
335 else if (self->readable)
336 flags |= O_RDONLY;
337 else
338 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000339
340#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000341 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000342#endif
343
Walter Dörwald0e411482007-06-06 16:55:38 +0000344#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000345 if (append)
346 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000347#endif
348
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000349 if (fd >= 0) {
350 if (check_fd(fd))
351 goto error;
352 self->fd = fd;
353 self->closefd = closefd;
354 }
355 else {
356 self->closefd = 1;
357 if (!closefd) {
358 PyErr_SetString(PyExc_ValueError,
359 "Cannot use closefd=False with file name");
360 goto error;
361 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000362
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000363 Py_BEGIN_ALLOW_THREADS
364 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000365#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000366 if (widename != NULL)
367 self->fd = _wopen(widename, flags, 0666);
368 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000369#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000370 self->fd = open(name, flags, 0666);
371 Py_END_ALLOW_THREADS
372 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000373#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000374 if (widename != NULL)
375 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
376 else
Christian Heimes0b489542007-10-31 19:20:48 +0000377#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000378 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
379 goto error;
380 }
Benjamin Peterson430d4692010-10-30 23:13:57 +0000381 if (dircheck(self, name) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000382 goto error;
383 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000384
Victor Stinner89e34362011-01-07 18:47:22 +0000385#if defined(MS_WINDOWS) || defined(__CYGWIN__)
386 /* don't translate newlines (\r\n <=> \n) */
387 _setmode(self->fd, O_BINARY);
388#endif
389
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000390 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
391 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000392
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000393 if (append) {
394 /* For consistent behaviour, we explicitly seek to the
395 end of file (otherwise, it might be done only on the
396 first write()). */
397 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000398 if (pos == NULL) {
399 if (closefd) {
400 close(self->fd);
401 self->fd = -1;
402 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000403 goto error;
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000404 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000405 Py_DECREF(pos);
406 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000407
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000408 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000409
410 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000411 ret = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000412 if (self->fd >= 0)
413 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000414
Guido van Rossuma9e20242007-03-08 00:43:48 +0000415 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000416 Py_CLEAR(stringobj);
417 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000418}
419
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000420static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000421fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000422{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000423 Py_VISIT(self->dict);
424 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000425}
426
427static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000428fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000429{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000430 Py_CLEAR(self->dict);
431 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000432}
433
Guido van Rossuma9e20242007-03-08 00:43:48 +0000434static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000435fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000436{
Antoine Pitroue033e062010-10-29 10:38:18 +0000437 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000438 if (_PyIOBase_finalize((PyObject *) self) < 0)
439 return;
440 _PyObject_GC_UNTRACK(self);
441 if (self->weakreflist != NULL)
442 PyObject_ClearWeakRefs((PyObject *) self);
443 Py_CLEAR(self->dict);
444 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000445}
446
447static PyObject *
448err_closed(void)
449{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000450 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
451 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000452}
453
454static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000455err_mode(char *action)
456{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000457 PyErr_Format(IO_STATE->unsupported_operation,
458 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000459 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000460}
461
462static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000463fileio_fileno(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 PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000468}
469
470static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000471fileio_readable(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->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000476}
477
478static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000479fileio_writable(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 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000484}
485
486static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000487fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000488{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000489 if (self->fd < 0)
490 return err_closed();
491 if (self->seekable < 0) {
492 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
493 if (pos == NULL) {
494 PyErr_Clear();
495 self->seekable = 0;
496 } else {
497 Py_DECREF(pos);
498 self->seekable = 1;
499 }
500 }
501 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000502}
503
504static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000505fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000506{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000507 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000508 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100509 int err;
Guido van Rossum53807da2007-04-10 19:01:47 +0000510
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000511 if (self->fd < 0)
512 return err_closed();
513 if (!self->readable)
514 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000515
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000516 if (!PyArg_ParseTuple(args, "w*", &pbuf))
517 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000518
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000519 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000520 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000521 Py_BEGIN_ALLOW_THREADS
522 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000523#if defined(MS_WIN64) || defined(MS_WINDOWS)
524 if (len > INT_MAX)
525 len = INT_MAX;
526 n = read(self->fd, pbuf.buf, (int)len);
527#else
Victor Stinner72344792011-01-11 00:04:12 +0000528 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000529#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000530 Py_END_ALLOW_THREADS
531 } else
532 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100533 err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000534 PyBuffer_Release(&pbuf);
535 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100536 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000537 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100538 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000539 PyErr_SetFromErrno(PyExc_IOError);
540 return NULL;
541 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000542
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000543 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000544}
545
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000546static size_t
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000547new_buffersize(fileio *self, size_t currentsize)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000548{
549#ifdef HAVE_FSTAT
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000550 off_t pos, end;
551 struct stat st;
552 if (fstat(self->fd, &st) == 0) {
553 end = st.st_size;
554 pos = lseek(self->fd, 0L, SEEK_CUR);
555 /* Files claiming a size smaller than SMALLCHUNK may
556 actually be streaming pseudo-files. In this case, we
557 apply the more aggressive algorithm below.
558 */
559 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
560 /* Add 1 so if the file were to grow we'd notice. */
561 return currentsize + end - pos + 1;
562 }
563 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000564#endif
Nadeem Vawdad41a98b2011-10-13 13:34:16 +0200565 /* Expand the buffer by an amount proportional to the current size,
566 giving us amortized linear-time behavior. Use a less-than-double
567 growth factor to avoid excessive allocation. */
568 return currentsize + (currentsize >> 3) + 6;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000569}
570
Guido van Rossum7165cb12007-07-10 06:54:34 +0000571static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000572fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000573{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000574 PyObject *result;
575 Py_ssize_t total = 0;
576 int n;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000577
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200578 if (self->fd < 0)
579 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000580 if (!_PyVerify_fd(self->fd))
581 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000582
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000583 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
584 if (result == NULL)
585 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000586
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000587 while (1) {
588 size_t newsize = new_buffersize(self, total);
589 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
590 PyErr_SetString(PyExc_OverflowError,
591 "unbounded read returned more bytes "
592 "than a Python string can hold ");
593 Py_DECREF(result);
594 return NULL;
595 }
Christian Heimesa872de52008-12-05 08:26:55 +0000596
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000597 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
598 if (_PyBytes_Resize(&result, newsize) < 0) {
599 if (total == 0) {
600 Py_DECREF(result);
601 return NULL;
602 }
603 PyErr_Clear();
604 break;
605 }
606 }
607 Py_BEGIN_ALLOW_THREADS
608 errno = 0;
609 n = read(self->fd,
610 PyBytes_AS_STRING(result) + total,
611 newsize - total);
612 Py_END_ALLOW_THREADS
613 if (n == 0)
614 break;
615 if (n < 0) {
616 if (total > 0)
617 break;
618 if (errno == EAGAIN) {
619 Py_DECREF(result);
620 Py_RETURN_NONE;
621 }
622 Py_DECREF(result);
623 PyErr_SetFromErrno(PyExc_IOError);
624 return NULL;
625 }
626 total += n;
627 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000628
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000629 if (PyBytes_GET_SIZE(result) > total) {
630 if (_PyBytes_Resize(&result, total) < 0) {
631 /* This should never happen, but just in case */
632 Py_DECREF(result);
633 return NULL;
634 }
635 }
636 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000637}
638
Guido van Rossuma9e20242007-03-08 00:43:48 +0000639static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000640fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000641{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000642 char *ptr;
643 Py_ssize_t n;
644 Py_ssize_t size = -1;
645 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000646
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000647 if (self->fd < 0)
648 return err_closed();
649 if (!self->readable)
650 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000651
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000652 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
653 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000654
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000655 if (size < 0) {
656 return fileio_readall(self);
657 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000658
Victor Stinnerc655a722011-07-05 11:31:49 +0200659#if defined(MS_WIN64) || defined(MS_WINDOWS)
660 if (size > INT_MAX)
661 size = INT_MAX;
662#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000663 bytes = PyBytes_FromStringAndSize(NULL, size);
664 if (bytes == NULL)
665 return NULL;
666 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000667
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000668 if (_PyVerify_fd(self->fd)) {
669 Py_BEGIN_ALLOW_THREADS
670 errno = 0;
Victor Stinnerc655a722011-07-05 11:31:49 +0200671#if defined(MS_WIN64) || defined(MS_WINDOWS)
672 n = read(self->fd, ptr, (int)size);
673#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000674 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200675#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000676 Py_END_ALLOW_THREADS
677 } else
678 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000679
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000680 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100681 int err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000682 Py_DECREF(bytes);
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100683 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000684 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100685 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000686 PyErr_SetFromErrno(PyExc_IOError);
687 return NULL;
688 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000689
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000690 if (n != size) {
691 if (_PyBytes_Resize(&bytes, n) < 0) {
692 Py_DECREF(bytes);
693 return NULL;
694 }
695 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000696
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000697 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000698}
699
700static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000701fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000702{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000703 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000704 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100705 int err;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000706
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000707 if (self->fd < 0)
708 return err_closed();
709 if (!self->writable)
710 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000711
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000712 if (!PyArg_ParseTuple(args, "y*", &pbuf))
713 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000714
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000715 if (_PyVerify_fd(self->fd)) {
716 Py_BEGIN_ALLOW_THREADS
717 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000718 len = pbuf.len;
719#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100720 if (len > 32767 && isatty(self->fd)) {
721 /* Issue #11395: the Windows console returns an error (12: not
722 enough space error) on writing into stdout if stdout mode is
723 binary and the length is greater than 66,000 bytes (or less,
724 depending on heap usage). */
725 len = 32767;
726 }
727 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000728 len = INT_MAX;
729 n = write(self->fd, pbuf.buf, (int)len);
730#else
Victor Stinner72344792011-01-11 00:04:12 +0000731 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000732#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000733 Py_END_ALLOW_THREADS
734 } else
735 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100736 err = errno;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000737
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000738 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000739
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000740 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100741 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000742 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100743 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000744 PyErr_SetFromErrno(PyExc_IOError);
745 return NULL;
746 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000747
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000748 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000749}
750
Guido van Rossum53807da2007-04-10 19:01:47 +0000751/* XXX Windows support below is likely incomplete */
752
Guido van Rossum53807da2007-04-10 19:01:47 +0000753/* Cribbed from posix_lseek() */
754static PyObject *
755portable_lseek(int fd, PyObject *posobj, int whence)
756{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000757 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000758
759#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000760 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
761 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000762#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000763 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000764#endif
765#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000766 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000767#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000768#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000769 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000770#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000771 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000772#endif /* SEEK_SET */
773
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000774 if (posobj == NULL)
775 pos = 0;
776 else {
777 if(PyFloat_Check(posobj)) {
778 PyErr_SetString(PyExc_TypeError, "an integer is required");
779 return NULL;
780 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000781#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000782 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000783#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000784 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000785#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000786 if (PyErr_Occurred())
787 return NULL;
788 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000789
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000790 if (_PyVerify_fd(fd)) {
791 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000792#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000793 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000794#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000795 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000796#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000797 Py_END_ALLOW_THREADS
798 } else
799 res = -1;
800 if (res < 0)
801 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000802
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000803#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000804 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000805#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000806 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000807#endif
808}
809
Guido van Rossuma9e20242007-03-08 00:43:48 +0000810static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000811fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000812{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000813 PyObject *posobj;
814 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000815
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000816 if (self->fd < 0)
817 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000818
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000819 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
820 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000821
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000822 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000823}
824
825static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000826fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000827{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000828 if (self->fd < 0)
829 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000830
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000831 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000832}
833
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000834#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000835static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000836fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000837{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000838 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000839#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000840 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000841#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000842 int ret;
843 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000844
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000845 fd = self->fd;
846 if (fd < 0)
847 return err_closed();
848 if (!self->writable)
849 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000850
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000851 if (!PyArg_ParseTuple(args, "|O", &posobj))
852 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000853
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000854 if (posobj == Py_None || posobj == NULL) {
855 /* Get the current position. */
856 posobj = portable_lseek(fd, NULL, 1);
857 if (posobj == NULL)
858 return NULL;
859 }
860 else {
861 Py_INCREF(posobj);
862 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000863
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000864#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000865 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
866 so don't even try using it. */
867 {
868 PyObject *oldposobj, *tempposobj;
869 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000870
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000871 /* we save the file pointer position */
872 oldposobj = portable_lseek(fd, NULL, 1);
873 if (oldposobj == NULL) {
874 Py_DECREF(posobj);
875 return NULL;
876 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000877
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000878 /* we then move to the truncation position */
879 tempposobj = portable_lseek(fd, posobj, 0);
880 if (tempposobj == NULL) {
881 Py_DECREF(oldposobj);
882 Py_DECREF(posobj);
883 return NULL;
884 }
885 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000886
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000887 /* Truncate. Note that this may grow the file! */
888 Py_BEGIN_ALLOW_THREADS
889 errno = 0;
890 hFile = (HANDLE)_get_osfhandle(fd);
891 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
892 if (ret == 0) {
893 ret = SetEndOfFile(hFile) == 0;
894 if (ret)
895 errno = EACCES;
896 }
897 Py_END_ALLOW_THREADS
898
899 /* we restore the file pointer position in any case */
900 tempposobj = portable_lseek(fd, oldposobj, 0);
901 Py_DECREF(oldposobj);
902 if (tempposobj == NULL) {
903 Py_DECREF(posobj);
904 return NULL;
905 }
906 Py_DECREF(tempposobj);
907 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000908#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000909
910#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000911 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000912#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000913 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000914#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000915 if (PyErr_Occurred()){
916 Py_DECREF(posobj);
917 return NULL;
918 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000919
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000920 Py_BEGIN_ALLOW_THREADS
921 errno = 0;
922 ret = ftruncate(fd, pos);
923 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000924
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000925#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000926
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000927 if (ret != 0) {
928 Py_DECREF(posobj);
929 PyErr_SetFromErrno(PyExc_IOError);
930 return NULL;
931 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000932
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000933 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000934}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000935#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000936
937static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000938mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000939{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000940 if (self->readable) {
941 if (self->writable)
942 return "rb+";
943 else
944 return "rb";
945 }
946 else
947 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000948}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000949
950static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000951fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000952{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000953 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000954
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000955 if (self->fd < 0)
956 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000957
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000958 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
959 if (nameobj == NULL) {
960 if (PyErr_ExceptionMatches(PyExc_AttributeError))
961 PyErr_Clear();
962 else
963 return NULL;
964 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
965 self->fd, mode_string(self));
966 }
967 else {
968 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
969 nameobj, mode_string(self));
970 Py_DECREF(nameobj);
971 }
972 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000973}
974
975static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000976fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000977{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000978 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000979
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000980 if (self->fd < 0)
981 return err_closed();
982 Py_BEGIN_ALLOW_THREADS
983 res = isatty(self->fd);
984 Py_END_ALLOW_THREADS
985 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000986}
987
Antoine Pitrou243757e2010-11-05 21:15:39 +0000988static PyObject *
989fileio_getstate(fileio *self)
990{
991 PyErr_Format(PyExc_TypeError,
992 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
993 return NULL;
994}
995
Guido van Rossuma9e20242007-03-08 00:43:48 +0000996
997PyDoc_STRVAR(fileio_doc,
998"file(name: str[, mode: str]) -> file IO object\n"
999"\n"
1000"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001001"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001002"when opened for writing or appending; it will be truncated when\n"
1003"opened for writing. Add a '+' to the mode to allow simultaneous\n"
1004"reading and writing.");
1005
1006PyDoc_STRVAR(read_doc,
1007"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1008"\n"
1009"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001010"In non-blocking mode, returns None if no data is available.\n"
1011"On end-of-file, returns ''.");
1012
1013PyDoc_STRVAR(readall_doc,
1014"readall() -> bytes. read all data from the file, returned as bytes.\n"
1015"\n"
1016"In non-blocking mode, returns as much as is immediately available,\n"
1017"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001018
1019PyDoc_STRVAR(write_doc,
1020"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1021"\n"
1022"Only makes one system call, so not all of the data may be written.\n"
1023"The number of bytes actually written is returned.");
1024
1025PyDoc_STRVAR(fileno_doc,
1026"fileno() -> int. \"file descriptor\".\n"
1027"\n"
1028"This is needed for lower-level file interfaces, such the fcntl module.");
1029
1030PyDoc_STRVAR(seek_doc,
1031"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1032"\n"
1033"Argument offset is a byte count. Optional argument whence defaults to\n"
1034"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1035"(move relative to current position, positive or negative), and 2 (move\n"
1036"relative to end of file, usually negative, although many platforms allow\n"
1037"seeking beyond the end of a file)."
1038"\n"
1039"Note that not all file objects are seekable.");
1040
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001041#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001042PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001043"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001044"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001045"Size defaults to the current file position, as returned by tell()."
1046"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001047#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001048
1049PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001050"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001051
1052PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001053"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001054
1055PyDoc_STRVAR(close_doc,
1056"close() -> None. Close the file.\n"
1057"\n"
1058"A closed file cannot be used for further I/O operations. close() may be\n"
1059"called more than once without error. Changes the fileno to -1.");
1060
1061PyDoc_STRVAR(isatty_doc,
1062"isatty() -> bool. True if the file is connected to a tty device.");
1063
Guido van Rossuma9e20242007-03-08 00:43:48 +00001064PyDoc_STRVAR(seekable_doc,
1065"seekable() -> bool. True if file supports random-access.");
1066
1067PyDoc_STRVAR(readable_doc,
1068"readable() -> bool. True if file was opened in a read mode.");
1069
1070PyDoc_STRVAR(writable_doc,
1071"writable() -> bool. True if file was opened in a write mode.");
1072
1073static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001074 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1075 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1076 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1077 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1078 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1079 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001080#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001081 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001082#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001083 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1084 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1085 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1086 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1087 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1088 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001089 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001090 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001091 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001092};
1093
Guido van Rossum53807da2007-04-10 19:01:47 +00001094/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1095
Guido van Rossumb0428152007-04-08 17:44:42 +00001096static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001097get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001098{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001099 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001100}
1101
1102static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001103get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001104{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001105 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001106}
1107
1108static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001109get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001110{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001111 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001112}
1113
1114static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001115 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1116 {"closefd", (getter)get_closefd, NULL,
1117 "True if the file descriptor will be closed"},
1118 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1119 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001120};
1121
Guido van Rossuma9e20242007-03-08 00:43:48 +00001122PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001123 PyVarObject_HEAD_INIT(NULL, 0)
1124 "_io.FileIO",
1125 sizeof(fileio),
1126 0,
1127 (destructor)fileio_dealloc, /* tp_dealloc */
1128 0, /* tp_print */
1129 0, /* tp_getattr */
1130 0, /* tp_setattr */
1131 0, /* tp_reserved */
1132 (reprfunc)fileio_repr, /* tp_repr */
1133 0, /* tp_as_number */
1134 0, /* tp_as_sequence */
1135 0, /* tp_as_mapping */
1136 0, /* tp_hash */
1137 0, /* tp_call */
1138 0, /* tp_str */
1139 PyObject_GenericGetAttr, /* tp_getattro */
1140 0, /* tp_setattro */
1141 0, /* tp_as_buffer */
1142 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1143 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1144 fileio_doc, /* tp_doc */
1145 (traverseproc)fileio_traverse, /* tp_traverse */
1146 (inquiry)fileio_clear, /* tp_clear */
1147 0, /* tp_richcompare */
1148 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1149 0, /* tp_iter */
1150 0, /* tp_iternext */
1151 fileio_methods, /* tp_methods */
1152 0, /* tp_members */
1153 fileio_getsetlist, /* tp_getset */
1154 0, /* tp_base */
1155 0, /* tp_dict */
1156 0, /* tp_descr_get */
1157 0, /* tp_descr_set */
1158 offsetof(fileio, dict), /* tp_dictoffset */
1159 fileio_init, /* tp_init */
1160 PyType_GenericAlloc, /* tp_alloc */
1161 fileio_new, /* tp_new */
1162 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001163};