blob: 8ea7c58aa8cd566ab533756199865f9466e1cfc5 [file] [log] [blame]
Guido van Rossuma9e20242007-03-08 00:43:48 +00001/* Author: Daniel Stutzbach */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
Antoine Pitroue033e062010-10-29 10:38:18 +00005#include "structmember.h"
Benjamin Peterson2614cda2010-03-21 22:36:19 +00006#ifdef HAVE_SYS_TYPES_H
Guido van Rossuma9e20242007-03-08 00:43:48 +00007#include <sys/types.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +00008#endif
9#ifdef HAVE_SYS_STAT_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000010#include <sys/stat.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000011#endif
12#ifdef HAVE_FCNTL_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000013#include <fcntl.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000014#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +000015#include <stddef.h> /* For offsetof */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000016#include "_iomodule.h"
Guido van Rossuma9e20242007-03-08 00:43:48 +000017
18/*
19 * Known likely problems:
20 *
21 * - Files larger then 2**32-1
22 * - Files with unicode filenames
23 * - Passing numbers greater than 2**32-1 when an integer is expected
24 * - Making it work on Windows and other oddball platforms
25 *
26 * To Do:
27 *
28 * - autoconfify header file inclusion
Guido van Rossuma9e20242007-03-08 00:43:48 +000029 */
30
31#ifdef MS_WINDOWS
32/* can simulate truncate with Win32 API functions; see file_truncate */
Thomas Hellerfdeee3a2007-07-12 11:21:36 +000033#define HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +000034#define WIN32_LEAN_AND_MEAN
35#include <windows.h>
36#endif
37
Christian Heimesa872de52008-12-05 08:26:55 +000038#if BUFSIZ < (8*1024)
39#define SMALLCHUNK (8*1024)
40#elif (BUFSIZ >= (2 << 25))
41#error "unreasonable BUFSIZ > 64MB defined"
42#else
43#define SMALLCHUNK BUFSIZ
44#endif
45
Guido van Rossuma9e20242007-03-08 00:43:48 +000046typedef struct {
Antoine Pitrouae4b4722010-05-05 16:31:07 +000047 PyObject_HEAD
48 int fd;
49 unsigned int readable : 1;
50 unsigned int writable : 1;
51 signed int seekable : 2; /* -1 means unknown */
52 unsigned int closefd : 1;
Antoine Pitroue033e062010-10-29 10:38:18 +000053 unsigned int deallocating: 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000054 PyObject *weakreflist;
55 PyObject *dict;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000056} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000057
Collin Winteraf334382007-03-08 21:46:15 +000058PyTypeObject PyFileIO_Type;
59
Guido van Rossuma9e20242007-03-08 00:43:48 +000060#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
61
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000062int
63_PyFileIO_closed(PyObject *self)
64{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000065 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000066}
Antoine Pitrou08838b62009-01-21 00:55:13 +000067
Antoine Pitroue033e062010-10-29 10:38:18 +000068/* Because this can call arbitrary code, it shouldn't be called when
69 the refcount is 0 (that is, not directly from tp_dealloc unless
70 the refcount has been temporarily re-incremented). */
71static PyObject *
72fileio_dealloc_warn(fileio *self, PyObject *source)
73{
74 if (self->fd >= 0 && self->closefd) {
75 PyObject *exc, *val, *tb;
76 PyErr_Fetch(&exc, &val, &tb);
77 if (PyErr_WarnFormat(PyExc_ResourceWarning, 1,
78 "unclosed file %R", source)) {
79 /* Spurious errors can appear at shutdown */
80 if (PyErr_ExceptionMatches(PyExc_Warning))
81 PyErr_WriteUnraisable((PyObject *) self);
82 }
83 PyErr_Restore(exc, val, tb);
84 }
85 Py_RETURN_NONE;
86}
87
Antoine Pitrou7fb111b2009-03-04 11:14:01 +000088static PyObject *
89portable_lseek(int fd, PyObject *posobj, int whence);
90
Antoine Pitroua28fcfd2009-03-13 23:42:55 +000091static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
92
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +000093/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +000094static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000095internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +000096{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000097 int err = 0;
98 int save_errno = 0;
99 if (self->fd >= 0) {
100 int fd = self->fd;
101 self->fd = -1;
102 /* fd is accessible and someone else may have closed it */
103 if (_PyVerify_fd(fd)) {
104 Py_BEGIN_ALLOW_THREADS
105 err = close(fd);
106 if (err < 0)
107 save_errno = errno;
108 Py_END_ALLOW_THREADS
109 } else {
110 save_errno = errno;
111 err = -1;
112 }
113 }
114 if (err < 0) {
115 errno = save_errno;
116 PyErr_SetFromErrno(PyExc_IOError);
117 return -1;
118 }
119 return 0;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000120}
121
122static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000123fileio_close(fileio *self)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000124{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000125 if (!self->closefd) {
126 self->fd = -1;
127 Py_RETURN_NONE;
128 }
Antoine Pitroue033e062010-10-29 10:38:18 +0000129 if (self->deallocating) {
130 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
131 if (r)
132 Py_DECREF(r);
133 else
134 PyErr_Clear();
135 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000136 errno = internal_close(self);
137 if (errno < 0)
138 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000139
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000140 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
141 "close", "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000142}
143
144static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000145fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000146{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000147 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000148
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000149 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000150
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000151 self = (fileio *) type->tp_alloc(type, 0);
152 if (self != NULL) {
153 self->fd = -1;
154 self->readable = 0;
155 self->writable = 0;
156 self->seekable = -1;
157 self->closefd = 1;
158 self->weakreflist = NULL;
159 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000160
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000161 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000162}
163
164/* On Unix, open will succeed for directories.
165 In Python, there should be no file objects referring to
166 directories, so we need a check. */
167
168static int
Antoine Pitrou9235b252012-07-06 18:48:24 +0200169dircheck(fileio* self, PyObject *nameobj)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000170{
171#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000172 struct stat buf;
173 if (self->fd < 0)
174 return 0;
175 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
Antoine Pitrou9235b252012-07-06 18:48:24 +0200176 errno = EISDIR;
177 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000178 return -1;
179 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000180#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000181 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000182}
183
Benjamin Peterson806d4022009-01-19 15:11:51 +0000184static int
185check_fd(int fd)
186{
187#if defined(HAVE_FSTAT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000188 struct stat buf;
189 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
190 PyObject *exc;
191 char *msg = strerror(EBADF);
192 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
193 EBADF, msg);
194 PyErr_SetObject(PyExc_OSError, exc);
195 Py_XDECREF(exc);
196 return -1;
197 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000198#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000199 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000200}
201
Guido van Rossuma9e20242007-03-08 00:43:48 +0000202
203static int
204fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
205{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000206 fileio *self = (fileio *) oself;
207 static char *kwlist[] = {"file", "mode", "closefd", NULL};
208 const char *name = NULL;
209 PyObject *nameobj, *stringobj = NULL;
210 char *mode = "r";
211 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000212#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000213 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000214#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000215 int ret = 0;
216 int rwa = 0, plus = 0, append = 0;
217 int flags = 0;
218 int fd = -1;
219 int closefd = 1;
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200220 int fd_is_own = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000221
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000222 assert(PyFileIO_Check(oself));
223 if (self->fd >= 0) {
Hynek Schlawack2cc71562012-05-25 10:05:53 +0200224 if (self->closefd) {
225 /* Have to close the existing file first. */
226 if (internal_close(self) < 0)
227 return -1;
228 }
229 else
230 self->fd = -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000231 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000232
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000233 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
234 kwlist, &nameobj, &mode, &closefd))
235 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000236
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000237 if (PyFloat_Check(nameobj)) {
238 PyErr_SetString(PyExc_TypeError,
239 "integer argument expected, got float");
240 return -1;
241 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000242
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000243 fd = PyLong_AsLong(nameobj);
244 if (fd < 0) {
245 if (!PyErr_Occurred()) {
246 PyErr_SetString(PyExc_ValueError,
247 "Negative filedescriptor");
248 return -1;
249 }
250 PyErr_Clear();
251 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000252
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000253#ifdef MS_WINDOWS
Antoine Pitrou13348842012-01-29 18:36:34 +0100254 if (PyUnicode_Check(nameobj)) {
255 int rv = _PyUnicode_HasNULChars(nameobj);
256 if (rv) {
257 if (rv != -1)
258 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
259 return -1;
260 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000261 widename = PyUnicode_AS_UNICODE(nameobj);
Antoine Pitrou13348842012-01-29 18:36:34 +0100262 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000263 if (widename == NULL)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000264#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000265 if (fd < 0)
266 {
Antoine Pitrou13348842012-01-29 18:36:34 +0100267 if (!PyUnicode_FSConverter(nameobj, &stringobj)) {
268 return -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000269 }
Antoine Pitrou13348842012-01-29 18:36:34 +0100270 name = PyBytes_AS_STRING(stringobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000271 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000272
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000273 s = mode;
274 while (*s) {
275 switch (*s++) {
276 case 'r':
277 if (rwa) {
278 bad_mode:
279 PyErr_SetString(PyExc_ValueError,
Georg Brandl28928ae2010-10-21 13:45:52 +0000280 "Must have exactly one of read/write/append "
281 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000282 goto error;
283 }
284 rwa = 1;
285 self->readable = 1;
286 break;
287 case 'w':
288 if (rwa)
289 goto bad_mode;
290 rwa = 1;
291 self->writable = 1;
292 flags |= O_CREAT | O_TRUNC;
293 break;
294 case 'a':
295 if (rwa)
296 goto bad_mode;
297 rwa = 1;
298 self->writable = 1;
299 flags |= O_CREAT;
300 append = 1;
301 break;
302 case 'b':
303 break;
304 case '+':
305 if (plus)
306 goto bad_mode;
307 self->readable = self->writable = 1;
308 plus = 1;
309 break;
310 default:
311 PyErr_Format(PyExc_ValueError,
312 "invalid mode: %.200s", mode);
313 goto error;
314 }
315 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000316
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000317 if (!rwa)
318 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000319
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000320 if (self->readable && self->writable)
321 flags |= O_RDWR;
322 else if (self->readable)
323 flags |= O_RDONLY;
324 else
325 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000326
327#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000328 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000329#endif
330
Walter Dörwald0e411482007-06-06 16:55:38 +0000331#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000332 if (append)
333 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000334#endif
335
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000336 if (fd >= 0) {
337 if (check_fd(fd))
338 goto error;
339 self->fd = fd;
340 self->closefd = closefd;
341 }
342 else {
343 self->closefd = 1;
344 if (!closefd) {
345 PyErr_SetString(PyExc_ValueError,
346 "Cannot use closefd=False with file name");
347 goto error;
348 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000349
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000350 Py_BEGIN_ALLOW_THREADS
351 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000352#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000353 if (widename != NULL)
354 self->fd = _wopen(widename, flags, 0666);
355 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000356#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000357 self->fd = open(name, flags, 0666);
358 Py_END_ALLOW_THREADS
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200359 fd_is_own = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000360 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000361#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000362 if (widename != NULL)
363 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
364 else
Christian Heimes0b489542007-10-31 19:20:48 +0000365#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000366 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
367 goto error;
368 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000369 }
Antoine Pitrou9235b252012-07-06 18:48:24 +0200370 if (dircheck(self, nameobj) < 0)
371 goto error;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000372
Victor Stinner89e34362011-01-07 18:47:22 +0000373#if defined(MS_WINDOWS) || defined(__CYGWIN__)
374 /* don't translate newlines (\r\n <=> \n) */
375 _setmode(self->fd, O_BINARY);
376#endif
377
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000378 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
379 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000380
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000381 if (append) {
382 /* For consistent behaviour, we explicitly seek to the
383 end of file (otherwise, it might be done only on the
384 first write()). */
385 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200386 if (pos == NULL)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000387 goto error;
388 Py_DECREF(pos);
389 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000390
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000391 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000392
393 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000394 ret = -1;
Hynek Schlawack9ed8b4e2012-06-21 20:20:25 +0200395 if (!fd_is_own)
396 self->fd = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000397 if (self->fd >= 0)
398 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000399
Guido van Rossuma9e20242007-03-08 00:43:48 +0000400 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000401 Py_CLEAR(stringobj);
402 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000403}
404
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000405static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000406fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000407{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000408 Py_VISIT(self->dict);
409 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000410}
411
412static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000413fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000414{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000415 Py_CLEAR(self->dict);
416 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000417}
418
Guido van Rossuma9e20242007-03-08 00:43:48 +0000419static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000420fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000421{
Antoine Pitroue033e062010-10-29 10:38:18 +0000422 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000423 if (_PyIOBase_finalize((PyObject *) self) < 0)
424 return;
425 _PyObject_GC_UNTRACK(self);
426 if (self->weakreflist != NULL)
427 PyObject_ClearWeakRefs((PyObject *) self);
428 Py_CLEAR(self->dict);
429 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000430}
431
432static PyObject *
433err_closed(void)
434{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000435 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
436 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000437}
438
439static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000440err_mode(char *action)
441{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000442 PyErr_Format(IO_STATE->unsupported_operation,
443 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000444 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000445}
446
447static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000448fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000449{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000450 if (self->fd < 0)
451 return err_closed();
452 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000453}
454
455static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000456fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000457{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000458 if (self->fd < 0)
459 return err_closed();
460 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000461}
462
463static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000464fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000465{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000466 if (self->fd < 0)
467 return err_closed();
468 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000469}
470
471static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000472fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000473{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000474 if (self->fd < 0)
475 return err_closed();
476 if (self->seekable < 0) {
477 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
478 if (pos == NULL) {
479 PyErr_Clear();
480 self->seekable = 0;
481 } else {
482 Py_DECREF(pos);
483 self->seekable = 1;
484 }
485 }
486 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000487}
488
489static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000490fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000491{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000492 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000493 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100494 int err;
Guido van Rossum53807da2007-04-10 19:01:47 +0000495
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000496 if (self->fd < 0)
497 return err_closed();
498 if (!self->readable)
499 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000500
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000501 if (!PyArg_ParseTuple(args, "w*", &pbuf))
502 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000503
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000504 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000505 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000506 Py_BEGIN_ALLOW_THREADS
507 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000508#if defined(MS_WIN64) || defined(MS_WINDOWS)
509 if (len > INT_MAX)
510 len = INT_MAX;
511 n = read(self->fd, pbuf.buf, (int)len);
512#else
Victor Stinner72344792011-01-11 00:04:12 +0000513 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000514#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000515 Py_END_ALLOW_THREADS
516 } else
517 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100518 err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000519 PyBuffer_Release(&pbuf);
520 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100521 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000522 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100523 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000524 PyErr_SetFromErrno(PyExc_IOError);
525 return NULL;
526 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000527
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000528 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000529}
530
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000531static size_t
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000532new_buffersize(fileio *self, size_t currentsize)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000533{
534#ifdef HAVE_FSTAT
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000535 off_t pos, end;
536 struct stat st;
537 if (fstat(self->fd, &st) == 0) {
538 end = st.st_size;
539 pos = lseek(self->fd, 0L, SEEK_CUR);
540 /* Files claiming a size smaller than SMALLCHUNK may
541 actually be streaming pseudo-files. In this case, we
542 apply the more aggressive algorithm below.
543 */
544 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
545 /* Add 1 so if the file were to grow we'd notice. */
546 return currentsize + end - pos + 1;
547 }
548 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000549#endif
Nadeem Vawdad41a98b2011-10-13 13:34:16 +0200550 /* Expand the buffer by an amount proportional to the current size,
551 giving us amortized linear-time behavior. Use a less-than-double
552 growth factor to avoid excessive allocation. */
553 return currentsize + (currentsize >> 3) + 6;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000554}
555
Guido van Rossum7165cb12007-07-10 06:54:34 +0000556static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000557fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000558{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000559 PyObject *result;
560 Py_ssize_t total = 0;
Victor Stinnerc44057d2013-01-03 03:33:21 +0100561 Py_ssize_t n;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000562
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200563 if (self->fd < 0)
564 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000565 if (!_PyVerify_fd(self->fd))
566 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000567
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000568 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
569 if (result == NULL)
570 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000571
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000572 while (1) {
573 size_t newsize = new_buffersize(self, total);
574 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
575 PyErr_SetString(PyExc_OverflowError,
576 "unbounded read returned more bytes "
577 "than a Python string can hold ");
578 Py_DECREF(result);
579 return NULL;
580 }
Christian Heimesa872de52008-12-05 08:26:55 +0000581
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000582 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
583 if (_PyBytes_Resize(&result, newsize) < 0) {
584 if (total == 0) {
585 Py_DECREF(result);
586 return NULL;
587 }
588 PyErr_Clear();
589 break;
590 }
591 }
592 Py_BEGIN_ALLOW_THREADS
593 errno = 0;
Victor Stinnerc44057d2013-01-03 03:33:21 +0100594 n = newsize - total;
595#if defined(MS_WIN64) || defined(MS_WINDOWS)
596 if (n > INT_MAX)
597 n = INT_MAX;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000598 n = read(self->fd,
599 PyBytes_AS_STRING(result) + total,
Victor Stinnerc44057d2013-01-03 03:33:21 +0100600 (int)n);
601#else
602 n = read(self->fd,
603 PyBytes_AS_STRING(result) + total,
604 n);
605#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000606 Py_END_ALLOW_THREADS
607 if (n == 0)
608 break;
609 if (n < 0) {
Gregory P. Smith51359922012-06-23 23:55:39 -0700610 if (errno == EINTR) {
611 if (PyErr_CheckSignals()) {
612 Py_DECREF(result);
613 return NULL;
614 }
615 continue;
616 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000617 if (total > 0)
618 break;
619 if (errno == EAGAIN) {
620 Py_DECREF(result);
621 Py_RETURN_NONE;
622 }
623 Py_DECREF(result);
624 PyErr_SetFromErrno(PyExc_IOError);
625 return NULL;
626 }
627 total += n;
628 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000629
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000630 if (PyBytes_GET_SIZE(result) > total) {
631 if (_PyBytes_Resize(&result, total) < 0) {
632 /* This should never happen, but just in case */
633 Py_DECREF(result);
634 return NULL;
635 }
636 }
637 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000638}
639
Guido van Rossuma9e20242007-03-08 00:43:48 +0000640static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000641fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000642{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000643 char *ptr;
644 Py_ssize_t n;
645 Py_ssize_t size = -1;
646 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000647
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000648 if (self->fd < 0)
649 return err_closed();
650 if (!self->readable)
651 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000652
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000653 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
654 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000655
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000656 if (size < 0) {
657 return fileio_readall(self);
658 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000659
Victor Stinnerc655a722011-07-05 11:31:49 +0200660#if defined(MS_WIN64) || defined(MS_WINDOWS)
661 if (size > INT_MAX)
662 size = INT_MAX;
663#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000664 bytes = PyBytes_FromStringAndSize(NULL, size);
665 if (bytes == NULL)
666 return NULL;
667 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000668
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000669 if (_PyVerify_fd(self->fd)) {
670 Py_BEGIN_ALLOW_THREADS
671 errno = 0;
Victor Stinnerc655a722011-07-05 11:31:49 +0200672#if defined(MS_WIN64) || defined(MS_WINDOWS)
673 n = read(self->fd, ptr, (int)size);
674#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000675 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200676#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000677 Py_END_ALLOW_THREADS
678 } else
679 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000680
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000681 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100682 int err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000683 Py_DECREF(bytes);
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100684 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000685 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100686 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000687 PyErr_SetFromErrno(PyExc_IOError);
688 return NULL;
689 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000690
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000691 if (n != size) {
692 if (_PyBytes_Resize(&bytes, n) < 0) {
693 Py_DECREF(bytes);
694 return NULL;
695 }
696 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000697
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000698 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000699}
700
701static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000702fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000703{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000704 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000705 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100706 int err;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000707
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000708 if (self->fd < 0)
709 return err_closed();
710 if (!self->writable)
711 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000712
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000713 if (!PyArg_ParseTuple(args, "y*", &pbuf))
714 return NULL;
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 Stinnere6edec22011-01-04 00:29:35 +0000719 len = pbuf.len;
720#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100721 if (len > 32767 && isatty(self->fd)) {
722 /* Issue #11395: the Windows console returns an error (12: not
723 enough space error) on writing into stdout if stdout mode is
724 binary and the length is greater than 66,000 bytes (or less,
725 depending on heap usage). */
726 len = 32767;
727 }
728 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000729 len = INT_MAX;
730 n = write(self->fd, pbuf.buf, (int)len);
731#else
Victor Stinner72344792011-01-11 00:04:12 +0000732 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000733#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000734 Py_END_ALLOW_THREADS
735 } else
736 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100737 err = errno;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000738
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000739 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000740
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000741 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100742 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000743 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100744 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000745 PyErr_SetFromErrno(PyExc_IOError);
746 return NULL;
747 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000748
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000749 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000750}
751
Guido van Rossum53807da2007-04-10 19:01:47 +0000752/* XXX Windows support below is likely incomplete */
753
Guido van Rossum53807da2007-04-10 19:01:47 +0000754/* Cribbed from posix_lseek() */
755static PyObject *
756portable_lseek(int fd, PyObject *posobj, int whence)
757{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000758 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000759
760#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000761 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
762 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000763#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000764 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000765#endif
766#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000767 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000768#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000769#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000770 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000771#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000772 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000773#endif /* SEEK_SET */
774
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000775 if (posobj == NULL)
776 pos = 0;
777 else {
778 if(PyFloat_Check(posobj)) {
779 PyErr_SetString(PyExc_TypeError, "an integer is required");
780 return NULL;
781 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000782#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000783 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000784#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000785 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000786#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000787 if (PyErr_Occurred())
788 return NULL;
789 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000790
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000791 if (_PyVerify_fd(fd)) {
792 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000793#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000794 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000795#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000796 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000797#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000798 Py_END_ALLOW_THREADS
799 } else
800 res = -1;
801 if (res < 0)
802 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000803
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000804#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000805 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000806#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000807 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000808#endif
809}
810
Guido van Rossuma9e20242007-03-08 00:43:48 +0000811static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000812fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000813{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000814 PyObject *posobj;
815 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000816
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000817 if (self->fd < 0)
818 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000819
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000820 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
821 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000822
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000823 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000824}
825
826static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000827fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000828{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000829 if (self->fd < 0)
830 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000831
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000832 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000833}
834
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000835#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000836static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000837fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000838{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000839 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000840#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000841 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000842#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000843 int ret;
844 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000845
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000846 fd = self->fd;
847 if (fd < 0)
848 return err_closed();
849 if (!self->writable)
850 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000851
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000852 if (!PyArg_ParseTuple(args, "|O", &posobj))
853 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000854
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000855 if (posobj == Py_None || posobj == NULL) {
856 /* Get the current position. */
857 posobj = portable_lseek(fd, NULL, 1);
858 if (posobj == NULL)
859 return NULL;
860 }
861 else {
862 Py_INCREF(posobj);
863 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000864
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000865#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000866 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
867 so don't even try using it. */
868 {
869 PyObject *oldposobj, *tempposobj;
870 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000871
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000872 /* we save the file pointer position */
873 oldposobj = portable_lseek(fd, NULL, 1);
874 if (oldposobj == NULL) {
875 Py_DECREF(posobj);
876 return NULL;
877 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000878
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000879 /* we then move to the truncation position */
880 tempposobj = portable_lseek(fd, posobj, 0);
881 if (tempposobj == NULL) {
882 Py_DECREF(oldposobj);
883 Py_DECREF(posobj);
884 return NULL;
885 }
886 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000887
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000888 /* Truncate. Note that this may grow the file! */
889 Py_BEGIN_ALLOW_THREADS
890 errno = 0;
891 hFile = (HANDLE)_get_osfhandle(fd);
892 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
893 if (ret == 0) {
894 ret = SetEndOfFile(hFile) == 0;
895 if (ret)
896 errno = EACCES;
897 }
898 Py_END_ALLOW_THREADS
899
900 /* we restore the file pointer position in any case */
901 tempposobj = portable_lseek(fd, oldposobj, 0);
902 Py_DECREF(oldposobj);
903 if (tempposobj == NULL) {
904 Py_DECREF(posobj);
905 return NULL;
906 }
907 Py_DECREF(tempposobj);
908 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000909#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000910
911#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000912 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000913#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000914 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000915#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000916 if (PyErr_Occurred()){
917 Py_DECREF(posobj);
918 return NULL;
919 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000920
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000921 Py_BEGIN_ALLOW_THREADS
922 errno = 0;
923 ret = ftruncate(fd, pos);
924 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000925
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000926#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000927
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000928 if (ret != 0) {
929 Py_DECREF(posobj);
930 PyErr_SetFromErrno(PyExc_IOError);
931 return NULL;
932 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000933
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000934 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000935}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000936#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000937
938static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000939mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000940{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000941 if (self->readable) {
942 if (self->writable)
943 return "rb+";
944 else
945 return "rb";
946 }
947 else
948 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000949}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000950
951static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000952fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000953{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000954 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000955
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000956 if (self->fd < 0)
957 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000958
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000959 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
960 if (nameobj == NULL) {
961 if (PyErr_ExceptionMatches(PyExc_AttributeError))
962 PyErr_Clear();
963 else
964 return NULL;
965 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
966 self->fd, mode_string(self));
967 }
968 else {
969 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
970 nameobj, mode_string(self));
971 Py_DECREF(nameobj);
972 }
973 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000974}
975
976static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000977fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000978{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000979 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000980
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000981 if (self->fd < 0)
982 return err_closed();
983 Py_BEGIN_ALLOW_THREADS
984 res = isatty(self->fd);
985 Py_END_ALLOW_THREADS
986 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000987}
988
Antoine Pitrou243757e2010-11-05 21:15:39 +0000989static PyObject *
990fileio_getstate(fileio *self)
991{
992 PyErr_Format(PyExc_TypeError,
993 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
994 return NULL;
995}
996
Guido van Rossuma9e20242007-03-08 00:43:48 +0000997
998PyDoc_STRVAR(fileio_doc,
999"file(name: str[, mode: str]) -> file IO object\n"
1000"\n"
1001"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001002"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001003"when opened for writing or appending; it will be truncated when\n"
1004"opened for writing. Add a '+' to the mode to allow simultaneous\n"
1005"reading and writing.");
1006
1007PyDoc_STRVAR(read_doc,
1008"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1009"\n"
1010"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001011"In non-blocking mode, returns None if no data is available.\n"
1012"On end-of-file, returns ''.");
1013
1014PyDoc_STRVAR(readall_doc,
1015"readall() -> bytes. read all data from the file, returned as bytes.\n"
1016"\n"
1017"In non-blocking mode, returns as much as is immediately available,\n"
1018"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001019
1020PyDoc_STRVAR(write_doc,
1021"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1022"\n"
1023"Only makes one system call, so not all of the data may be written.\n"
1024"The number of bytes actually written is returned.");
1025
1026PyDoc_STRVAR(fileno_doc,
1027"fileno() -> int. \"file descriptor\".\n"
1028"\n"
1029"This is needed for lower-level file interfaces, such the fcntl module.");
1030
1031PyDoc_STRVAR(seek_doc,
1032"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1033"\n"
1034"Argument offset is a byte count. Optional argument whence defaults to\n"
1035"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1036"(move relative to current position, positive or negative), and 2 (move\n"
1037"relative to end of file, usually negative, although many platforms allow\n"
1038"seeking beyond the end of a file)."
1039"\n"
1040"Note that not all file objects are seekable.");
1041
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001042#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001043PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001044"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001045"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001046"Size defaults to the current file position, as returned by tell()."
1047"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001048#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001049
1050PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001051"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001052
1053PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001054"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001055
1056PyDoc_STRVAR(close_doc,
1057"close() -> None. Close the file.\n"
1058"\n"
1059"A closed file cannot be used for further I/O operations. close() may be\n"
1060"called more than once without error. Changes the fileno to -1.");
1061
1062PyDoc_STRVAR(isatty_doc,
1063"isatty() -> bool. True if the file is connected to a tty device.");
1064
Guido van Rossuma9e20242007-03-08 00:43:48 +00001065PyDoc_STRVAR(seekable_doc,
1066"seekable() -> bool. True if file supports random-access.");
1067
1068PyDoc_STRVAR(readable_doc,
1069"readable() -> bool. True if file was opened in a read mode.");
1070
1071PyDoc_STRVAR(writable_doc,
1072"writable() -> bool. True if file was opened in a write mode.");
1073
1074static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001075 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1076 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1077 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1078 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1079 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1080 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001081#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001082 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001083#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001084 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1085 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1086 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1087 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1088 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1089 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001090 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001091 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001092 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001093};
1094
Guido van Rossum53807da2007-04-10 19:01:47 +00001095/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1096
Guido van Rossumb0428152007-04-08 17:44:42 +00001097static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001098get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001099{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001100 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001101}
1102
1103static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001104get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001105{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001106 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001107}
1108
1109static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001110get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001111{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001112 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001113}
1114
1115static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001116 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1117 {"closefd", (getter)get_closefd, NULL,
1118 "True if the file descriptor will be closed"},
1119 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1120 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001121};
1122
Guido van Rossuma9e20242007-03-08 00:43:48 +00001123PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001124 PyVarObject_HEAD_INIT(NULL, 0)
1125 "_io.FileIO",
1126 sizeof(fileio),
1127 0,
1128 (destructor)fileio_dealloc, /* tp_dealloc */
1129 0, /* tp_print */
1130 0, /* tp_getattr */
1131 0, /* tp_setattr */
1132 0, /* tp_reserved */
1133 (reprfunc)fileio_repr, /* tp_repr */
1134 0, /* tp_as_number */
1135 0, /* tp_as_sequence */
1136 0, /* tp_as_mapping */
1137 0, /* tp_hash */
1138 0, /* tp_call */
1139 0, /* tp_str */
1140 PyObject_GenericGetAttr, /* tp_getattro */
1141 0, /* tp_setattro */
1142 0, /* tp_as_buffer */
1143 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1144 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1145 fileio_doc, /* tp_doc */
1146 (traverseproc)fileio_traverse, /* tp_traverse */
1147 (inquiry)fileio_clear, /* tp_clear */
1148 0, /* tp_richcompare */
1149 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1150 0, /* tp_iter */
1151 0, /* tp_iternext */
1152 fileio_methods, /* tp_methods */
1153 0, /* tp_members */
1154 fileio_getsetlist, /* tp_getset */
1155 0, /* tp_base */
1156 0, /* tp_dict */
1157 0, /* tp_descr_get */
1158 0, /* tp_descr_set */
1159 offsetof(fileio, dict), /* tp_dictoffset */
1160 fileio_init, /* tp_init */
1161 PyType_GenericAlloc, /* tp_alloc */
1162 fileio_new, /* tp_new */
1163 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001164};