blob: e3c0dd93b59b20bbdf6830df3f8c4a0a0bbef6db [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{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200125 _Py_IDENTIFIER(close);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000126 if (!self->closefd) {
127 self->fd = -1;
128 Py_RETURN_NONE;
129 }
Antoine Pitroue033e062010-10-29 10:38:18 +0000130 if (self->deallocating) {
131 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
132 if (r)
133 Py_DECREF(r);
134 else
135 PyErr_Clear();
136 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000137 errno = internal_close(self);
138 if (errno < 0)
139 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000140
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200141 return _PyObject_CallMethodId((PyObject*)&PyRawIOBase_Type,
142 &PyId_close, "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000143}
144
145static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000146fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000147{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000148 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000149
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000150 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000151
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000152 self = (fileio *) type->tp_alloc(type, 0);
153 if (self != NULL) {
154 self->fd = -1;
155 self->readable = 0;
156 self->writable = 0;
157 self->seekable = -1;
158 self->closefd = 1;
159 self->weakreflist = NULL;
160 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000161
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000162 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000163}
164
165/* On Unix, open will succeed for directories.
166 In Python, there should be no file objects referring to
167 directories, so we need a check. */
168
169static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000170dircheck(fileio* self, const char *name)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000171{
172#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000173 struct stat buf;
174 if (self->fd < 0)
175 return 0;
176 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
177 char *msg = strerror(EISDIR);
178 PyObject *exc;
179 if (internal_close(self))
180 return -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000181
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000182 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
183 EISDIR, msg, name);
184 PyErr_SetObject(PyExc_IOError, exc);
185 Py_XDECREF(exc);
186 return -1;
187 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000188#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000189 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000190}
191
Benjamin Peterson806d4022009-01-19 15:11:51 +0000192static int
193check_fd(int fd)
194{
195#if defined(HAVE_FSTAT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000196 struct stat buf;
197 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
198 PyObject *exc;
199 char *msg = strerror(EBADF);
200 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
201 EBADF, msg);
202 PyErr_SetObject(PyExc_OSError, exc);
203 Py_XDECREF(exc);
204 return -1;
205 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000206#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000207 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000208}
209
Guido van Rossuma9e20242007-03-08 00:43:48 +0000210
211static int
212fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
213{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000214 fileio *self = (fileio *) oself;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200215 static char *kwlist[] = {"file", "mode", "closefd", "opener", NULL};
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000216 const char *name = NULL;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200217 PyObject *nameobj, *stringobj = NULL, *opener = Py_None;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000218 char *mode = "r";
219 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000220#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000221 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000222#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000223 int ret = 0;
224 int rwa = 0, plus = 0, append = 0;
225 int flags = 0;
226 int fd = -1;
227 int closefd = 1;
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) {
231 /* Have to close the existing file first. */
232 if (internal_close(self) < 0)
233 return -1;
234 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000235
Ross Lagerwall59142db2011-10-31 20:34:46 +0200236 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|siO:fileio",
237 kwlist, &nameobj, &mode, &closefd,
238 &opener))
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000239 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000240
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000241 if (PyFloat_Check(nameobj)) {
242 PyErr_SetString(PyExc_TypeError,
243 "integer argument expected, got float");
244 return -1;
245 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000246
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000247 fd = PyLong_AsLong(nameobj);
248 if (fd < 0) {
249 if (!PyErr_Occurred()) {
250 PyErr_SetString(PyExc_ValueError,
251 "Negative filedescriptor");
252 return -1;
253 }
254 PyErr_Clear();
255 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000256
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000257#ifdef MS_WINDOWS
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200258 if (PyUnicode_Check(nameobj)) {
259 widename = PyUnicode_AsUnicode(nameobj);
260 if (widename == NULL)
261 return -1;
262 } else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000263#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000264 if (fd < 0)
265 {
266 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
267 Py_ssize_t namelen;
268 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
269 return -1;
270 }
271 else {
272 PyObject *u = PyUnicode_FromObject(nameobj);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000273
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000274 if (u == NULL)
275 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000276
Victor Stinnerae6265f2010-05-15 16:27:27 +0000277 stringobj = PyUnicode_EncodeFSDefault(u);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000278 Py_DECREF(u);
279 if (stringobj == NULL)
280 return -1;
281 if (!PyBytes_Check(stringobj)) {
282 PyErr_SetString(PyExc_TypeError,
283 "encoder failed to return bytes");
284 goto error;
285 }
286 name = PyBytes_AS_STRING(stringobj);
287 }
288 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000289
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000290 s = mode;
291 while (*s) {
292 switch (*s++) {
293 case 'r':
294 if (rwa) {
295 bad_mode:
296 PyErr_SetString(PyExc_ValueError,
Georg Brandl28928ae2010-10-21 13:45:52 +0000297 "Must have exactly one of read/write/append "
298 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000299 goto error;
300 }
301 rwa = 1;
302 self->readable = 1;
303 break;
304 case 'w':
305 if (rwa)
306 goto bad_mode;
307 rwa = 1;
308 self->writable = 1;
309 flags |= O_CREAT | O_TRUNC;
310 break;
311 case 'a':
312 if (rwa)
313 goto bad_mode;
314 rwa = 1;
315 self->writable = 1;
316 flags |= O_CREAT;
317 append = 1;
318 break;
319 case 'b':
320 break;
321 case '+':
322 if (plus)
323 goto bad_mode;
324 self->readable = self->writable = 1;
325 plus = 1;
326 break;
327 default:
328 PyErr_Format(PyExc_ValueError,
329 "invalid mode: %.200s", mode);
330 goto error;
331 }
332 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000333
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000334 if (!rwa)
335 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000336
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000337 if (self->readable && self->writable)
338 flags |= O_RDWR;
339 else if (self->readable)
340 flags |= O_RDONLY;
341 else
342 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000343
344#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000345 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000346#endif
347
Walter Dörwald0e411482007-06-06 16:55:38 +0000348#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000349 if (append)
350 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000351#endif
352
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000353 if (fd >= 0) {
354 if (check_fd(fd))
355 goto error;
356 self->fd = fd;
357 self->closefd = closefd;
358 }
359 else {
360 self->closefd = 1;
361 if (!closefd) {
362 PyErr_SetString(PyExc_ValueError,
363 "Cannot use closefd=False with file name");
364 goto error;
365 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000366
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000367 errno = 0;
Ross Lagerwall59142db2011-10-31 20:34:46 +0200368 if (opener == Py_None) {
369 Py_BEGIN_ALLOW_THREADS
Thomas Helleraf2be262007-07-12 11:03:13 +0000370#ifdef MS_WINDOWS
Ross Lagerwall59142db2011-10-31 20:34:46 +0200371 if (widename != NULL)
372 self->fd = _wopen(widename, flags, 0666);
373 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000374#endif
Ross Lagerwall59142db2011-10-31 20:34:46 +0200375 self->fd = open(name, flags, 0666);
376 Py_END_ALLOW_THREADS
377 } else {
378 PyObject *fdobj = PyObject_CallFunction(
379 opener, "Oi", nameobj, flags);
380 if (fdobj == NULL)
381 goto error;
382 if (!PyLong_Check(fdobj)) {
383 Py_DECREF(fdobj);
384 PyErr_SetString(PyExc_TypeError,
385 "expected integer from opener");
386 goto error;
387 }
388
389 self->fd = PyLong_AsLong(fdobj);
390 Py_DECREF(fdobj);
391 if (self->fd == -1) {
392 goto error;
393 }
394 }
395
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000396 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000397#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000398 if (widename != NULL)
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200399 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000400 else
Christian Heimes0b489542007-10-31 19:20:48 +0000401#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000402 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
403 goto error;
404 }
Benjamin Peterson430d4692010-10-30 23:13:57 +0000405 if (dircheck(self, name) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000406 goto error;
407 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000408
Victor Stinner89e34362011-01-07 18:47:22 +0000409#if defined(MS_WINDOWS) || defined(__CYGWIN__)
410 /* don't translate newlines (\r\n <=> \n) */
411 _setmode(self->fd, O_BINARY);
412#endif
413
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000414 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
415 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000416
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000417 if (append) {
418 /* For consistent behaviour, we explicitly seek to the
419 end of file (otherwise, it might be done only on the
420 first write()). */
421 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000422 if (pos == NULL) {
423 if (closefd) {
424 close(self->fd);
425 self->fd = -1;
426 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000427 goto error;
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000428 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000429 Py_DECREF(pos);
430 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000431
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000432 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000433
434 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000435 ret = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000436 if (self->fd >= 0)
437 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000438
Guido van Rossuma9e20242007-03-08 00:43:48 +0000439 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000440 Py_CLEAR(stringobj);
441 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000442}
443
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000444static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000445fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000446{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000447 Py_VISIT(self->dict);
448 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000449}
450
451static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000452fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000453{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000454 Py_CLEAR(self->dict);
455 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000456}
457
Guido van Rossuma9e20242007-03-08 00:43:48 +0000458static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000459fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000460{
Antoine Pitroue033e062010-10-29 10:38:18 +0000461 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000462 if (_PyIOBase_finalize((PyObject *) self) < 0)
463 return;
464 _PyObject_GC_UNTRACK(self);
465 if (self->weakreflist != NULL)
466 PyObject_ClearWeakRefs((PyObject *) self);
467 Py_CLEAR(self->dict);
468 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000469}
470
471static PyObject *
472err_closed(void)
473{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000474 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
475 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000476}
477
478static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000479err_mode(char *action)
480{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000481 PyErr_Format(IO_STATE->unsupported_operation,
482 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000483 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000484}
485
486static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000487fileio_fileno(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 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000492}
493
494static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000495fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000496{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000497 if (self->fd < 0)
498 return err_closed();
499 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000500}
501
502static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000503fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000504{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000505 if (self->fd < 0)
506 return err_closed();
507 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000508}
509
510static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000511fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000512{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000513 if (self->fd < 0)
514 return err_closed();
515 if (self->seekable < 0) {
516 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
517 if (pos == NULL) {
518 PyErr_Clear();
519 self->seekable = 0;
520 } else {
521 Py_DECREF(pos);
522 self->seekable = 1;
523 }
524 }
525 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000526}
527
528static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000529fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000530{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000531 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000532 Py_ssize_t n, len;
Guido van Rossum53807da2007-04-10 19:01:47 +0000533
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000534 if (self->fd < 0)
535 return err_closed();
536 if (!self->readable)
537 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000538
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000539 if (!PyArg_ParseTuple(args, "w*", &pbuf))
540 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000541
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000542 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000543 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000544 Py_BEGIN_ALLOW_THREADS
545 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000546#if defined(MS_WIN64) || defined(MS_WINDOWS)
547 if (len > INT_MAX)
548 len = INT_MAX;
549 n = read(self->fd, pbuf.buf, (int)len);
550#else
Victor Stinner72344792011-01-11 00:04:12 +0000551 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000552#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000553 Py_END_ALLOW_THREADS
554 } else
555 n = -1;
556 PyBuffer_Release(&pbuf);
557 if (n < 0) {
558 if (errno == EAGAIN)
559 Py_RETURN_NONE;
560 PyErr_SetFromErrno(PyExc_IOError);
561 return NULL;
562 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000563
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000564 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000565}
566
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000567static size_t
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200568new_buffersize(fileio *self, size_t currentsize
569#ifdef HAVE_FSTAT
Victor Stinnera2a64772011-10-11 22:45:02 +0200570 , Py_off_t pos, Py_off_t end
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200571#endif
572 )
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000573{
574#ifdef HAVE_FSTAT
Victor Stinnera2a64772011-10-11 22:45:02 +0200575 if (end != (Py_off_t)-1) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000576 /* Files claiming a size smaller than SMALLCHUNK may
577 actually be streaming pseudo-files. In this case, we
578 apply the more aggressive algorithm below.
579 */
580 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
581 /* Add 1 so if the file were to grow we'd notice. */
Victor Stinnerc5af7732011-10-11 23:00:31 +0200582 Py_off_t bufsize = currentsize + end - pos + 1;
583 if (bufsize < PY_SSIZE_T_MAX)
584 return (size_t)bufsize;
585 else
586 return PY_SSIZE_T_MAX;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000587 }
588 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000589#endif
Nadeem Vawdad41a98b2011-10-13 13:34:16 +0200590 /* Expand the buffer by an amount proportional to the current size,
591 giving us amortized linear-time behavior. Use a less-than-double
592 growth factor to avoid excessive allocation. */
593 return currentsize + (currentsize >> 3) + 6;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000594}
595
Guido van Rossum7165cb12007-07-10 06:54:34 +0000596static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000597fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000598{
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200599#ifdef HAVE_FSTAT
600 struct stat st;
Victor Stinnera2a64772011-10-11 22:45:02 +0200601 Py_off_t pos, end;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200602#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000603 PyObject *result;
604 Py_ssize_t total = 0;
605 int n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200606 size_t newsize;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000607
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200608 if (self->fd < 0)
609 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000610 if (!_PyVerify_fd(self->fd))
611 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000612
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000613 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
614 if (result == NULL)
615 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000616
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200617#ifdef HAVE_FSTAT
618#if defined(MS_WIN64) || defined(MS_WINDOWS)
619 pos = _lseeki64(self->fd, 0L, SEEK_CUR);
620#else
621 pos = lseek(self->fd, 0L, SEEK_CUR);
622#endif
623 if (fstat(self->fd, &st) == 0)
624 end = st.st_size;
625 else
Victor Stinnera2a64772011-10-11 22:45:02 +0200626 end = (Py_off_t)-1;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200627#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000628 while (1) {
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200629#ifdef HAVE_FSTAT
630 newsize = new_buffersize(self, total, pos, end);
631#else
632 newsize = new_buffersize(self, total);
633#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000634 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
635 PyErr_SetString(PyExc_OverflowError,
636 "unbounded read returned more bytes "
637 "than a Python string can hold ");
638 Py_DECREF(result);
639 return NULL;
640 }
Christian Heimesa872de52008-12-05 08:26:55 +0000641
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000642 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
643 if (_PyBytes_Resize(&result, newsize) < 0) {
644 if (total == 0) {
645 Py_DECREF(result);
646 return NULL;
647 }
648 PyErr_Clear();
649 break;
650 }
651 }
652 Py_BEGIN_ALLOW_THREADS
653 errno = 0;
654 n = read(self->fd,
655 PyBytes_AS_STRING(result) + total,
656 newsize - total);
657 Py_END_ALLOW_THREADS
658 if (n == 0)
659 break;
660 if (n < 0) {
661 if (total > 0)
662 break;
663 if (errno == EAGAIN) {
664 Py_DECREF(result);
665 Py_RETURN_NONE;
666 }
667 Py_DECREF(result);
668 PyErr_SetFromErrno(PyExc_IOError);
669 return NULL;
670 }
671 total += n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200672#ifdef HAVE_FSTAT
673 pos += n;
674#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000675 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000676
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000677 if (PyBytes_GET_SIZE(result) > total) {
678 if (_PyBytes_Resize(&result, total) < 0) {
679 /* This should never happen, but just in case */
680 Py_DECREF(result);
681 return NULL;
682 }
683 }
684 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000685}
686
Guido van Rossuma9e20242007-03-08 00:43:48 +0000687static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000688fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000689{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000690 char *ptr;
691 Py_ssize_t n;
692 Py_ssize_t size = -1;
693 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000694
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000695 if (self->fd < 0)
696 return err_closed();
697 if (!self->readable)
698 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000699
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000700 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
701 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000702
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000703 if (size < 0) {
704 return fileio_readall(self);
705 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000706
Victor Stinnerc655a722011-07-05 11:31:49 +0200707#if defined(MS_WIN64) || defined(MS_WINDOWS)
708 if (size > INT_MAX)
709 size = INT_MAX;
710#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000711 bytes = PyBytes_FromStringAndSize(NULL, size);
712 if (bytes == NULL)
713 return NULL;
714 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000715
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000716 if (_PyVerify_fd(self->fd)) {
717 Py_BEGIN_ALLOW_THREADS
718 errno = 0;
Victor Stinnerc655a722011-07-05 11:31:49 +0200719#if defined(MS_WIN64) || defined(MS_WINDOWS)
720 n = read(self->fd, ptr, (int)size);
721#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000722 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200723#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000724 Py_END_ALLOW_THREADS
725 } else
726 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000727
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000728 if (n < 0) {
729 Py_DECREF(bytes);
730 if (errno == EAGAIN)
731 Py_RETURN_NONE;
732 PyErr_SetFromErrno(PyExc_IOError);
733 return NULL;
734 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000735
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000736 if (n != size) {
737 if (_PyBytes_Resize(&bytes, n) < 0) {
738 Py_DECREF(bytes);
739 return NULL;
740 }
741 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000742
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000743 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000744}
745
746static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000747fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000748{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000749 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000750 Py_ssize_t n, len;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000751
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000752 if (self->fd < 0)
753 return err_closed();
754 if (!self->writable)
755 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000756
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000757 if (!PyArg_ParseTuple(args, "y*", &pbuf))
758 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000759
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000760 if (_PyVerify_fd(self->fd)) {
761 Py_BEGIN_ALLOW_THREADS
762 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000763 len = pbuf.len;
764#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100765 if (len > 32767 && isatty(self->fd)) {
766 /* Issue #11395: the Windows console returns an error (12: not
767 enough space error) on writing into stdout if stdout mode is
768 binary and the length is greater than 66,000 bytes (or less,
769 depending on heap usage). */
770 len = 32767;
771 }
772 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000773 len = INT_MAX;
774 n = write(self->fd, pbuf.buf, (int)len);
775#else
Victor Stinner72344792011-01-11 00:04:12 +0000776 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000777#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000778 Py_END_ALLOW_THREADS
779 } else
780 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000781
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000782 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000783
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000784 if (n < 0) {
785 if (errno == EAGAIN)
786 Py_RETURN_NONE;
787 PyErr_SetFromErrno(PyExc_IOError);
788 return NULL;
789 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000790
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000791 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000792}
793
Guido van Rossum53807da2007-04-10 19:01:47 +0000794/* XXX Windows support below is likely incomplete */
795
Guido van Rossum53807da2007-04-10 19:01:47 +0000796/* Cribbed from posix_lseek() */
797static PyObject *
798portable_lseek(int fd, PyObject *posobj, int whence)
799{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000800 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000801
802#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000803 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
804 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000805#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000806 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000807#endif
808#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000809 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000810#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000811#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000812 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000813#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000814 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000815#endif /* SEEK_SET */
816
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000817 if (posobj == NULL)
818 pos = 0;
819 else {
820 if(PyFloat_Check(posobj)) {
821 PyErr_SetString(PyExc_TypeError, "an integer is required");
822 return NULL;
823 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000824#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000825 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000826#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000827 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000828#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000829 if (PyErr_Occurred())
830 return NULL;
831 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000832
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000833 if (_PyVerify_fd(fd)) {
834 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000835#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000836 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000837#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000838 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000839#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000840 Py_END_ALLOW_THREADS
841 } else
842 res = -1;
843 if (res < 0)
844 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000845
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000846#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000847 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000848#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000849 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000850#endif
851}
852
Guido van Rossuma9e20242007-03-08 00:43:48 +0000853static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000854fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000855{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000856 PyObject *posobj;
857 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000858
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000859 if (self->fd < 0)
860 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000861
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000862 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
863 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000864
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000865 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000866}
867
868static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000869fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000870{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000871 if (self->fd < 0)
872 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000873
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000874 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000875}
876
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000877#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000878static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000879fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000880{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000881 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000882#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000883 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000884#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000885 int ret;
886 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000887
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000888 fd = self->fd;
889 if (fd < 0)
890 return err_closed();
891 if (!self->writable)
892 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000893
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000894 if (!PyArg_ParseTuple(args, "|O", &posobj))
895 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000896
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000897 if (posobj == Py_None || posobj == NULL) {
898 /* Get the current position. */
899 posobj = portable_lseek(fd, NULL, 1);
900 if (posobj == NULL)
901 return NULL;
902 }
903 else {
904 Py_INCREF(posobj);
905 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000906
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000907#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000908 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
909 so don't even try using it. */
910 {
911 PyObject *oldposobj, *tempposobj;
912 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000913
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000914 /* we save the file pointer position */
915 oldposobj = portable_lseek(fd, NULL, 1);
916 if (oldposobj == NULL) {
917 Py_DECREF(posobj);
918 return NULL;
919 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000920
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000921 /* we then move to the truncation position */
922 tempposobj = portable_lseek(fd, posobj, 0);
923 if (tempposobj == NULL) {
924 Py_DECREF(oldposobj);
925 Py_DECREF(posobj);
926 return NULL;
927 }
928 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000929
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000930 /* Truncate. Note that this may grow the file! */
931 Py_BEGIN_ALLOW_THREADS
932 errno = 0;
933 hFile = (HANDLE)_get_osfhandle(fd);
934 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
935 if (ret == 0) {
936 ret = SetEndOfFile(hFile) == 0;
937 if (ret)
938 errno = EACCES;
939 }
940 Py_END_ALLOW_THREADS
941
942 /* we restore the file pointer position in any case */
943 tempposobj = portable_lseek(fd, oldposobj, 0);
944 Py_DECREF(oldposobj);
945 if (tempposobj == NULL) {
946 Py_DECREF(posobj);
947 return NULL;
948 }
949 Py_DECREF(tempposobj);
950 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000951#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000952
953#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000954 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000955#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000956 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000957#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000958 if (PyErr_Occurred()){
959 Py_DECREF(posobj);
960 return NULL;
961 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000962
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000963 Py_BEGIN_ALLOW_THREADS
964 errno = 0;
965 ret = ftruncate(fd, pos);
966 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000967
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000968#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000969
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000970 if (ret != 0) {
971 Py_DECREF(posobj);
972 PyErr_SetFromErrno(PyExc_IOError);
973 return NULL;
974 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000975
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000976 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000977}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000978#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000979
980static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000981mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000982{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000983 if (self->readable) {
984 if (self->writable)
985 return "rb+";
986 else
987 return "rb";
988 }
989 else
990 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000991}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000992
993static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000994fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000995{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000996 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000997
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000998 if (self->fd < 0)
999 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +00001000
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001001 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
1002 if (nameobj == NULL) {
1003 if (PyErr_ExceptionMatches(PyExc_AttributeError))
1004 PyErr_Clear();
1005 else
1006 return NULL;
1007 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
1008 self->fd, mode_string(self));
1009 }
1010 else {
1011 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
1012 nameobj, mode_string(self));
1013 Py_DECREF(nameobj);
1014 }
1015 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001016}
1017
1018static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001019fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +00001020{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001021 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +00001022
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001023 if (self->fd < 0)
1024 return err_closed();
1025 Py_BEGIN_ALLOW_THREADS
1026 res = isatty(self->fd);
1027 Py_END_ALLOW_THREADS
1028 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +00001029}
1030
Antoine Pitrou243757e2010-11-05 21:15:39 +00001031static PyObject *
1032fileio_getstate(fileio *self)
1033{
1034 PyErr_Format(PyExc_TypeError,
1035 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
1036 return NULL;
1037}
1038
Guido van Rossuma9e20242007-03-08 00:43:48 +00001039
1040PyDoc_STRVAR(fileio_doc,
Ross Lagerwall59142db2011-10-31 20:34:46 +02001041"file(name: str[, mode: str][, opener: None]) -> file IO object\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001042"\n"
1043"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001044"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001045"when opened for writing or appending; it will be truncated when\n"
1046"opened for writing. Add a '+' to the mode to allow simultaneous\n"
Ross Lagerwall59142db2011-10-31 20:34:46 +02001047"reading and writing. A custom opener can be used by passing a\n"
1048"callable as *opener*. The underlying file descriptor for the file\n"
1049"object is then obtained by calling opener with (*name*, *flags*).\n"
1050"*opener* must return an open file descriptor (passing os.open as\n"
1051"*opener* results in functionality similar to passing None).");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001052
1053PyDoc_STRVAR(read_doc,
1054"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1055"\n"
1056"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001057"In non-blocking mode, returns None if no data is available.\n"
1058"On end-of-file, returns ''.");
1059
1060PyDoc_STRVAR(readall_doc,
1061"readall() -> bytes. read all data from the file, returned as bytes.\n"
1062"\n"
1063"In non-blocking mode, returns as much as is immediately available,\n"
1064"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001065
1066PyDoc_STRVAR(write_doc,
1067"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1068"\n"
1069"Only makes one system call, so not all of the data may be written.\n"
1070"The number of bytes actually written is returned.");
1071
1072PyDoc_STRVAR(fileno_doc,
1073"fileno() -> int. \"file descriptor\".\n"
1074"\n"
1075"This is needed for lower-level file interfaces, such the fcntl module.");
1076
1077PyDoc_STRVAR(seek_doc,
1078"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1079"\n"
1080"Argument offset is a byte count. Optional argument whence defaults to\n"
1081"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1082"(move relative to current position, positive or negative), and 2 (move\n"
1083"relative to end of file, usually negative, although many platforms allow\n"
1084"seeking beyond the end of a file)."
1085"\n"
1086"Note that not all file objects are seekable.");
1087
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001088#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001089PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001090"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001091"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001092"Size defaults to the current file position, as returned by tell()."
1093"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001094#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001095
1096PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001097"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001098
1099PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001100"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001101
1102PyDoc_STRVAR(close_doc,
1103"close() -> None. Close the file.\n"
1104"\n"
1105"A closed file cannot be used for further I/O operations. close() may be\n"
1106"called more than once without error. Changes the fileno to -1.");
1107
1108PyDoc_STRVAR(isatty_doc,
1109"isatty() -> bool. True if the file is connected to a tty device.");
1110
Guido van Rossuma9e20242007-03-08 00:43:48 +00001111PyDoc_STRVAR(seekable_doc,
1112"seekable() -> bool. True if file supports random-access.");
1113
1114PyDoc_STRVAR(readable_doc,
1115"readable() -> bool. True if file was opened in a read mode.");
1116
1117PyDoc_STRVAR(writable_doc,
1118"writable() -> bool. True if file was opened in a write mode.");
1119
1120static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001121 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1122 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1123 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1124 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1125 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1126 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001127#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001128 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001129#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001130 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1131 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1132 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1133 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1134 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1135 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001136 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001137 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001138 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001139};
1140
Guido van Rossum53807da2007-04-10 19:01:47 +00001141/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1142
Guido van Rossumb0428152007-04-08 17:44:42 +00001143static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001144get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001145{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001146 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001147}
1148
1149static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001150get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001151{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001152 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001153}
1154
1155static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001156get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001157{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001158 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001159}
1160
1161static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001162 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1163 {"closefd", (getter)get_closefd, NULL,
1164 "True if the file descriptor will be closed"},
1165 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1166 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001167};
1168
Guido van Rossuma9e20242007-03-08 00:43:48 +00001169PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001170 PyVarObject_HEAD_INIT(NULL, 0)
1171 "_io.FileIO",
1172 sizeof(fileio),
1173 0,
1174 (destructor)fileio_dealloc, /* tp_dealloc */
1175 0, /* tp_print */
1176 0, /* tp_getattr */
1177 0, /* tp_setattr */
1178 0, /* tp_reserved */
1179 (reprfunc)fileio_repr, /* tp_repr */
1180 0, /* tp_as_number */
1181 0, /* tp_as_sequence */
1182 0, /* tp_as_mapping */
1183 0, /* tp_hash */
1184 0, /* tp_call */
1185 0, /* tp_str */
1186 PyObject_GenericGetAttr, /* tp_getattro */
1187 0, /* tp_setattro */
1188 0, /* tp_as_buffer */
1189 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1190 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1191 fileio_doc, /* tp_doc */
1192 (traverseproc)fileio_traverse, /* tp_traverse */
1193 (inquiry)fileio_clear, /* tp_clear */
1194 0, /* tp_richcompare */
1195 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1196 0, /* tp_iter */
1197 0, /* tp_iternext */
1198 fileio_methods, /* tp_methods */
1199 0, /* tp_members */
1200 fileio_getsetlist, /* tp_getset */
1201 0, /* tp_base */
1202 0, /* tp_dict */
1203 0, /* tp_descr_get */
1204 0, /* tp_descr_set */
1205 offsetof(fileio, dict), /* tp_dictoffset */
1206 fileio_init, /* tp_init */
1207 PyType_GenericAlloc, /* tp_alloc */
1208 fileio_new, /* tp_new */
1209 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001210};