blob: 3829e0bb3966cdedf7f46a5df7112501a5c089f3 [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;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100533 int err;
Guido van Rossum53807da2007-04-10 19:01:47 +0000534
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000535 if (self->fd < 0)
536 return err_closed();
537 if (!self->readable)
538 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000539
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000540 if (!PyArg_ParseTuple(args, "w*", &pbuf))
541 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000542
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000543 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000544 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000545 Py_BEGIN_ALLOW_THREADS
546 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000547#if defined(MS_WIN64) || defined(MS_WINDOWS)
548 if (len > INT_MAX)
549 len = INT_MAX;
550 n = read(self->fd, pbuf.buf, (int)len);
551#else
Victor Stinner72344792011-01-11 00:04:12 +0000552 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000553#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000554 Py_END_ALLOW_THREADS
555 } else
556 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100557 err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000558 PyBuffer_Release(&pbuf);
559 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100560 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000561 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100562 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000563 PyErr_SetFromErrno(PyExc_IOError);
564 return NULL;
565 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000566
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000567 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000568}
569
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000570static size_t
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200571new_buffersize(fileio *self, size_t currentsize
572#ifdef HAVE_FSTAT
Victor Stinnera2a64772011-10-11 22:45:02 +0200573 , Py_off_t pos, Py_off_t end
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200574#endif
575 )
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000576{
577#ifdef HAVE_FSTAT
Victor Stinnera2a64772011-10-11 22:45:02 +0200578 if (end != (Py_off_t)-1) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000579 /* Files claiming a size smaller than SMALLCHUNK may
580 actually be streaming pseudo-files. In this case, we
581 apply the more aggressive algorithm below.
582 */
583 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
584 /* Add 1 so if the file were to grow we'd notice. */
Victor Stinnerc5af7732011-10-11 23:00:31 +0200585 Py_off_t bufsize = currentsize + end - pos + 1;
586 if (bufsize < PY_SSIZE_T_MAX)
587 return (size_t)bufsize;
588 else
589 return PY_SSIZE_T_MAX;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000590 }
591 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000592#endif
Nadeem Vawdad41a98b2011-10-13 13:34:16 +0200593 /* Expand the buffer by an amount proportional to the current size,
594 giving us amortized linear-time behavior. Use a less-than-double
595 growth factor to avoid excessive allocation. */
596 return currentsize + (currentsize >> 3) + 6;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000597}
598
Guido van Rossum7165cb12007-07-10 06:54:34 +0000599static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000600fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000601{
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200602#ifdef HAVE_FSTAT
603 struct stat st;
Victor Stinnera2a64772011-10-11 22:45:02 +0200604 Py_off_t pos, end;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200605#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000606 PyObject *result;
607 Py_ssize_t total = 0;
608 int n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200609 size_t newsize;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000610
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200611 if (self->fd < 0)
612 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000613 if (!_PyVerify_fd(self->fd))
614 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000615
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000616 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
617 if (result == NULL)
618 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000619
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200620#ifdef HAVE_FSTAT
621#if defined(MS_WIN64) || defined(MS_WINDOWS)
622 pos = _lseeki64(self->fd, 0L, SEEK_CUR);
623#else
624 pos = lseek(self->fd, 0L, SEEK_CUR);
625#endif
626 if (fstat(self->fd, &st) == 0)
627 end = st.st_size;
628 else
Victor Stinnera2a64772011-10-11 22:45:02 +0200629 end = (Py_off_t)-1;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200630#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000631 while (1) {
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200632#ifdef HAVE_FSTAT
633 newsize = new_buffersize(self, total, pos, end);
634#else
635 newsize = new_buffersize(self, total);
636#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000637 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
638 PyErr_SetString(PyExc_OverflowError,
639 "unbounded read returned more bytes "
640 "than a Python string can hold ");
641 Py_DECREF(result);
642 return NULL;
643 }
Christian Heimesa872de52008-12-05 08:26:55 +0000644
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000645 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
646 if (_PyBytes_Resize(&result, newsize) < 0) {
647 if (total == 0) {
648 Py_DECREF(result);
649 return NULL;
650 }
651 PyErr_Clear();
652 break;
653 }
654 }
655 Py_BEGIN_ALLOW_THREADS
656 errno = 0;
657 n = read(self->fd,
658 PyBytes_AS_STRING(result) + total,
659 newsize - total);
660 Py_END_ALLOW_THREADS
661 if (n == 0)
662 break;
663 if (n < 0) {
664 if (total > 0)
665 break;
666 if (errno == EAGAIN) {
667 Py_DECREF(result);
668 Py_RETURN_NONE;
669 }
670 Py_DECREF(result);
671 PyErr_SetFromErrno(PyExc_IOError);
672 return NULL;
673 }
674 total += n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200675#ifdef HAVE_FSTAT
676 pos += n;
677#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000678 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000679
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000680 if (PyBytes_GET_SIZE(result) > total) {
681 if (_PyBytes_Resize(&result, total) < 0) {
682 /* This should never happen, but just in case */
683 Py_DECREF(result);
684 return NULL;
685 }
686 }
687 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000688}
689
Guido van Rossuma9e20242007-03-08 00:43:48 +0000690static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000691fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000692{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000693 char *ptr;
694 Py_ssize_t n;
695 Py_ssize_t size = -1;
696 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000697
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000698 if (self->fd < 0)
699 return err_closed();
700 if (!self->readable)
701 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000702
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000703 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
704 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000705
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000706 if (size < 0) {
707 return fileio_readall(self);
708 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000709
Victor Stinnerc655a722011-07-05 11:31:49 +0200710#if defined(MS_WIN64) || defined(MS_WINDOWS)
711 if (size > INT_MAX)
712 size = INT_MAX;
713#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000714 bytes = PyBytes_FromStringAndSize(NULL, size);
715 if (bytes == NULL)
716 return NULL;
717 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000718
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000719 if (_PyVerify_fd(self->fd)) {
720 Py_BEGIN_ALLOW_THREADS
721 errno = 0;
Victor Stinnerc655a722011-07-05 11:31:49 +0200722#if defined(MS_WIN64) || defined(MS_WINDOWS)
723 n = read(self->fd, ptr, (int)size);
724#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000725 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200726#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000727 Py_END_ALLOW_THREADS
728 } else
729 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000730
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000731 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100732 int err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000733 Py_DECREF(bytes);
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100734 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000735 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100736 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000737 PyErr_SetFromErrno(PyExc_IOError);
738 return NULL;
739 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000740
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000741 if (n != size) {
742 if (_PyBytes_Resize(&bytes, n) < 0) {
743 Py_DECREF(bytes);
744 return NULL;
745 }
746 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000747
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000748 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000749}
750
751static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000752fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000753{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000754 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000755 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100756 int err;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000757
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000758 if (self->fd < 0)
759 return err_closed();
760 if (!self->writable)
761 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000762
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000763 if (!PyArg_ParseTuple(args, "y*", &pbuf))
764 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000765
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000766 if (_PyVerify_fd(self->fd)) {
767 Py_BEGIN_ALLOW_THREADS
768 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000769 len = pbuf.len;
770#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100771 if (len > 32767 && isatty(self->fd)) {
772 /* Issue #11395: the Windows console returns an error (12: not
773 enough space error) on writing into stdout if stdout mode is
774 binary and the length is greater than 66,000 bytes (or less,
775 depending on heap usage). */
776 len = 32767;
777 }
778 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000779 len = INT_MAX;
780 n = write(self->fd, pbuf.buf, (int)len);
781#else
Victor Stinner72344792011-01-11 00:04:12 +0000782 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000783#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000784 Py_END_ALLOW_THREADS
785 } else
786 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100787 err = errno;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000788
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000789 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000790
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000791 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100792 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000793 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100794 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000795 PyErr_SetFromErrno(PyExc_IOError);
796 return NULL;
797 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000798
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000799 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000800}
801
Guido van Rossum53807da2007-04-10 19:01:47 +0000802/* XXX Windows support below is likely incomplete */
803
Guido van Rossum53807da2007-04-10 19:01:47 +0000804/* Cribbed from posix_lseek() */
805static PyObject *
806portable_lseek(int fd, PyObject *posobj, int whence)
807{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000808 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000809
810#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000811 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
812 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000813#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000814 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000815#endif
816#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000817 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000818#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000819#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000820 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000821#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000822 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000823#endif /* SEEK_SET */
824
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000825 if (posobj == NULL)
826 pos = 0;
827 else {
828 if(PyFloat_Check(posobj)) {
829 PyErr_SetString(PyExc_TypeError, "an integer is required");
830 return NULL;
831 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000832#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000833 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000834#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000835 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000836#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000837 if (PyErr_Occurred())
838 return NULL;
839 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000840
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000841 if (_PyVerify_fd(fd)) {
842 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000843#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000844 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000845#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000846 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000847#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000848 Py_END_ALLOW_THREADS
849 } else
850 res = -1;
851 if (res < 0)
852 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000853
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000854#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000855 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000856#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000857 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000858#endif
859}
860
Guido van Rossuma9e20242007-03-08 00:43:48 +0000861static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000862fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000863{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000864 PyObject *posobj;
865 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000866
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000867 if (self->fd < 0)
868 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000869
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000870 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
871 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000872
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000873 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000874}
875
876static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000877fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000878{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000879 if (self->fd < 0)
880 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000881
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000882 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000883}
884
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000885#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000886static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000887fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000888{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000889 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000890#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000891 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000892#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000893 int ret;
894 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000895
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000896 fd = self->fd;
897 if (fd < 0)
898 return err_closed();
899 if (!self->writable)
900 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000901
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000902 if (!PyArg_ParseTuple(args, "|O", &posobj))
903 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000904
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000905 if (posobj == Py_None || posobj == NULL) {
906 /* Get the current position. */
907 posobj = portable_lseek(fd, NULL, 1);
908 if (posobj == NULL)
909 return NULL;
910 }
911 else {
912 Py_INCREF(posobj);
913 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000914
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000915#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000916 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
917 so don't even try using it. */
918 {
919 PyObject *oldposobj, *tempposobj;
920 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000921
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000922 /* we save the file pointer position */
923 oldposobj = portable_lseek(fd, NULL, 1);
924 if (oldposobj == NULL) {
925 Py_DECREF(posobj);
926 return NULL;
927 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000928
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000929 /* we then move to the truncation position */
930 tempposobj = portable_lseek(fd, posobj, 0);
931 if (tempposobj == NULL) {
932 Py_DECREF(oldposobj);
933 Py_DECREF(posobj);
934 return NULL;
935 }
936 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000937
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000938 /* Truncate. Note that this may grow the file! */
939 Py_BEGIN_ALLOW_THREADS
940 errno = 0;
941 hFile = (HANDLE)_get_osfhandle(fd);
942 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
943 if (ret == 0) {
944 ret = SetEndOfFile(hFile) == 0;
945 if (ret)
946 errno = EACCES;
947 }
948 Py_END_ALLOW_THREADS
949
950 /* we restore the file pointer position in any case */
951 tempposobj = portable_lseek(fd, oldposobj, 0);
952 Py_DECREF(oldposobj);
953 if (tempposobj == NULL) {
954 Py_DECREF(posobj);
955 return NULL;
956 }
957 Py_DECREF(tempposobj);
958 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000959#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000960
961#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000962 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000963#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000964 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000965#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000966 if (PyErr_Occurred()){
967 Py_DECREF(posobj);
968 return NULL;
969 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000970
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000971 Py_BEGIN_ALLOW_THREADS
972 errno = 0;
973 ret = ftruncate(fd, pos);
974 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000975
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000976#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000977
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000978 if (ret != 0) {
979 Py_DECREF(posobj);
980 PyErr_SetFromErrno(PyExc_IOError);
981 return NULL;
982 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000983
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000984 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000985}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000986#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000987
988static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000989mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000990{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000991 if (self->readable) {
992 if (self->writable)
993 return "rb+";
994 else
995 return "rb";
996 }
997 else
998 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000999}
Guido van Rossuma9e20242007-03-08 00:43:48 +00001000
1001static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001002fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +00001003{
Martin v. Löwis767046a2011-10-14 15:35:36 +02001004 _Py_IDENTIFIER(name);
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001005 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001006
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001007 if (self->fd < 0)
1008 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +00001009
Martin v. Löwis767046a2011-10-14 15:35:36 +02001010 nameobj = _PyObject_GetAttrId((PyObject *) self, &PyId_name);
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001011 if (nameobj == NULL) {
1012 if (PyErr_ExceptionMatches(PyExc_AttributeError))
1013 PyErr_Clear();
1014 else
1015 return NULL;
1016 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
1017 self->fd, mode_string(self));
1018 }
1019 else {
1020 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
1021 nameobj, mode_string(self));
1022 Py_DECREF(nameobj);
1023 }
1024 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001025}
1026
1027static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001028fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +00001029{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001030 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +00001031
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001032 if (self->fd < 0)
1033 return err_closed();
1034 Py_BEGIN_ALLOW_THREADS
1035 res = isatty(self->fd);
1036 Py_END_ALLOW_THREADS
1037 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +00001038}
1039
Antoine Pitrou243757e2010-11-05 21:15:39 +00001040static PyObject *
1041fileio_getstate(fileio *self)
1042{
1043 PyErr_Format(PyExc_TypeError,
1044 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
1045 return NULL;
1046}
1047
Guido van Rossuma9e20242007-03-08 00:43:48 +00001048
1049PyDoc_STRVAR(fileio_doc,
Ross Lagerwall59142db2011-10-31 20:34:46 +02001050"file(name: str[, mode: str][, opener: None]) -> file IO object\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001051"\n"
1052"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001053"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001054"when opened for writing or appending; it will be truncated when\n"
1055"opened for writing. Add a '+' to the mode to allow simultaneous\n"
Ross Lagerwall59142db2011-10-31 20:34:46 +02001056"reading and writing. A custom opener can be used by passing a\n"
1057"callable as *opener*. The underlying file descriptor for the file\n"
1058"object is then obtained by calling opener with (*name*, *flags*).\n"
1059"*opener* must return an open file descriptor (passing os.open as\n"
1060"*opener* results in functionality similar to passing None).");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001061
1062PyDoc_STRVAR(read_doc,
1063"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1064"\n"
1065"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001066"In non-blocking mode, returns None if no data is available.\n"
1067"On end-of-file, returns ''.");
1068
1069PyDoc_STRVAR(readall_doc,
1070"readall() -> bytes. read all data from the file, returned as bytes.\n"
1071"\n"
1072"In non-blocking mode, returns as much as is immediately available,\n"
1073"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001074
1075PyDoc_STRVAR(write_doc,
1076"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1077"\n"
1078"Only makes one system call, so not all of the data may be written.\n"
1079"The number of bytes actually written is returned.");
1080
1081PyDoc_STRVAR(fileno_doc,
1082"fileno() -> int. \"file descriptor\".\n"
1083"\n"
1084"This is needed for lower-level file interfaces, such the fcntl module.");
1085
1086PyDoc_STRVAR(seek_doc,
1087"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1088"\n"
1089"Argument offset is a byte count. Optional argument whence defaults to\n"
1090"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1091"(move relative to current position, positive or negative), and 2 (move\n"
1092"relative to end of file, usually negative, although many platforms allow\n"
1093"seeking beyond the end of a file)."
1094"\n"
1095"Note that not all file objects are seekable.");
1096
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001097#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001098PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001099"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001100"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001101"Size defaults to the current file position, as returned by tell()."
1102"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001103#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001104
1105PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001106"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001107
1108PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001109"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001110
1111PyDoc_STRVAR(close_doc,
1112"close() -> None. Close the file.\n"
1113"\n"
1114"A closed file cannot be used for further I/O operations. close() may be\n"
1115"called more than once without error. Changes the fileno to -1.");
1116
1117PyDoc_STRVAR(isatty_doc,
1118"isatty() -> bool. True if the file is connected to a tty device.");
1119
Guido van Rossuma9e20242007-03-08 00:43:48 +00001120PyDoc_STRVAR(seekable_doc,
1121"seekable() -> bool. True if file supports random-access.");
1122
1123PyDoc_STRVAR(readable_doc,
1124"readable() -> bool. True if file was opened in a read mode.");
1125
1126PyDoc_STRVAR(writable_doc,
1127"writable() -> bool. True if file was opened in a write mode.");
1128
1129static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001130 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1131 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1132 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1133 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1134 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1135 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001136#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001137 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001138#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001139 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1140 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1141 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1142 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1143 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1144 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001145 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001146 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001147 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001148};
1149
Guido van Rossum53807da2007-04-10 19:01:47 +00001150/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1151
Guido van Rossumb0428152007-04-08 17:44:42 +00001152static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001153get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001154{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001155 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001156}
1157
1158static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001159get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001160{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001161 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001162}
1163
1164static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001165get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001166{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001167 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001168}
1169
1170static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001171 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1172 {"closefd", (getter)get_closefd, NULL,
1173 "True if the file descriptor will be closed"},
1174 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1175 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001176};
1177
Guido van Rossuma9e20242007-03-08 00:43:48 +00001178PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001179 PyVarObject_HEAD_INIT(NULL, 0)
1180 "_io.FileIO",
1181 sizeof(fileio),
1182 0,
1183 (destructor)fileio_dealloc, /* tp_dealloc */
1184 0, /* tp_print */
1185 0, /* tp_getattr */
1186 0, /* tp_setattr */
1187 0, /* tp_reserved */
1188 (reprfunc)fileio_repr, /* tp_repr */
1189 0, /* tp_as_number */
1190 0, /* tp_as_sequence */
1191 0, /* tp_as_mapping */
1192 0, /* tp_hash */
1193 0, /* tp_call */
1194 0, /* tp_str */
1195 PyObject_GenericGetAttr, /* tp_getattro */
1196 0, /* tp_setattro */
1197 0, /* tp_as_buffer */
1198 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1199 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1200 fileio_doc, /* tp_doc */
1201 (traverseproc)fileio_traverse, /* tp_traverse */
1202 (inquiry)fileio_clear, /* tp_clear */
1203 0, /* tp_richcompare */
1204 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1205 0, /* tp_iter */
1206 0, /* tp_iternext */
1207 fileio_methods, /* tp_methods */
1208 0, /* tp_members */
1209 fileio_getsetlist, /* tp_getset */
1210 0, /* tp_base */
1211 0, /* tp_dict */
1212 0, /* tp_descr_get */
1213 0, /* tp_descr_set */
1214 offsetof(fileio, dict), /* tp_dictoffset */
1215 fileio_init, /* tp_init */
1216 PyType_GenericAlloc, /* tp_alloc */
1217 fileio_new, /* tp_new */
1218 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001219};