blob: 54116656012bc021feaf8a262fc56588bbe72552 [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) {
Gregory P. Smith99716162012-10-12 13:02:06 -0700573 if (errno == EINTR) {
574 if (PyErr_CheckSignals()) {
575 Py_DECREF(result);
576 return NULL;
577 }
578 continue;
579 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000580 if (total > 0)
581 break;
582 if (errno == EAGAIN) {
583 Py_DECREF(result);
584 Py_RETURN_NONE;
585 }
586 Py_DECREF(result);
587 PyErr_SetFromErrno(PyExc_IOError);
588 return NULL;
589 }
590 total += n;
591 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000592
Antoine Pitroub26dc462010-05-05 16:27:30 +0000593 if (PyBytes_GET_SIZE(result) > total) {
594 if (_PyBytes_Resize(&result, total) < 0) {
595 /* This should never happen, but just in case */
596 Py_DECREF(result);
597 return NULL;
598 }
599 }
600 return result;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000601}
602
603static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000604fileio_read(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000605{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000606 char *ptr;
607 Py_ssize_t n;
608 Py_ssize_t size = -1;
609 PyObject *bytes;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000610
Antoine Pitroub26dc462010-05-05 16:27:30 +0000611 if (self->fd < 0)
612 return err_closed();
613 if (!self->readable)
614 return err_mode("reading");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000615
Antoine Pitroub26dc462010-05-05 16:27:30 +0000616 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
617 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000618
Antoine Pitroub26dc462010-05-05 16:27:30 +0000619 if (size < 0) {
620 return fileio_readall(self);
621 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000622
Victor Stinner59729ff2011-07-05 11:28:19 +0200623#if defined(MS_WIN64) || defined(MS_WINDOWS)
624 if (size > INT_MAX)
625 size = INT_MAX;
626#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000627 bytes = PyBytes_FromStringAndSize(NULL, size);
628 if (bytes == NULL)
629 return NULL;
630 ptr = PyBytes_AS_STRING(bytes);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000631
Antoine Pitroub26dc462010-05-05 16:27:30 +0000632 if (_PyVerify_fd(self->fd)) {
633 Py_BEGIN_ALLOW_THREADS
634 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200635#if defined(MS_WIN64) || defined(MS_WINDOWS)
636 n = read(self->fd, ptr, (int)size);
637#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000638 n = read(self->fd, ptr, size);
Victor Stinner59729ff2011-07-05 11:28:19 +0200639#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000640 Py_END_ALLOW_THREADS
641 } else
642 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000643
Antoine Pitroub26dc462010-05-05 16:27:30 +0000644 if (n < 0) {
645 Py_DECREF(bytes);
646 if (errno == EAGAIN)
647 Py_RETURN_NONE;
648 PyErr_SetFromErrno(PyExc_IOError);
649 return NULL;
650 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000651
Antoine Pitroub26dc462010-05-05 16:27:30 +0000652 if (n != size) {
653 if (_PyBytes_Resize(&bytes, n) < 0) {
654 Py_DECREF(bytes);
655 return NULL;
656 }
657 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000658
Antoine Pitroub26dc462010-05-05 16:27:30 +0000659 return (PyObject *) bytes;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000660}
661
662static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000663fileio_write(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000664{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000665 Py_buffer pbuf;
Victor Stinner59729ff2011-07-05 11:28:19 +0200666 Py_ssize_t n, len;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000667
Antoine Pitroub26dc462010-05-05 16:27:30 +0000668 if (self->fd < 0)
669 return err_closed();
670 if (!self->writable)
671 return err_mode("writing");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000672
Antoine Pitroub26dc462010-05-05 16:27:30 +0000673 if (!PyArg_ParseTuple(args, "s*", &pbuf))
674 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000675
Antoine Pitroub26dc462010-05-05 16:27:30 +0000676 if (_PyVerify_fd(self->fd)) {
677 Py_BEGIN_ALLOW_THREADS
678 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200679 len = pbuf.len;
680#if defined(MS_WIN64) || defined(MS_WINDOWS)
681 if (len > INT_MAX)
682 len = INT_MAX;
683 n = write(self->fd, pbuf.buf, (int)len);
684#else
685 n = write(self->fd, pbuf.buf, len);
686#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000687 Py_END_ALLOW_THREADS
688 } else
689 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000690
Antoine Pitroub26dc462010-05-05 16:27:30 +0000691 PyBuffer_Release(&pbuf);
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000692
Antoine Pitroub26dc462010-05-05 16:27:30 +0000693 if (n < 0) {
694 if (errno == EAGAIN)
695 Py_RETURN_NONE;
696 PyErr_SetFromErrno(PyExc_IOError);
697 return NULL;
698 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000699
Antoine Pitroub26dc462010-05-05 16:27:30 +0000700 return PyLong_FromSsize_t(n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000701}
702
703/* XXX Windows support below is likely incomplete */
704
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000705/* Cribbed from posix_lseek() */
706static PyObject *
707portable_lseek(int fd, PyObject *posobj, int whence)
708{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000709 Py_off_t pos, res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000710
711#ifdef SEEK_SET
Antoine Pitroub26dc462010-05-05 16:27:30 +0000712 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
713 switch (whence) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000714#if SEEK_SET != 0
Antoine Pitroub26dc462010-05-05 16:27:30 +0000715 case 0: whence = SEEK_SET; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000716#endif
717#if SEEK_CUR != 1
Antoine Pitroub26dc462010-05-05 16:27:30 +0000718 case 1: whence = SEEK_CUR; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000719#endif
Benjamin Peterson8024cec2009-01-20 14:31:08 +0000720#if SEEK_END != 2
Antoine Pitroub26dc462010-05-05 16:27:30 +0000721 case 2: whence = SEEK_END; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000722#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000723 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000724#endif /* SEEK_SET */
725
Antoine Pitroub26dc462010-05-05 16:27:30 +0000726 if (posobj == NULL)
727 pos = 0;
728 else {
729 if(PyFloat_Check(posobj)) {
730 PyErr_SetString(PyExc_TypeError, "an integer is required");
731 return NULL;
732 }
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000733#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000734 pos = PyLong_AsLongLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000735#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000736 pos = PyLong_AsLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000737#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000738 if (PyErr_Occurred())
739 return NULL;
740 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000741
Antoine Pitroub26dc462010-05-05 16:27:30 +0000742 if (_PyVerify_fd(fd)) {
743 Py_BEGIN_ALLOW_THREADS
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000744#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000745 res = _lseeki64(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000746#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000747 res = lseek(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000748#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000749 Py_END_ALLOW_THREADS
750 } else
751 res = -1;
752 if (res < 0)
753 return PyErr_SetFromErrno(PyExc_IOError);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000754
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000755#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000756 return PyLong_FromLongLong(res);
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000757#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000758 return PyLong_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000759#endif
760}
761
762static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000763fileio_seek(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000764{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000765 PyObject *posobj;
766 int whence = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000767
Antoine Pitroub26dc462010-05-05 16:27:30 +0000768 if (self->fd < 0)
769 return err_closed();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000770
Antoine Pitroub26dc462010-05-05 16:27:30 +0000771 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
772 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000773
Antoine Pitroub26dc462010-05-05 16:27:30 +0000774 return portable_lseek(self->fd, posobj, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000775}
776
777static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000778fileio_tell(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000779{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000780 if (self->fd < 0)
781 return err_closed();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000782
Antoine Pitroub26dc462010-05-05 16:27:30 +0000783 return portable_lseek(self->fd, NULL, 1);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000784}
785
786#ifdef HAVE_FTRUNCATE
787static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000788fileio_truncate(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000789{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000790 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000791#ifndef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000792 Py_off_t pos;
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000793#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000794 int ret;
795 int fd;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000796
Antoine Pitroub26dc462010-05-05 16:27:30 +0000797 fd = self->fd;
798 if (fd < 0)
799 return err_closed();
800 if (!self->writable)
801 return err_mode("writing");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000802
Antoine Pitroub26dc462010-05-05 16:27:30 +0000803 if (!PyArg_ParseTuple(args, "|O", &posobj))
804 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000805
Antoine Pitroub26dc462010-05-05 16:27:30 +0000806 if (posobj == Py_None || posobj == NULL) {
807 /* Get the current position. */
808 posobj = portable_lseek(fd, NULL, 1);
809 if (posobj == NULL)
810 return NULL;
811 }
812 else {
813 Py_INCREF(posobj);
814 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000815
816#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000817 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
818 so don't even try using it. */
819 {
820 PyObject *oldposobj, *tempposobj;
821 HANDLE hFile;
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000822
Antoine Pitroub26dc462010-05-05 16:27:30 +0000823 /* we save the file pointer position */
824 oldposobj = portable_lseek(fd, NULL, 1);
825 if (oldposobj == NULL) {
826 Py_DECREF(posobj);
827 return NULL;
828 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000829
Antoine Pitroub26dc462010-05-05 16:27:30 +0000830 /* we then move to the truncation position */
831 tempposobj = portable_lseek(fd, posobj, 0);
832 if (tempposobj == NULL) {
833 Py_DECREF(oldposobj);
834 Py_DECREF(posobj);
835 return NULL;
836 }
837 Py_DECREF(tempposobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000838
Antoine Pitroub26dc462010-05-05 16:27:30 +0000839 /* Truncate. Note that this may grow the file! */
840 Py_BEGIN_ALLOW_THREADS
841 errno = 0;
842 hFile = (HANDLE)_get_osfhandle(fd);
843 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
844 if (ret == 0) {
845 ret = SetEndOfFile(hFile) == 0;
846 if (ret)
847 errno = EACCES;
848 }
849 Py_END_ALLOW_THREADS
850
851 /* we restore the file pointer position in any case */
852 tempposobj = portable_lseek(fd, oldposobj, 0);
853 Py_DECREF(oldposobj);
854 if (tempposobj == NULL) {
855 Py_DECREF(posobj);
856 return NULL;
857 }
858 Py_DECREF(tempposobj);
859 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000860#else
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000861
862#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000863 pos = PyLong_AsLongLong(posobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000864#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000865 pos = PyLong_AsLong(posobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000866#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000867 if (PyErr_Occurred()){
868 Py_DECREF(posobj);
869 return NULL;
870 }
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000871
Antoine Pitroub26dc462010-05-05 16:27:30 +0000872 Py_BEGIN_ALLOW_THREADS
873 errno = 0;
874 ret = ftruncate(fd, pos);
875 Py_END_ALLOW_THREADS
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000876
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000877#endif /* !MS_WINDOWS */
878
Antoine Pitroub26dc462010-05-05 16:27:30 +0000879 if (ret != 0) {
880 Py_DECREF(posobj);
881 PyErr_SetFromErrno(PyExc_IOError);
882 return NULL;
883 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000884
Antoine Pitroub26dc462010-05-05 16:27:30 +0000885 return posobj;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000886}
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000887#endif /* HAVE_FTRUNCATE */
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000888
889static char *
Antoine Pitrou19690592009-06-12 20:14:08 +0000890mode_string(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000891{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000892 if (self->readable) {
893 if (self->writable)
894 return "rb+";
895 else
896 return "rb";
897 }
898 else
899 return "wb";
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000900}
901
902static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000903fileio_repr(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000904{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000905 PyObject *nameobj, *res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000906
Antoine Pitroub26dc462010-05-05 16:27:30 +0000907 if (self->fd < 0)
908 return PyString_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou19690592009-06-12 20:14:08 +0000909
Antoine Pitroub26dc462010-05-05 16:27:30 +0000910 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
911 if (nameobj == NULL) {
912 if (PyErr_ExceptionMatches(PyExc_AttributeError))
913 PyErr_Clear();
914 else
915 return NULL;
916 res = PyString_FromFormat("<_io.FileIO fd=%d mode='%s'>",
917 self->fd, mode_string(self));
918 }
919 else {
920 PyObject *repr = PyObject_Repr(nameobj);
921 Py_DECREF(nameobj);
922 if (repr == NULL)
923 return NULL;
924 res = PyString_FromFormat("<_io.FileIO name=%s mode='%s'>",
925 PyString_AS_STRING(repr),
926 mode_string(self));
927 Py_DECREF(repr);
928 }
929 return res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000930}
931
932static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000933fileio_isatty(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000934{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000935 long res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000936
Antoine Pitroub26dc462010-05-05 16:27:30 +0000937 if (self->fd < 0)
938 return err_closed();
939 Py_BEGIN_ALLOW_THREADS
940 res = isatty(self->fd);
941 Py_END_ALLOW_THREADS
942 return PyBool_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000943}
944
945
946PyDoc_STRVAR(fileio_doc,
947"file(name: str[, mode: str]) -> file IO object\n"
948"\n"
949"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitroub26dc462010-05-05 16:27:30 +0000950"writing or appending. The file will be created if it doesn't exist\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000951"when opened for writing or appending; it will be truncated when\n"
952"opened for writing. Add a '+' to the mode to allow simultaneous\n"
953"reading and writing.");
954
955PyDoc_STRVAR(read_doc,
956"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
957"\n"
958"Only makes one system call, so less data may be returned than requested\n"
959"In non-blocking mode, returns None if no data is available.\n"
960"On end-of-file, returns ''.");
961
962PyDoc_STRVAR(readall_doc,
963"readall() -> bytes. read all data from the file, returned as bytes.\n"
964"\n"
965"In non-blocking mode, returns as much as is immediately available,\n"
966"or None if no data is available. On end-of-file, returns ''.");
967
968PyDoc_STRVAR(write_doc,
969"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
970"\n"
971"Only makes one system call, so not all of the data may be written.\n"
972"The number of bytes actually written is returned.");
973
974PyDoc_STRVAR(fileno_doc,
975"fileno() -> int. \"file descriptor\".\n"
976"\n"
977"This is needed for lower-level file interfaces, such the fcntl module.");
978
979PyDoc_STRVAR(seek_doc,
980"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
981"\n"
982"Argument offset is a byte count. Optional argument whence defaults to\n"
983"0 (offset from start of file, offset should be >= 0); other values are 1\n"
984"(move relative to current position, positive or negative), and 2 (move\n"
985"relative to end of file, usually negative, although many platforms allow\n"
986"seeking beyond the end of a file)."
987"\n"
988"Note that not all file objects are seekable.");
989
990#ifdef HAVE_FTRUNCATE
991PyDoc_STRVAR(truncate_doc,
Antoine Pitroub26dc462010-05-05 16:27:30 +0000992"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000993"\n"
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000994"Size defaults to the current file position, as returned by tell()."
995"The current file position is changed to the value of size.");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000996#endif
997
998PyDoc_STRVAR(tell_doc,
Antoine Pitroub26dc462010-05-05 16:27:30 +0000999"tell() -> int. Current file position");
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001000
1001PyDoc_STRVAR(readinto_doc,
Antoine Pitrou19690592009-06-12 20:14:08 +00001002"readinto() -> Same as RawIOBase.readinto().");
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001003
1004PyDoc_STRVAR(close_doc,
1005"close() -> None. Close the file.\n"
1006"\n"
1007"A closed file cannot be used for further I/O operations. close() may be\n"
1008"called more than once without error. Changes the fileno to -1.");
1009
1010PyDoc_STRVAR(isatty_doc,
1011"isatty() -> bool. True if the file is connected to a tty device.");
1012
1013PyDoc_STRVAR(seekable_doc,
1014"seekable() -> bool. True if file supports random-access.");
1015
1016PyDoc_STRVAR(readable_doc,
1017"readable() -> bool. True if file was opened in a read mode.");
1018
1019PyDoc_STRVAR(writable_doc,
1020"writable() -> bool. True if file was opened in a write mode.");
1021
1022static PyMethodDef fileio_methods[] = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001023 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1024 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1025 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1026 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1027 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1028 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001029#ifdef HAVE_FTRUNCATE
Antoine Pitroub26dc462010-05-05 16:27:30 +00001030 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001031#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +00001032 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1033 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1034 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1035 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1036 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1037 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
1038 {NULL, NULL} /* sentinel */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001039};
1040
1041/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1042
1043static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001044get_closed(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001045{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001046 return PyBool_FromLong((long)(self->fd < 0));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001047}
1048
1049static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001050get_closefd(fileio *self, void *closure)
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001051{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001052 return PyBool_FromLong((long)(self->closefd));
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001053}
1054
1055static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001056get_mode(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001057{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001058 return PyUnicode_FromString(mode_string(self));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001059}
1060
1061static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001062 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1063 {"closefd", (getter)get_closefd, NULL,
1064 "True if the file descriptor will be closed"},
1065 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1066 {NULL},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001067};
1068
1069PyTypeObject PyFileIO_Type = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001070 PyVarObject_HEAD_INIT(NULL, 0)
1071 "_io.FileIO",
1072 sizeof(fileio),
1073 0,
1074 (destructor)fileio_dealloc, /* tp_dealloc */
1075 0, /* tp_print */
1076 0, /* tp_getattr */
1077 0, /* tp_setattr */
1078 0, /* tp_reserved */
1079 (reprfunc)fileio_repr, /* tp_repr */
1080 0, /* tp_as_number */
1081 0, /* tp_as_sequence */
1082 0, /* tp_as_mapping */
1083 0, /* tp_hash */
1084 0, /* tp_call */
1085 0, /* tp_str */
1086 PyObject_GenericGetAttr, /* tp_getattro */
1087 0, /* tp_setattro */
1088 0, /* tp_as_buffer */
1089 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1090 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1091 fileio_doc, /* tp_doc */
1092 (traverseproc)fileio_traverse, /* tp_traverse */
1093 (inquiry)fileio_clear, /* tp_clear */
1094 0, /* tp_richcompare */
1095 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1096 0, /* tp_iter */
1097 0, /* tp_iternext */
1098 fileio_methods, /* tp_methods */
1099 0, /* tp_members */
1100 fileio_getsetlist, /* tp_getset */
1101 0, /* tp_base */
1102 0, /* tp_dict */
1103 0, /* tp_descr_get */
1104 0, /* tp_descr_set */
1105 offsetof(fileio, dict), /* tp_dictoffset */
1106 fileio_init, /* tp_init */
1107 PyType_GenericAlloc, /* tp_alloc */
1108 fileio_new, /* tp_new */
1109 PyObject_GC_Del, /* tp_free */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001110};