blob: c51d69798bdbf073b0c0bf7daefcdb09a4a58ad0 [file] [log] [blame]
Guido van Rossuma9e20242007-03-08 00:43:48 +00001/* Author: Daniel Stutzbach */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
Antoine Pitroue033e062010-10-29 10:38:18 +00005#include "structmember.h"
Benjamin Peterson2614cda2010-03-21 22:36:19 +00006#ifdef HAVE_SYS_TYPES_H
Guido van Rossuma9e20242007-03-08 00:43:48 +00007#include <sys/types.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +00008#endif
9#ifdef HAVE_SYS_STAT_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000010#include <sys/stat.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000011#endif
12#ifdef HAVE_FCNTL_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000013#include <fcntl.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000014#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +000015#include <stddef.h> /* For offsetof */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000016#include "_iomodule.h"
Guido van Rossuma9e20242007-03-08 00:43:48 +000017
18/*
19 * Known likely problems:
20 *
21 * - Files larger then 2**32-1
22 * - Files with unicode filenames
23 * - Passing numbers greater than 2**32-1 when an integer is expected
24 * - Making it work on Windows and other oddball platforms
25 *
26 * To Do:
27 *
28 * - autoconfify header file inclusion
Guido van Rossuma9e20242007-03-08 00:43:48 +000029 */
30
31#ifdef MS_WINDOWS
32/* can simulate truncate with Win32 API functions; see file_truncate */
Thomas Hellerfdeee3a2007-07-12 11:21:36 +000033#define HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +000034#define WIN32_LEAN_AND_MEAN
35#include <windows.h>
36#endif
37
Christian Heimesa872de52008-12-05 08:26:55 +000038#if BUFSIZ < (8*1024)
39#define SMALLCHUNK (8*1024)
40#elif (BUFSIZ >= (2 << 25))
41#error "unreasonable BUFSIZ > 64MB defined"
42#else
43#define SMALLCHUNK BUFSIZ
44#endif
45
Guido van Rossuma9e20242007-03-08 00:43:48 +000046typedef struct {
Antoine Pitrouae4b4722010-05-05 16:31:07 +000047 PyObject_HEAD
48 int fd;
49 unsigned int readable : 1;
50 unsigned int writable : 1;
51 signed int seekable : 2; /* -1 means unknown */
52 unsigned int closefd : 1;
Antoine Pitroue033e062010-10-29 10:38:18 +000053 unsigned int deallocating: 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000054 PyObject *weakreflist;
55 PyObject *dict;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000056} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000057
Collin Winteraf334382007-03-08 21:46:15 +000058PyTypeObject PyFileIO_Type;
59
Guido van Rossuma9e20242007-03-08 00:43:48 +000060#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
61
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000062int
63_PyFileIO_closed(PyObject *self)
64{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000065 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000066}
Antoine Pitrou08838b62009-01-21 00:55:13 +000067
Antoine Pitroue033e062010-10-29 10:38:18 +000068/* Because this can call arbitrary code, it shouldn't be called when
69 the refcount is 0 (that is, not directly from tp_dealloc unless
70 the refcount has been temporarily re-incremented). */
71static PyObject *
72fileio_dealloc_warn(fileio *self, PyObject *source)
73{
74 if (self->fd >= 0 && self->closefd) {
75 PyObject *exc, *val, *tb;
76 PyErr_Fetch(&exc, &val, &tb);
77 if (PyErr_WarnFormat(PyExc_ResourceWarning, 1,
78 "unclosed file %R", source)) {
79 /* Spurious errors can appear at shutdown */
80 if (PyErr_ExceptionMatches(PyExc_Warning))
81 PyErr_WriteUnraisable((PyObject *) self);
82 }
83 PyErr_Restore(exc, val, tb);
84 }
85 Py_RETURN_NONE;
86}
87
Antoine Pitrou7fb111b2009-03-04 11:14:01 +000088static PyObject *
89portable_lseek(int fd, PyObject *posobj, int whence);
90
Antoine Pitroua28fcfd2009-03-13 23:42:55 +000091static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
92
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +000093/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +000094static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000095internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +000096{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000097 int err = 0;
98 int save_errno = 0;
99 if (self->fd >= 0) {
100 int fd = self->fd;
101 self->fd = -1;
102 /* fd is accessible and someone else may have closed it */
103 if (_PyVerify_fd(fd)) {
104 Py_BEGIN_ALLOW_THREADS
105 err = close(fd);
106 if (err < 0)
107 save_errno = errno;
108 Py_END_ALLOW_THREADS
109 } else {
110 save_errno = errno;
111 err = -1;
112 }
113 }
114 if (err < 0) {
115 errno = save_errno;
116 PyErr_SetFromErrno(PyExc_IOError);
117 return -1;
118 }
119 return 0;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000120}
121
122static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000123fileio_close(fileio *self)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000124{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000125 if (!self->closefd) {
126 self->fd = -1;
127 Py_RETURN_NONE;
128 }
Antoine Pitroue033e062010-10-29 10:38:18 +0000129 if (self->deallocating) {
130 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
131 if (r)
132 Py_DECREF(r);
133 else
134 PyErr_Clear();
135 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000136 errno = internal_close(self);
137 if (errno < 0)
138 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000139
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000140 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
141 "close", "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000142}
143
144static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000145fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000146{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000147 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000148
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000149 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000150
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000151 self = (fileio *) type->tp_alloc(type, 0);
152 if (self != NULL) {
153 self->fd = -1;
154 self->readable = 0;
155 self->writable = 0;
156 self->seekable = -1;
157 self->closefd = 1;
158 self->weakreflist = NULL;
159 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000160
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000161 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000162}
163
164/* On Unix, open will succeed for directories.
165 In Python, there should be no file objects referring to
166 directories, so we need a check. */
167
168static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000169dircheck(fileio* self, const char *name)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000170{
171#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000172 struct stat buf;
173 if (self->fd < 0)
174 return 0;
175 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
176 char *msg = strerror(EISDIR);
177 PyObject *exc;
178 if (internal_close(self))
179 return -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000180
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000181 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
182 EISDIR, msg, name);
183 PyErr_SetObject(PyExc_IOError, exc);
184 Py_XDECREF(exc);
185 return -1;
186 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000187#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000188 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000189}
190
Benjamin Peterson806d4022009-01-19 15:11:51 +0000191static int
192check_fd(int fd)
193{
194#if defined(HAVE_FSTAT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000195 struct stat buf;
196 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
197 PyObject *exc;
198 char *msg = strerror(EBADF);
199 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
200 EBADF, msg);
201 PyErr_SetObject(PyExc_OSError, exc);
202 Py_XDECREF(exc);
203 return -1;
204 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000205#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000206 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000207}
208
Guido van Rossuma9e20242007-03-08 00:43:48 +0000209
210static int
211fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
212{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000213 fileio *self = (fileio *) oself;
214 static char *kwlist[] = {"file", "mode", "closefd", NULL};
215 const char *name = NULL;
216 PyObject *nameobj, *stringobj = NULL;
217 char *mode = "r";
218 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000219#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000220 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000221#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000222 int ret = 0;
223 int rwa = 0, plus = 0, append = 0;
224 int flags = 0;
225 int fd = -1;
226 int closefd = 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000227
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000228 assert(PyFileIO_Check(oself));
229 if (self->fd >= 0) {
Hynek Schlawack2cc71562012-05-25 10:05:53 +0200230 if (self->closefd) {
231 /* Have to close the existing file first. */
232 if (internal_close(self) < 0)
233 return -1;
234 }
235 else
236 self->fd = -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000237 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000238
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000239 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
240 kwlist, &nameobj, &mode, &closefd))
241 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000242
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000243 if (PyFloat_Check(nameobj)) {
244 PyErr_SetString(PyExc_TypeError,
245 "integer argument expected, got float");
246 return -1;
247 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000248
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000249 fd = PyLong_AsLong(nameobj);
250 if (fd < 0) {
251 if (!PyErr_Occurred()) {
252 PyErr_SetString(PyExc_ValueError,
253 "Negative filedescriptor");
254 return -1;
255 }
256 PyErr_Clear();
257 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000258
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000259#ifdef MS_WINDOWS
Antoine Pitrou13348842012-01-29 18:36:34 +0100260 if (PyUnicode_Check(nameobj)) {
261 int rv = _PyUnicode_HasNULChars(nameobj);
262 if (rv) {
263 if (rv != -1)
264 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
265 return -1;
266 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000267 widename = PyUnicode_AS_UNICODE(nameobj);
Antoine Pitrou13348842012-01-29 18:36:34 +0100268 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000269 if (widename == NULL)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000270#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000271 if (fd < 0)
272 {
Antoine Pitrou13348842012-01-29 18:36:34 +0100273 if (!PyUnicode_FSConverter(nameobj, &stringobj)) {
274 return -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000275 }
Antoine Pitrou13348842012-01-29 18:36:34 +0100276 name = PyBytes_AS_STRING(stringobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000277 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000278
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000279 s = mode;
280 while (*s) {
281 switch (*s++) {
282 case 'r':
283 if (rwa) {
284 bad_mode:
285 PyErr_SetString(PyExc_ValueError,
Georg Brandl28928ae2010-10-21 13:45:52 +0000286 "Must have exactly one of read/write/append "
287 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000288 goto error;
289 }
290 rwa = 1;
291 self->readable = 1;
292 break;
293 case 'w':
294 if (rwa)
295 goto bad_mode;
296 rwa = 1;
297 self->writable = 1;
298 flags |= O_CREAT | O_TRUNC;
299 break;
300 case 'a':
301 if (rwa)
302 goto bad_mode;
303 rwa = 1;
304 self->writable = 1;
305 flags |= O_CREAT;
306 append = 1;
307 break;
308 case 'b':
309 break;
310 case '+':
311 if (plus)
312 goto bad_mode;
313 self->readable = self->writable = 1;
314 plus = 1;
315 break;
316 default:
317 PyErr_Format(PyExc_ValueError,
318 "invalid mode: %.200s", mode);
319 goto error;
320 }
321 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000322
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000323 if (!rwa)
324 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000325
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000326 if (self->readable && self->writable)
327 flags |= O_RDWR;
328 else if (self->readable)
329 flags |= O_RDONLY;
330 else
331 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000332
333#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000334 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000335#endif
336
Walter Dörwald0e411482007-06-06 16:55:38 +0000337#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000338 if (append)
339 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000340#endif
341
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000342 if (fd >= 0) {
343 if (check_fd(fd))
344 goto error;
345 self->fd = fd;
346 self->closefd = closefd;
347 }
348 else {
349 self->closefd = 1;
350 if (!closefd) {
351 PyErr_SetString(PyExc_ValueError,
352 "Cannot use closefd=False with file name");
353 goto error;
354 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000355
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000356 Py_BEGIN_ALLOW_THREADS
357 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000358#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000359 if (widename != NULL)
360 self->fd = _wopen(widename, flags, 0666);
361 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000362#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000363 self->fd = open(name, flags, 0666);
364 Py_END_ALLOW_THREADS
365 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000366#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000367 if (widename != NULL)
368 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
369 else
Christian Heimes0b489542007-10-31 19:20:48 +0000370#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000371 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
372 goto error;
373 }
Benjamin Peterson430d4692010-10-30 23:13:57 +0000374 if (dircheck(self, name) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000375 goto error;
376 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000377
Victor Stinner89e34362011-01-07 18:47:22 +0000378#if defined(MS_WINDOWS) || defined(__CYGWIN__)
379 /* don't translate newlines (\r\n <=> \n) */
380 _setmode(self->fd, O_BINARY);
381#endif
382
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000383 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
384 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000385
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000386 if (append) {
387 /* For consistent behaviour, we explicitly seek to the
388 end of file (otherwise, it might be done only on the
389 first write()). */
390 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000391 if (pos == NULL) {
392 if (closefd) {
393 close(self->fd);
394 self->fd = -1;
395 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000396 goto error;
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000397 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000398 Py_DECREF(pos);
399 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000400
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000401 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000402
403 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000404 ret = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000405 if (self->fd >= 0)
406 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000407
Guido van Rossuma9e20242007-03-08 00:43:48 +0000408 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000409 Py_CLEAR(stringobj);
410 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000411}
412
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000413static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000414fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000415{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000416 Py_VISIT(self->dict);
417 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000418}
419
420static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000421fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000422{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000423 Py_CLEAR(self->dict);
424 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000425}
426
Guido van Rossuma9e20242007-03-08 00:43:48 +0000427static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000428fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000429{
Antoine Pitroue033e062010-10-29 10:38:18 +0000430 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000431 if (_PyIOBase_finalize((PyObject *) self) < 0)
432 return;
433 _PyObject_GC_UNTRACK(self);
434 if (self->weakreflist != NULL)
435 PyObject_ClearWeakRefs((PyObject *) self);
436 Py_CLEAR(self->dict);
437 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000438}
439
440static PyObject *
441err_closed(void)
442{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000443 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
444 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000445}
446
447static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000448err_mode(char *action)
449{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000450 PyErr_Format(IO_STATE->unsupported_operation,
451 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000452 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000453}
454
455static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000456fileio_fileno(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 PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000461}
462
463static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000464fileio_readable(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->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000469}
470
471static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000472fileio_writable(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 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000477}
478
479static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000480fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000481{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000482 if (self->fd < 0)
483 return err_closed();
484 if (self->seekable < 0) {
485 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
486 if (pos == NULL) {
487 PyErr_Clear();
488 self->seekable = 0;
489 } else {
490 Py_DECREF(pos);
491 self->seekable = 1;
492 }
493 }
494 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000495}
496
497static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000498fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000499{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000500 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000501 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100502 int err;
Guido van Rossum53807da2007-04-10 19:01:47 +0000503
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000504 if (self->fd < 0)
505 return err_closed();
506 if (!self->readable)
507 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000508
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000509 if (!PyArg_ParseTuple(args, "w*", &pbuf))
510 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000511
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000512 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000513 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000514 Py_BEGIN_ALLOW_THREADS
515 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000516#if defined(MS_WIN64) || defined(MS_WINDOWS)
517 if (len > INT_MAX)
518 len = INT_MAX;
519 n = read(self->fd, pbuf.buf, (int)len);
520#else
Victor Stinner72344792011-01-11 00:04:12 +0000521 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000522#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000523 Py_END_ALLOW_THREADS
524 } else
525 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100526 err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000527 PyBuffer_Release(&pbuf);
528 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100529 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000530 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100531 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000532 PyErr_SetFromErrno(PyExc_IOError);
533 return NULL;
534 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000535
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000536 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000537}
538
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000539static size_t
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000540new_buffersize(fileio *self, size_t currentsize)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000541{
542#ifdef HAVE_FSTAT
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000543 off_t pos, end;
544 struct stat st;
545 if (fstat(self->fd, &st) == 0) {
546 end = st.st_size;
547 pos = lseek(self->fd, 0L, SEEK_CUR);
548 /* Files claiming a size smaller than SMALLCHUNK may
549 actually be streaming pseudo-files. In this case, we
550 apply the more aggressive algorithm below.
551 */
552 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
553 /* Add 1 so if the file were to grow we'd notice. */
554 return currentsize + end - pos + 1;
555 }
556 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000557#endif
Nadeem Vawdad41a98b2011-10-13 13:34:16 +0200558 /* Expand the buffer by an amount proportional to the current size,
559 giving us amortized linear-time behavior. Use a less-than-double
560 growth factor to avoid excessive allocation. */
561 return currentsize + (currentsize >> 3) + 6;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000562}
563
Guido van Rossum7165cb12007-07-10 06:54:34 +0000564static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000565fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000566{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000567 PyObject *result;
568 Py_ssize_t total = 0;
569 int n;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000570
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200571 if (self->fd < 0)
572 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000573 if (!_PyVerify_fd(self->fd))
574 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000575
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000576 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
577 if (result == NULL)
578 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000579
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000580 while (1) {
581 size_t newsize = new_buffersize(self, total);
582 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
583 PyErr_SetString(PyExc_OverflowError,
584 "unbounded read returned more bytes "
585 "than a Python string can hold ");
586 Py_DECREF(result);
587 return NULL;
588 }
Christian Heimesa872de52008-12-05 08:26:55 +0000589
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000590 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
591 if (_PyBytes_Resize(&result, newsize) < 0) {
592 if (total == 0) {
593 Py_DECREF(result);
594 return NULL;
595 }
596 PyErr_Clear();
597 break;
598 }
599 }
600 Py_BEGIN_ALLOW_THREADS
601 errno = 0;
602 n = read(self->fd,
603 PyBytes_AS_STRING(result) + total,
604 newsize - total);
605 Py_END_ALLOW_THREADS
606 if (n == 0)
607 break;
608 if (n < 0) {
609 if (total > 0)
610 break;
611 if (errno == EAGAIN) {
612 Py_DECREF(result);
613 Py_RETURN_NONE;
614 }
615 Py_DECREF(result);
616 PyErr_SetFromErrno(PyExc_IOError);
617 return NULL;
618 }
619 total += n;
620 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000621
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000622 if (PyBytes_GET_SIZE(result) > total) {
623 if (_PyBytes_Resize(&result, total) < 0) {
624 /* This should never happen, but just in case */
625 Py_DECREF(result);
626 return NULL;
627 }
628 }
629 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000630}
631
Guido van Rossuma9e20242007-03-08 00:43:48 +0000632static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000633fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000634{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000635 char *ptr;
636 Py_ssize_t n;
637 Py_ssize_t size = -1;
638 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000639
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000640 if (self->fd < 0)
641 return err_closed();
642 if (!self->readable)
643 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000644
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000645 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
646 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000647
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000648 if (size < 0) {
649 return fileio_readall(self);
650 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000651
Victor Stinnerc655a722011-07-05 11:31:49 +0200652#if defined(MS_WIN64) || defined(MS_WINDOWS)
653 if (size > INT_MAX)
654 size = INT_MAX;
655#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000656 bytes = PyBytes_FromStringAndSize(NULL, size);
657 if (bytes == NULL)
658 return NULL;
659 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000660
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000661 if (_PyVerify_fd(self->fd)) {
662 Py_BEGIN_ALLOW_THREADS
663 errno = 0;
Victor Stinnerc655a722011-07-05 11:31:49 +0200664#if defined(MS_WIN64) || defined(MS_WINDOWS)
665 n = read(self->fd, ptr, (int)size);
666#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000667 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200668#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000669 Py_END_ALLOW_THREADS
670 } else
671 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000672
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000673 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100674 int err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000675 Py_DECREF(bytes);
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100676 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000677 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100678 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000679 PyErr_SetFromErrno(PyExc_IOError);
680 return NULL;
681 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000682
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000683 if (n != size) {
684 if (_PyBytes_Resize(&bytes, n) < 0) {
685 Py_DECREF(bytes);
686 return NULL;
687 }
688 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000689
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000690 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000691}
692
693static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000694fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000695{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000696 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000697 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100698 int err;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000699
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000700 if (self->fd < 0)
701 return err_closed();
702 if (!self->writable)
703 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000704
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000705 if (!PyArg_ParseTuple(args, "y*", &pbuf))
706 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000707
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000708 if (_PyVerify_fd(self->fd)) {
709 Py_BEGIN_ALLOW_THREADS
710 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000711 len = pbuf.len;
712#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100713 if (len > 32767 && isatty(self->fd)) {
714 /* Issue #11395: the Windows console returns an error (12: not
715 enough space error) on writing into stdout if stdout mode is
716 binary and the length is greater than 66,000 bytes (or less,
717 depending on heap usage). */
718 len = 32767;
719 }
720 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000721 len = INT_MAX;
722 n = write(self->fd, pbuf.buf, (int)len);
723#else
Victor Stinner72344792011-01-11 00:04:12 +0000724 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000725#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000726 Py_END_ALLOW_THREADS
727 } else
728 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100729 err = errno;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000730
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000731 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000732
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000733 if (n < 0) {
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 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000742}
743
Guido van Rossum53807da2007-04-10 19:01:47 +0000744/* XXX Windows support below is likely incomplete */
745
Guido van Rossum53807da2007-04-10 19:01:47 +0000746/* Cribbed from posix_lseek() */
747static PyObject *
748portable_lseek(int fd, PyObject *posobj, int whence)
749{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000750 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000751
752#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000753 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
754 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000755#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000756 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000757#endif
758#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000759 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000760#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000761#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000762 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000763#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000764 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000765#endif /* SEEK_SET */
766
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000767 if (posobj == NULL)
768 pos = 0;
769 else {
770 if(PyFloat_Check(posobj)) {
771 PyErr_SetString(PyExc_TypeError, "an integer is required");
772 return NULL;
773 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000774#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000775 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000776#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000777 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000778#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000779 if (PyErr_Occurred())
780 return NULL;
781 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000782
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000783 if (_PyVerify_fd(fd)) {
784 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000785#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000786 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000787#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000788 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000789#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000790 Py_END_ALLOW_THREADS
791 } else
792 res = -1;
793 if (res < 0)
794 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000795
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000796#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000797 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000798#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000799 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000800#endif
801}
802
Guido van Rossuma9e20242007-03-08 00:43:48 +0000803static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000804fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000805{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000806 PyObject *posobj;
807 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000808
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000809 if (self->fd < 0)
810 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000811
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000812 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
813 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000814
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000815 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000816}
817
818static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000819fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000820{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000821 if (self->fd < 0)
822 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000823
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000824 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000825}
826
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000827#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000828static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000829fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000830{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000831 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000832#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000833 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000834#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000835 int ret;
836 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000837
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000838 fd = self->fd;
839 if (fd < 0)
840 return err_closed();
841 if (!self->writable)
842 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000843
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000844 if (!PyArg_ParseTuple(args, "|O", &posobj))
845 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000846
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000847 if (posobj == Py_None || posobj == NULL) {
848 /* Get the current position. */
849 posobj = portable_lseek(fd, NULL, 1);
850 if (posobj == NULL)
851 return NULL;
852 }
853 else {
854 Py_INCREF(posobj);
855 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000856
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000857#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000858 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
859 so don't even try using it. */
860 {
861 PyObject *oldposobj, *tempposobj;
862 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000863
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000864 /* we save the file pointer position */
865 oldposobj = portable_lseek(fd, NULL, 1);
866 if (oldposobj == NULL) {
867 Py_DECREF(posobj);
868 return NULL;
869 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000870
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000871 /* we then move to the truncation position */
872 tempposobj = portable_lseek(fd, posobj, 0);
873 if (tempposobj == NULL) {
874 Py_DECREF(oldposobj);
875 Py_DECREF(posobj);
876 return NULL;
877 }
878 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000879
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000880 /* Truncate. Note that this may grow the file! */
881 Py_BEGIN_ALLOW_THREADS
882 errno = 0;
883 hFile = (HANDLE)_get_osfhandle(fd);
884 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
885 if (ret == 0) {
886 ret = SetEndOfFile(hFile) == 0;
887 if (ret)
888 errno = EACCES;
889 }
890 Py_END_ALLOW_THREADS
891
892 /* we restore the file pointer position in any case */
893 tempposobj = portable_lseek(fd, oldposobj, 0);
894 Py_DECREF(oldposobj);
895 if (tempposobj == NULL) {
896 Py_DECREF(posobj);
897 return NULL;
898 }
899 Py_DECREF(tempposobj);
900 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000901#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000902
903#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000904 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000905#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000906 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000907#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000908 if (PyErr_Occurred()){
909 Py_DECREF(posobj);
910 return NULL;
911 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000912
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000913 Py_BEGIN_ALLOW_THREADS
914 errno = 0;
915 ret = ftruncate(fd, pos);
916 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000917
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000918#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000919
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000920 if (ret != 0) {
921 Py_DECREF(posobj);
922 PyErr_SetFromErrno(PyExc_IOError);
923 return NULL;
924 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000925
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000926 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000927}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000928#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000929
930static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000931mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000932{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000933 if (self->readable) {
934 if (self->writable)
935 return "rb+";
936 else
937 return "rb";
938 }
939 else
940 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000941}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000942
943static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000944fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000945{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000946 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000947
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000948 if (self->fd < 0)
949 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000950
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000951 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
952 if (nameobj == NULL) {
953 if (PyErr_ExceptionMatches(PyExc_AttributeError))
954 PyErr_Clear();
955 else
956 return NULL;
957 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
958 self->fd, mode_string(self));
959 }
960 else {
961 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
962 nameobj, mode_string(self));
963 Py_DECREF(nameobj);
964 }
965 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000966}
967
968static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000969fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000970{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000971 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000972
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000973 if (self->fd < 0)
974 return err_closed();
975 Py_BEGIN_ALLOW_THREADS
976 res = isatty(self->fd);
977 Py_END_ALLOW_THREADS
978 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000979}
980
Antoine Pitrou243757e2010-11-05 21:15:39 +0000981static PyObject *
982fileio_getstate(fileio *self)
983{
984 PyErr_Format(PyExc_TypeError,
985 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
986 return NULL;
987}
988
Guido van Rossuma9e20242007-03-08 00:43:48 +0000989
990PyDoc_STRVAR(fileio_doc,
991"file(name: str[, mode: str]) -> file IO object\n"
992"\n"
993"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000994"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +0000995"when opened for writing or appending; it will be truncated when\n"
996"opened for writing. Add a '+' to the mode to allow simultaneous\n"
997"reading and writing.");
998
999PyDoc_STRVAR(read_doc,
1000"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1001"\n"
1002"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001003"In non-blocking mode, returns None if no data is available.\n"
1004"On end-of-file, returns ''.");
1005
1006PyDoc_STRVAR(readall_doc,
1007"readall() -> bytes. read all data from the file, returned as bytes.\n"
1008"\n"
1009"In non-blocking mode, returns as much as is immediately available,\n"
1010"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001011
1012PyDoc_STRVAR(write_doc,
1013"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1014"\n"
1015"Only makes one system call, so not all of the data may be written.\n"
1016"The number of bytes actually written is returned.");
1017
1018PyDoc_STRVAR(fileno_doc,
1019"fileno() -> int. \"file descriptor\".\n"
1020"\n"
1021"This is needed for lower-level file interfaces, such the fcntl module.");
1022
1023PyDoc_STRVAR(seek_doc,
1024"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1025"\n"
1026"Argument offset is a byte count. Optional argument whence defaults to\n"
1027"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1028"(move relative to current position, positive or negative), and 2 (move\n"
1029"relative to end of file, usually negative, although many platforms allow\n"
1030"seeking beyond the end of a file)."
1031"\n"
1032"Note that not all file objects are seekable.");
1033
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001034#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001035PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001036"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001037"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001038"Size defaults to the current file position, as returned by tell()."
1039"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001040#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001041
1042PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001043"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001044
1045PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001046"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001047
1048PyDoc_STRVAR(close_doc,
1049"close() -> None. Close the file.\n"
1050"\n"
1051"A closed file cannot be used for further I/O operations. close() may be\n"
1052"called more than once without error. Changes the fileno to -1.");
1053
1054PyDoc_STRVAR(isatty_doc,
1055"isatty() -> bool. True if the file is connected to a tty device.");
1056
Guido van Rossuma9e20242007-03-08 00:43:48 +00001057PyDoc_STRVAR(seekable_doc,
1058"seekable() -> bool. True if file supports random-access.");
1059
1060PyDoc_STRVAR(readable_doc,
1061"readable() -> bool. True if file was opened in a read mode.");
1062
1063PyDoc_STRVAR(writable_doc,
1064"writable() -> bool. True if file was opened in a write mode.");
1065
1066static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001067 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1068 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1069 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1070 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1071 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1072 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001073#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001074 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001075#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001076 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1077 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1078 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1079 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1080 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1081 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001082 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001083 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001084 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001085};
1086
Guido van Rossum53807da2007-04-10 19:01:47 +00001087/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1088
Guido van Rossumb0428152007-04-08 17:44:42 +00001089static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001090get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001091{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001092 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001093}
1094
1095static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001096get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001097{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001098 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001099}
1100
1101static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001102get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001103{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001104 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001105}
1106
1107static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001108 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1109 {"closefd", (getter)get_closefd, NULL,
1110 "True if the file descriptor will be closed"},
1111 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1112 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001113};
1114
Guido van Rossuma9e20242007-03-08 00:43:48 +00001115PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001116 PyVarObject_HEAD_INIT(NULL, 0)
1117 "_io.FileIO",
1118 sizeof(fileio),
1119 0,
1120 (destructor)fileio_dealloc, /* tp_dealloc */
1121 0, /* tp_print */
1122 0, /* tp_getattr */
1123 0, /* tp_setattr */
1124 0, /* tp_reserved */
1125 (reprfunc)fileio_repr, /* tp_repr */
1126 0, /* tp_as_number */
1127 0, /* tp_as_sequence */
1128 0, /* tp_as_mapping */
1129 0, /* tp_hash */
1130 0, /* tp_call */
1131 0, /* tp_str */
1132 PyObject_GenericGetAttr, /* tp_getattro */
1133 0, /* tp_setattro */
1134 0, /* tp_as_buffer */
1135 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1136 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1137 fileio_doc, /* tp_doc */
1138 (traverseproc)fileio_traverse, /* tp_traverse */
1139 (inquiry)fileio_clear, /* tp_clear */
1140 0, /* tp_richcompare */
1141 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1142 0, /* tp_iter */
1143 0, /* tp_iternext */
1144 fileio_methods, /* tp_methods */
1145 0, /* tp_members */
1146 fileio_getsetlist, /* tp_getset */
1147 0, /* tp_base */
1148 0, /* tp_dict */
1149 0, /* tp_descr_get */
1150 0, /* tp_descr_set */
1151 offsetof(fileio, dict), /* tp_dictoffset */
1152 fileio_init, /* tp_init */
1153 PyType_GenericAlloc, /* tp_alloc */
1154 fileio_new, /* tp_new */
1155 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001156};