blob: a8567bf284ead0484d1317fa76efb3d592a8f033 [file] [log] [blame]
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001/* Author: Daniel Stutzbach */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +00005#ifdef HAVE_SYS_TYPES_H
Christian Heimes7f39c9f2008-01-25 12:18:43 +00006#include <sys/types.h>
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +00007#endif
8#ifdef HAVE_SYS_STAT_H
Christian Heimes7f39c9f2008-01-25 12:18:43 +00009#include <sys/stat.h>
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +000010#endif
11#ifdef HAVE_FCNTL_H
Christian Heimes7f39c9f2008-01-25 12:18:43 +000012#include <fcntl.h>
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +000013#endif
Christian Heimes7f39c9f2008-01-25 12:18:43 +000014#include <stddef.h> /* For offsetof */
Antoine Pitrou19690592009-06-12 20:14:08 +000015#include "_iomodule.h"
Christian Heimes7f39c9f2008-01-25 12:18:43 +000016
17/*
18 * Known likely problems:
19 *
20 * - Files larger then 2**32-1
21 * - Files with unicode filenames
22 * - Passing numbers greater than 2**32-1 when an integer is expected
23 * - Making it work on Windows and other oddball platforms
24 *
25 * To Do:
26 *
27 * - autoconfify header file inclusion
28 */
29
30#ifdef MS_WINDOWS
31/* can simulate truncate with Win32 API functions; see file_truncate */
32#define HAVE_FTRUNCATE
33#define WIN32_LEAN_AND_MEAN
34#include <windows.h>
35#endif
36
Antoine Pitrou19690592009-06-12 20:14:08 +000037#if BUFSIZ < (8*1024)
38#define SMALLCHUNK (8*1024)
39#elif (BUFSIZ >= (2 << 25))
40#error "unreasonable BUFSIZ > 64MB defined"
41#else
42#define SMALLCHUNK BUFSIZ
43#endif
44
Christian Heimes7f39c9f2008-01-25 12:18:43 +000045typedef struct {
Antoine Pitroub26dc462010-05-05 16:27:30 +000046 PyObject_HEAD
47 int fd;
48 unsigned int readable : 1;
49 unsigned int writable : 1;
50 signed int seekable : 2; /* -1 means unknown */
51 unsigned int closefd : 1;
52 PyObject *weakreflist;
53 PyObject *dict;
Antoine Pitrou19690592009-06-12 20:14:08 +000054} fileio;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000055
56PyTypeObject PyFileIO_Type;
57
58#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
59
Antoine Pitrou19690592009-06-12 20:14:08 +000060int
61_PyFileIO_closed(PyObject *self)
62{
Antoine Pitroub26dc462010-05-05 16:27:30 +000063 return ((fileio *)self)->fd < 0;
Antoine Pitrou19690592009-06-12 20:14:08 +000064}
65
Antoine Pitroue741cc62009-01-21 00:45:36 +000066static PyObject *
67portable_lseek(int fd, PyObject *posobj, int whence);
68
Antoine Pitrou19690592009-06-12 20:14:08 +000069static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
70
71/* Returns 0 on success, -1 with exception set on failure. */
Christian Heimes7f39c9f2008-01-25 12:18:43 +000072static int
Antoine Pitrou19690592009-06-12 20:14:08 +000073internal_close(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +000074{
Antoine Pitroub26dc462010-05-05 16:27:30 +000075 int err = 0;
76 int save_errno = 0;
77 if (self->fd >= 0) {
78 int fd = self->fd;
79 self->fd = -1;
80 /* fd is accessible and someone else may have closed it */
81 if (_PyVerify_fd(fd)) {
82 Py_BEGIN_ALLOW_THREADS
83 err = close(fd);
84 if (err < 0)
85 save_errno = errno;
86 Py_END_ALLOW_THREADS
87 } else {
88 save_errno = errno;
89 err = -1;
90 }
91 }
92 if (err < 0) {
93 errno = save_errno;
94 PyErr_SetFromErrno(PyExc_IOError);
95 return -1;
96 }
97 return 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000098}
99
100static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000101fileio_close(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000102{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000103 if (!self->closefd) {
104 self->fd = -1;
105 Py_RETURN_NONE;
106 }
107 errno = internal_close(self);
108 if (errno < 0)
109 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000110
Antoine Pitroub26dc462010-05-05 16:27:30 +0000111 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
112 "close", "O", self);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000113}
114
115static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000116fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000117{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000118 fileio *self;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000119
Antoine Pitroub26dc462010-05-05 16:27:30 +0000120 assert(type != NULL && type->tp_alloc != NULL);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000121
Antoine Pitroub26dc462010-05-05 16:27:30 +0000122 self = (fileio *) type->tp_alloc(type, 0);
123 if (self != NULL) {
124 self->fd = -1;
125 self->readable = 0;
126 self->writable = 0;
127 self->seekable = -1;
128 self->closefd = 1;
129 self->weakreflist = NULL;
130 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000131
Antoine Pitroub26dc462010-05-05 16:27:30 +0000132 return (PyObject *) self;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000133}
134
135/* On Unix, open will succeed for directories.
136 In Python, there should be no file objects referring to
137 directories, so we need a check. */
138
139static int
Antoine Pitrouc2ec9922012-07-06 18:48:24 +0200140dircheck(fileio* self, PyObject *nameobj)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000141{
142#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000143 struct stat buf;
144 if (self->fd < 0)
145 return 0;
146 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
Antoine Pitrouc2ec9922012-07-06 18:48:24 +0200147 errno = EISDIR;
148 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
Antoine Pitroub26dc462010-05-05 16:27:30 +0000149 return -1;
150 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000151#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000152 return 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000153}
154
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000155static int
156check_fd(int fd)
157{
158#if defined(HAVE_FSTAT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000159 struct stat buf;
160 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
161 PyObject *exc;
162 char *msg = strerror(EBADF);
163 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
164 EBADF, msg);
165 PyErr_SetObject(PyExc_OSError, exc);
166 Py_XDECREF(exc);
167 return -1;
168 }
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000169#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000170 return 0;
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000171}
172
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000173
174static int
175fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
176{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000177 fileio *self = (fileio *) oself;
178 static char *kwlist[] = {"file", "mode", "closefd", NULL};
179 const char *name = NULL;
180 PyObject *nameobj, *stringobj = NULL;
181 char *mode = "r";
182 char *s;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000183#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000184 Py_UNICODE *widename = NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000185#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000186 int ret = 0;
187 int rwa = 0, plus = 0, append = 0;
188 int flags = 0;
189 int fd = -1;
190 int closefd = 1;
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200191 int fd_is_own = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000192
Antoine Pitroub26dc462010-05-05 16:27:30 +0000193 assert(PyFileIO_Check(oself));
194 if (self->fd >= 0) {
Hynek Schlawack877effc2012-05-25 09:24:18 +0200195 if (self->closefd) {
196 /* Have to close the existing file first. */
197 if (internal_close(self) < 0)
198 return -1;
199 }
200 else
201 self->fd = -1;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000202 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000203
Antoine Pitroub26dc462010-05-05 16:27:30 +0000204 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
205 kwlist, &nameobj, &mode, &closefd))
206 return -1;
Antoine Pitrou19690592009-06-12 20:14:08 +0000207
Antoine Pitroub26dc462010-05-05 16:27:30 +0000208 if (PyFloat_Check(nameobj)) {
209 PyErr_SetString(PyExc_TypeError,
210 "integer argument expected, got float");
211 return -1;
212 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000213
Antoine Pitroub26dc462010-05-05 16:27:30 +0000214 fd = PyLong_AsLong(nameobj);
215 if (fd < 0) {
216 if (!PyErr_Occurred()) {
217 PyErr_SetString(PyExc_ValueError,
218 "Negative filedescriptor");
219 return -1;
220 }
221 PyErr_Clear();
222 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000223
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +0000224#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000225 if (PyUnicode_Check(nameobj))
226 widename = PyUnicode_AS_UNICODE(nameobj);
227 if (widename == NULL)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000228#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000229 if (fd < 0)
230 {
231 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
232 Py_ssize_t namelen;
233 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
234 return -1;
235 }
236 else {
237 PyObject *u = PyUnicode_FromObject(nameobj);
Antoine Pitrou19690592009-06-12 20:14:08 +0000238
Antoine Pitroub26dc462010-05-05 16:27:30 +0000239 if (u == NULL)
240 return -1;
Antoine Pitrou19690592009-06-12 20:14:08 +0000241
Antoine Pitroub26dc462010-05-05 16:27:30 +0000242 stringobj = PyUnicode_AsEncodedString(
243 u, Py_FileSystemDefaultEncoding, NULL);
244 Py_DECREF(u);
245 if (stringobj == NULL)
246 return -1;
247 if (!PyBytes_Check(stringobj)) {
248 PyErr_SetString(PyExc_TypeError,
249 "encoder failed to return bytes");
250 goto error;
251 }
252 name = PyBytes_AS_STRING(stringobj);
253 }
254 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000255
Antoine Pitroub26dc462010-05-05 16:27:30 +0000256 s = mode;
257 while (*s) {
258 switch (*s++) {
259 case 'r':
260 if (rwa) {
261 bad_mode:
262 PyErr_SetString(PyExc_ValueError,
Georg Brandl10603802010-11-26 08:10:41 +0000263 "Must have exactly one of read/write/append "
264 "mode and at most one plus");
Antoine Pitroub26dc462010-05-05 16:27:30 +0000265 goto error;
266 }
267 rwa = 1;
268 self->readable = 1;
269 break;
270 case 'w':
271 if (rwa)
272 goto bad_mode;
273 rwa = 1;
274 self->writable = 1;
275 flags |= O_CREAT | O_TRUNC;
276 break;
277 case 'a':
278 if (rwa)
279 goto bad_mode;
280 rwa = 1;
281 self->writable = 1;
282 flags |= O_CREAT;
283 append = 1;
284 break;
285 case 'b':
286 break;
287 case '+':
288 if (plus)
289 goto bad_mode;
290 self->readable = self->writable = 1;
291 plus = 1;
292 break;
293 default:
294 PyErr_Format(PyExc_ValueError,
295 "invalid mode: %.200s", mode);
296 goto error;
297 }
298 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000299
Antoine Pitroub26dc462010-05-05 16:27:30 +0000300 if (!rwa)
301 goto bad_mode;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000302
Antoine Pitroub26dc462010-05-05 16:27:30 +0000303 if (self->readable && self->writable)
304 flags |= O_RDWR;
305 else if (self->readable)
306 flags |= O_RDONLY;
307 else
308 flags |= O_WRONLY;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000309
310#ifdef O_BINARY
Antoine Pitroub26dc462010-05-05 16:27:30 +0000311 flags |= O_BINARY;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000312#endif
313
314#ifdef O_APPEND
Antoine Pitroub26dc462010-05-05 16:27:30 +0000315 if (append)
316 flags |= O_APPEND;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000317#endif
318
Antoine Pitroub26dc462010-05-05 16:27:30 +0000319 if (fd >= 0) {
320 if (check_fd(fd))
321 goto error;
322 self->fd = fd;
323 self->closefd = closefd;
324 }
325 else {
326 self->closefd = 1;
327 if (!closefd) {
328 PyErr_SetString(PyExc_ValueError,
329 "Cannot use closefd=False with file name");
330 goto error;
331 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000332
Antoine Pitroub26dc462010-05-05 16:27:30 +0000333 Py_BEGIN_ALLOW_THREADS
334 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000335#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000336 if (widename != NULL)
337 self->fd = _wopen(widename, flags, 0666);
338 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000339#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000340 self->fd = open(name, flags, 0666);
341 Py_END_ALLOW_THREADS
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200342 fd_is_own = 1;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000343 if (self->fd < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000344#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000345 if (widename != NULL)
346 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
347 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000348#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000349 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
350 goto error;
351 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000352 }
Antoine Pitrouc2ec9922012-07-06 18:48:24 +0200353 if (dircheck(self, nameobj) < 0)
354 goto error;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000355
Antoine Pitroub26dc462010-05-05 16:27:30 +0000356 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
357 goto error;
Antoine Pitrou19690592009-06-12 20:14:08 +0000358
Antoine Pitroub26dc462010-05-05 16:27:30 +0000359 if (append) {
360 /* For consistent behaviour, we explicitly seek to the
361 end of file (otherwise, it might be done only on the
362 first write()). */
363 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200364 if (pos == NULL)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000365 goto error;
366 Py_DECREF(pos);
367 }
Antoine Pitroue741cc62009-01-21 00:45:36 +0000368
Antoine Pitroub26dc462010-05-05 16:27:30 +0000369 goto done;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000370
371 error:
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200372 if (!fd_is_own)
373 self->fd = -1;
374
Antoine Pitroub26dc462010-05-05 16:27:30 +0000375 ret = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000376
377 done:
Antoine Pitroub26dc462010-05-05 16:27:30 +0000378 Py_CLEAR(stringobj);
379 return ret;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000380}
381
Antoine Pitrou19690592009-06-12 20:14:08 +0000382static int
383fileio_traverse(fileio *self, visitproc visit, void *arg)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000384{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000385 Py_VISIT(self->dict);
386 return 0;
Antoine Pitrou19690592009-06-12 20:14:08 +0000387}
388
389static int
390fileio_clear(fileio *self)
391{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000392 Py_CLEAR(self->dict);
393 return 0;
Antoine Pitrou19690592009-06-12 20:14:08 +0000394}
395
396static void
397fileio_dealloc(fileio *self)
398{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000399 if (_PyIOBase_finalize((PyObject *) self) < 0)
400 return;
401 _PyObject_GC_UNTRACK(self);
402 if (self->weakreflist != NULL)
403 PyObject_ClearWeakRefs((PyObject *) self);
404 Py_CLEAR(self->dict);
405 Py_TYPE(self)->tp_free((PyObject *)self);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000406}
407
408static PyObject *
409err_closed(void)
410{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000411 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
412 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000413}
414
415static PyObject *
416err_mode(char *action)
417{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000418 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
419 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000420}
421
422static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000423fileio_fileno(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000424{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000425 if (self->fd < 0)
426 return err_closed();
427 return PyInt_FromLong((long) self->fd);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000428}
429
430static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000431fileio_readable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000432{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000433 if (self->fd < 0)
434 return err_closed();
435 return PyBool_FromLong((long) self->readable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000436}
437
438static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000439fileio_writable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000440{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000441 if (self->fd < 0)
442 return err_closed();
443 return PyBool_FromLong((long) self->writable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000444}
445
446static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000447fileio_seekable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000448{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000449 if (self->fd < 0)
450 return err_closed();
451 if (self->seekable < 0) {
452 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
453 if (pos == NULL) {
454 PyErr_Clear();
455 self->seekable = 0;
456 } else {
457 Py_DECREF(pos);
458 self->seekable = 1;
459 }
460 }
461 return PyBool_FromLong((long) self->seekable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000462}
463
464static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000465fileio_readinto(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000466{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000467 Py_buffer pbuf;
Victor Stinner59729ff2011-07-05 11:28:19 +0200468 Py_ssize_t n, len;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000469
Antoine Pitroub26dc462010-05-05 16:27:30 +0000470 if (self->fd < 0)
471 return err_closed();
472 if (!self->readable)
473 return err_mode("reading");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000474
Antoine Pitroub26dc462010-05-05 16:27:30 +0000475 if (!PyArg_ParseTuple(args, "w*", &pbuf))
476 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000477
Antoine Pitroub26dc462010-05-05 16:27:30 +0000478 if (_PyVerify_fd(self->fd)) {
Victor Stinner59729ff2011-07-05 11:28:19 +0200479 len = pbuf.len;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000480 Py_BEGIN_ALLOW_THREADS
481 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200482#if defined(MS_WIN64) || defined(MS_WINDOWS)
483 if (len > INT_MAX)
484 len = INT_MAX;
485 n = read(self->fd, pbuf.buf, (int)len);
486#else
487 n = read(self->fd, pbuf.buf, len);
488#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000489 Py_END_ALLOW_THREADS
490 } else
491 n = -1;
492 PyBuffer_Release(&pbuf);
493 if (n < 0) {
494 if (errno == EAGAIN)
495 Py_RETURN_NONE;
496 PyErr_SetFromErrno(PyExc_IOError);
497 return NULL;
498 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000499
Antoine Pitroub26dc462010-05-05 16:27:30 +0000500 return PyLong_FromSsize_t(n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000501}
502
Antoine Pitrou19690592009-06-12 20:14:08 +0000503static size_t
504new_buffersize(fileio *self, size_t currentsize)
505{
506#ifdef HAVE_FSTAT
Antoine Pitroub26dc462010-05-05 16:27:30 +0000507 off_t pos, end;
508 struct stat st;
509 if (fstat(self->fd, &st) == 0) {
510 end = st.st_size;
511 pos = lseek(self->fd, 0L, SEEK_CUR);
512 /* Files claiming a size smaller than SMALLCHUNK may
513 actually be streaming pseudo-files. In this case, we
514 apply the more aggressive algorithm below.
515 */
516 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
517 /* Add 1 so if the file were to grow we'd notice. */
518 return currentsize + end - pos + 1;
519 }
520 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000521#endif
Nadeem Vawda36248152011-10-13 13:52:46 +0200522 /* Expand the buffer by an amount proportional to the current size,
523 giving us amortized linear-time behavior. Use a less-than-double
524 growth factor to avoid excessive allocation. */
525 return currentsize + (currentsize >> 3) + 6;
Antoine Pitrou19690592009-06-12 20:14:08 +0000526}
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000527
528static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000529fileio_readall(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000530{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000531 PyObject *result;
532 Py_ssize_t total = 0;
533 int n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000534
Victor Stinner5100a402011-05-25 22:15:36 +0200535 if (self->fd < 0)
536 return err_closed();
Antoine Pitroub26dc462010-05-05 16:27:30 +0000537 if (!_PyVerify_fd(self->fd))
538 return PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou19690592009-06-12 20:14:08 +0000539
Antoine Pitroub26dc462010-05-05 16:27:30 +0000540 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
541 if (result == NULL)
542 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000543
Antoine Pitroub26dc462010-05-05 16:27:30 +0000544 while (1) {
545 size_t newsize = new_buffersize(self, total);
546 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
547 PyErr_SetString(PyExc_OverflowError,
548 "unbounded read returned more bytes "
549 "than a Python string can hold ");
550 Py_DECREF(result);
551 return NULL;
552 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000553
Antoine Pitroub26dc462010-05-05 16:27:30 +0000554 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
555 if (_PyBytes_Resize(&result, newsize) < 0) {
556 if (total == 0) {
557 Py_DECREF(result);
558 return NULL;
559 }
560 PyErr_Clear();
561 break;
562 }
563 }
564 Py_BEGIN_ALLOW_THREADS
565 errno = 0;
566 n = read(self->fd,
567 PyBytes_AS_STRING(result) + total,
568 newsize - total);
569 Py_END_ALLOW_THREADS
570 if (n == 0)
571 break;
572 if (n < 0) {
573 if (total > 0)
574 break;
575 if (errno == EAGAIN) {
576 Py_DECREF(result);
577 Py_RETURN_NONE;
578 }
579 Py_DECREF(result);
580 PyErr_SetFromErrno(PyExc_IOError);
581 return NULL;
582 }
583 total += n;
584 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000585
Antoine Pitroub26dc462010-05-05 16:27:30 +0000586 if (PyBytes_GET_SIZE(result) > total) {
587 if (_PyBytes_Resize(&result, total) < 0) {
588 /* This should never happen, but just in case */
589 Py_DECREF(result);
590 return NULL;
591 }
592 }
593 return result;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000594}
595
596static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000597fileio_read(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000598{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000599 char *ptr;
600 Py_ssize_t n;
601 Py_ssize_t size = -1;
602 PyObject *bytes;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000603
Antoine Pitroub26dc462010-05-05 16:27:30 +0000604 if (self->fd < 0)
605 return err_closed();
606 if (!self->readable)
607 return err_mode("reading");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000608
Antoine Pitroub26dc462010-05-05 16:27:30 +0000609 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
610 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000611
Antoine Pitroub26dc462010-05-05 16:27:30 +0000612 if (size < 0) {
613 return fileio_readall(self);
614 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000615
Victor Stinner59729ff2011-07-05 11:28:19 +0200616#if defined(MS_WIN64) || defined(MS_WINDOWS)
617 if (size > INT_MAX)
618 size = INT_MAX;
619#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000620 bytes = PyBytes_FromStringAndSize(NULL, size);
621 if (bytes == NULL)
622 return NULL;
623 ptr = PyBytes_AS_STRING(bytes);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000624
Antoine Pitroub26dc462010-05-05 16:27:30 +0000625 if (_PyVerify_fd(self->fd)) {
626 Py_BEGIN_ALLOW_THREADS
627 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200628#if defined(MS_WIN64) || defined(MS_WINDOWS)
629 n = read(self->fd, ptr, (int)size);
630#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000631 n = read(self->fd, ptr, size);
Victor Stinner59729ff2011-07-05 11:28:19 +0200632#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000633 Py_END_ALLOW_THREADS
634 } else
635 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000636
Antoine Pitroub26dc462010-05-05 16:27:30 +0000637 if (n < 0) {
638 Py_DECREF(bytes);
639 if (errno == EAGAIN)
640 Py_RETURN_NONE;
641 PyErr_SetFromErrno(PyExc_IOError);
642 return NULL;
643 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000644
Antoine Pitroub26dc462010-05-05 16:27:30 +0000645 if (n != size) {
646 if (_PyBytes_Resize(&bytes, n) < 0) {
647 Py_DECREF(bytes);
648 return NULL;
649 }
650 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000651
Antoine Pitroub26dc462010-05-05 16:27:30 +0000652 return (PyObject *) bytes;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000653}
654
655static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000656fileio_write(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000657{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000658 Py_buffer pbuf;
Victor Stinner59729ff2011-07-05 11:28:19 +0200659 Py_ssize_t n, len;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000660
Antoine Pitroub26dc462010-05-05 16:27:30 +0000661 if (self->fd < 0)
662 return err_closed();
663 if (!self->writable)
664 return err_mode("writing");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000665
Antoine Pitroub26dc462010-05-05 16:27:30 +0000666 if (!PyArg_ParseTuple(args, "s*", &pbuf))
667 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000668
Antoine Pitroub26dc462010-05-05 16:27:30 +0000669 if (_PyVerify_fd(self->fd)) {
670 Py_BEGIN_ALLOW_THREADS
671 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200672 len = pbuf.len;
673#if defined(MS_WIN64) || defined(MS_WINDOWS)
674 if (len > INT_MAX)
675 len = INT_MAX;
676 n = write(self->fd, pbuf.buf, (int)len);
677#else
678 n = write(self->fd, pbuf.buf, len);
679#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000680 Py_END_ALLOW_THREADS
681 } else
682 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000683
Antoine Pitroub26dc462010-05-05 16:27:30 +0000684 PyBuffer_Release(&pbuf);
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000685
Antoine Pitroub26dc462010-05-05 16:27:30 +0000686 if (n < 0) {
687 if (errno == EAGAIN)
688 Py_RETURN_NONE;
689 PyErr_SetFromErrno(PyExc_IOError);
690 return NULL;
691 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000692
Antoine Pitroub26dc462010-05-05 16:27:30 +0000693 return PyLong_FromSsize_t(n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000694}
695
696/* XXX Windows support below is likely incomplete */
697
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000698/* Cribbed from posix_lseek() */
699static PyObject *
700portable_lseek(int fd, PyObject *posobj, int whence)
701{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000702 Py_off_t pos, res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000703
704#ifdef SEEK_SET
Antoine Pitroub26dc462010-05-05 16:27:30 +0000705 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
706 switch (whence) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000707#if SEEK_SET != 0
Antoine Pitroub26dc462010-05-05 16:27:30 +0000708 case 0: whence = SEEK_SET; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000709#endif
710#if SEEK_CUR != 1
Antoine Pitroub26dc462010-05-05 16:27:30 +0000711 case 1: whence = SEEK_CUR; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000712#endif
Benjamin Peterson8024cec2009-01-20 14:31:08 +0000713#if SEEK_END != 2
Antoine Pitroub26dc462010-05-05 16:27:30 +0000714 case 2: whence = SEEK_END; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000715#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000716 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000717#endif /* SEEK_SET */
718
Antoine Pitroub26dc462010-05-05 16:27:30 +0000719 if (posobj == NULL)
720 pos = 0;
721 else {
722 if(PyFloat_Check(posobj)) {
723 PyErr_SetString(PyExc_TypeError, "an integer is required");
724 return NULL;
725 }
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000726#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000727 pos = PyLong_AsLongLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000728#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000729 pos = PyLong_AsLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000730#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000731 if (PyErr_Occurred())
732 return NULL;
733 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000734
Antoine Pitroub26dc462010-05-05 16:27:30 +0000735 if (_PyVerify_fd(fd)) {
736 Py_BEGIN_ALLOW_THREADS
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000737#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000738 res = _lseeki64(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000739#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000740 res = lseek(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000741#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000742 Py_END_ALLOW_THREADS
743 } else
744 res = -1;
745 if (res < 0)
746 return PyErr_SetFromErrno(PyExc_IOError);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000747
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000748#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000749 return PyLong_FromLongLong(res);
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000750#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000751 return PyLong_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000752#endif
753}
754
755static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000756fileio_seek(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000757{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000758 PyObject *posobj;
759 int whence = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000760
Antoine Pitroub26dc462010-05-05 16:27:30 +0000761 if (self->fd < 0)
762 return err_closed();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000763
Antoine Pitroub26dc462010-05-05 16:27:30 +0000764 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
765 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000766
Antoine Pitroub26dc462010-05-05 16:27:30 +0000767 return portable_lseek(self->fd, posobj, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000768}
769
770static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000771fileio_tell(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000772{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000773 if (self->fd < 0)
774 return err_closed();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000775
Antoine Pitroub26dc462010-05-05 16:27:30 +0000776 return portable_lseek(self->fd, NULL, 1);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000777}
778
779#ifdef HAVE_FTRUNCATE
780static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000781fileio_truncate(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000782{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000783 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000784#ifndef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000785 Py_off_t pos;
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000786#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000787 int ret;
788 int fd;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000789
Antoine Pitroub26dc462010-05-05 16:27:30 +0000790 fd = self->fd;
791 if (fd < 0)
792 return err_closed();
793 if (!self->writable)
794 return err_mode("writing");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000795
Antoine Pitroub26dc462010-05-05 16:27:30 +0000796 if (!PyArg_ParseTuple(args, "|O", &posobj))
797 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000798
Antoine Pitroub26dc462010-05-05 16:27:30 +0000799 if (posobj == Py_None || posobj == NULL) {
800 /* Get the current position. */
801 posobj = portable_lseek(fd, NULL, 1);
802 if (posobj == NULL)
803 return NULL;
804 }
805 else {
806 Py_INCREF(posobj);
807 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000808
809#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000810 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
811 so don't even try using it. */
812 {
813 PyObject *oldposobj, *tempposobj;
814 HANDLE hFile;
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000815
Antoine Pitroub26dc462010-05-05 16:27:30 +0000816 /* we save the file pointer position */
817 oldposobj = portable_lseek(fd, NULL, 1);
818 if (oldposobj == NULL) {
819 Py_DECREF(posobj);
820 return NULL;
821 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000822
Antoine Pitroub26dc462010-05-05 16:27:30 +0000823 /* we then move to the truncation position */
824 tempposobj = portable_lseek(fd, posobj, 0);
825 if (tempposobj == NULL) {
826 Py_DECREF(oldposobj);
827 Py_DECREF(posobj);
828 return NULL;
829 }
830 Py_DECREF(tempposobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000831
Antoine Pitroub26dc462010-05-05 16:27:30 +0000832 /* Truncate. Note that this may grow the file! */
833 Py_BEGIN_ALLOW_THREADS
834 errno = 0;
835 hFile = (HANDLE)_get_osfhandle(fd);
836 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
837 if (ret == 0) {
838 ret = SetEndOfFile(hFile) == 0;
839 if (ret)
840 errno = EACCES;
841 }
842 Py_END_ALLOW_THREADS
843
844 /* we restore the file pointer position in any case */
845 tempposobj = portable_lseek(fd, oldposobj, 0);
846 Py_DECREF(oldposobj);
847 if (tempposobj == NULL) {
848 Py_DECREF(posobj);
849 return NULL;
850 }
851 Py_DECREF(tempposobj);
852 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000853#else
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000854
855#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000856 pos = PyLong_AsLongLong(posobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000857#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000858 pos = PyLong_AsLong(posobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000859#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000860 if (PyErr_Occurred()){
861 Py_DECREF(posobj);
862 return NULL;
863 }
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000864
Antoine Pitroub26dc462010-05-05 16:27:30 +0000865 Py_BEGIN_ALLOW_THREADS
866 errno = 0;
867 ret = ftruncate(fd, pos);
868 Py_END_ALLOW_THREADS
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000869
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000870#endif /* !MS_WINDOWS */
871
Antoine Pitroub26dc462010-05-05 16:27:30 +0000872 if (ret != 0) {
873 Py_DECREF(posobj);
874 PyErr_SetFromErrno(PyExc_IOError);
875 return NULL;
876 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000877
Antoine Pitroub26dc462010-05-05 16:27:30 +0000878 return posobj;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000879}
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000880#endif /* HAVE_FTRUNCATE */
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000881
882static char *
Antoine Pitrou19690592009-06-12 20:14:08 +0000883mode_string(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000884{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000885 if (self->readable) {
886 if (self->writable)
887 return "rb+";
888 else
889 return "rb";
890 }
891 else
892 return "wb";
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000893}
894
895static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000896fileio_repr(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000897{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000898 PyObject *nameobj, *res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000899
Antoine Pitroub26dc462010-05-05 16:27:30 +0000900 if (self->fd < 0)
901 return PyString_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou19690592009-06-12 20:14:08 +0000902
Antoine Pitroub26dc462010-05-05 16:27:30 +0000903 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
904 if (nameobj == NULL) {
905 if (PyErr_ExceptionMatches(PyExc_AttributeError))
906 PyErr_Clear();
907 else
908 return NULL;
909 res = PyString_FromFormat("<_io.FileIO fd=%d mode='%s'>",
910 self->fd, mode_string(self));
911 }
912 else {
913 PyObject *repr = PyObject_Repr(nameobj);
914 Py_DECREF(nameobj);
915 if (repr == NULL)
916 return NULL;
917 res = PyString_FromFormat("<_io.FileIO name=%s mode='%s'>",
918 PyString_AS_STRING(repr),
919 mode_string(self));
920 Py_DECREF(repr);
921 }
922 return res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000923}
924
925static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000926fileio_isatty(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000927{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000928 long res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000929
Antoine Pitroub26dc462010-05-05 16:27:30 +0000930 if (self->fd < 0)
931 return err_closed();
932 Py_BEGIN_ALLOW_THREADS
933 res = isatty(self->fd);
934 Py_END_ALLOW_THREADS
935 return PyBool_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000936}
937
938
939PyDoc_STRVAR(fileio_doc,
940"file(name: str[, mode: str]) -> file IO object\n"
941"\n"
942"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitroub26dc462010-05-05 16:27:30 +0000943"writing or appending. The file will be created if it doesn't exist\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000944"when opened for writing or appending; it will be truncated when\n"
945"opened for writing. Add a '+' to the mode to allow simultaneous\n"
946"reading and writing.");
947
948PyDoc_STRVAR(read_doc,
949"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
950"\n"
951"Only makes one system call, so less data may be returned than requested\n"
952"In non-blocking mode, returns None if no data is available.\n"
953"On end-of-file, returns ''.");
954
955PyDoc_STRVAR(readall_doc,
956"readall() -> bytes. read all data from the file, returned as bytes.\n"
957"\n"
958"In non-blocking mode, returns as much as is immediately available,\n"
959"or None if no data is available. On end-of-file, returns ''.");
960
961PyDoc_STRVAR(write_doc,
962"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
963"\n"
964"Only makes one system call, so not all of the data may be written.\n"
965"The number of bytes actually written is returned.");
966
967PyDoc_STRVAR(fileno_doc,
968"fileno() -> int. \"file descriptor\".\n"
969"\n"
970"This is needed for lower-level file interfaces, such the fcntl module.");
971
972PyDoc_STRVAR(seek_doc,
973"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
974"\n"
975"Argument offset is a byte count. Optional argument whence defaults to\n"
976"0 (offset from start of file, offset should be >= 0); other values are 1\n"
977"(move relative to current position, positive or negative), and 2 (move\n"
978"relative to end of file, usually negative, although many platforms allow\n"
979"seeking beyond the end of a file)."
980"\n"
981"Note that not all file objects are seekable.");
982
983#ifdef HAVE_FTRUNCATE
984PyDoc_STRVAR(truncate_doc,
Antoine Pitroub26dc462010-05-05 16:27:30 +0000985"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000986"\n"
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000987"Size defaults to the current file position, as returned by tell()."
988"The current file position is changed to the value of size.");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000989#endif
990
991PyDoc_STRVAR(tell_doc,
Antoine Pitroub26dc462010-05-05 16:27:30 +0000992"tell() -> int. Current file position");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000993
994PyDoc_STRVAR(readinto_doc,
Antoine Pitrou19690592009-06-12 20:14:08 +0000995"readinto() -> Same as RawIOBase.readinto().");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000996
997PyDoc_STRVAR(close_doc,
998"close() -> None. Close the file.\n"
999"\n"
1000"A closed file cannot be used for further I/O operations. close() may be\n"
1001"called more than once without error. Changes the fileno to -1.");
1002
1003PyDoc_STRVAR(isatty_doc,
1004"isatty() -> bool. True if the file is connected to a tty device.");
1005
1006PyDoc_STRVAR(seekable_doc,
1007"seekable() -> bool. True if file supports random-access.");
1008
1009PyDoc_STRVAR(readable_doc,
1010"readable() -> bool. True if file was opened in a read mode.");
1011
1012PyDoc_STRVAR(writable_doc,
1013"writable() -> bool. True if file was opened in a write mode.");
1014
1015static PyMethodDef fileio_methods[] = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001016 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1017 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1018 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1019 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1020 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1021 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001022#ifdef HAVE_FTRUNCATE
Antoine Pitroub26dc462010-05-05 16:27:30 +00001023 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001024#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +00001025 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1026 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1027 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1028 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1029 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1030 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
1031 {NULL, NULL} /* sentinel */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001032};
1033
1034/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1035
1036static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001037get_closed(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001038{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001039 return PyBool_FromLong((long)(self->fd < 0));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001040}
1041
1042static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001043get_closefd(fileio *self, void *closure)
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001044{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001045 return PyBool_FromLong((long)(self->closefd));
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001046}
1047
1048static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001049get_mode(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001050{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001051 return PyUnicode_FromString(mode_string(self));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001052}
1053
1054static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001055 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1056 {"closefd", (getter)get_closefd, NULL,
1057 "True if the file descriptor will be closed"},
1058 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1059 {NULL},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001060};
1061
1062PyTypeObject PyFileIO_Type = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001063 PyVarObject_HEAD_INIT(NULL, 0)
1064 "_io.FileIO",
1065 sizeof(fileio),
1066 0,
1067 (destructor)fileio_dealloc, /* tp_dealloc */
1068 0, /* tp_print */
1069 0, /* tp_getattr */
1070 0, /* tp_setattr */
1071 0, /* tp_reserved */
1072 (reprfunc)fileio_repr, /* tp_repr */
1073 0, /* tp_as_number */
1074 0, /* tp_as_sequence */
1075 0, /* tp_as_mapping */
1076 0, /* tp_hash */
1077 0, /* tp_call */
1078 0, /* tp_str */
1079 PyObject_GenericGetAttr, /* tp_getattro */
1080 0, /* tp_setattro */
1081 0, /* tp_as_buffer */
1082 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1083 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1084 fileio_doc, /* tp_doc */
1085 (traverseproc)fileio_traverse, /* tp_traverse */
1086 (inquiry)fileio_clear, /* tp_clear */
1087 0, /* tp_richcompare */
1088 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1089 0, /* tp_iter */
1090 0, /* tp_iternext */
1091 fileio_methods, /* tp_methods */
1092 0, /* tp_members */
1093 fileio_getsetlist, /* tp_getset */
1094 0, /* tp_base */
1095 0, /* tp_dict */
1096 0, /* tp_descr_get */
1097 0, /* tp_descr_set */
1098 offsetof(fileio, dict), /* tp_dictoffset */
1099 fileio_init, /* tp_init */
1100 PyType_GenericAlloc, /* tp_alloc */
1101 fileio_new, /* tp_new */
1102 PyObject_GC_Del, /* tp_free */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001103};