blob: 5946e6a2bcc5d156d60a1610162b2da6818edb1d [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;
Antoine Pitrou213fec42013-09-04 20:46:33 +020050 unsigned int appending : 1;
Antoine Pitroub26dc462010-05-05 16:27:30 +000051 signed int seekable : 2; /* -1 means unknown */
52 unsigned int closefd : 1;
53 PyObject *weakreflist;
54 PyObject *dict;
Antoine Pitrou19690592009-06-12 20:14:08 +000055} fileio;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000056
57PyTypeObject PyFileIO_Type;
58
59#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
60
Antoine Pitrou19690592009-06-12 20:14:08 +000061int
62_PyFileIO_closed(PyObject *self)
63{
Antoine Pitroub26dc462010-05-05 16:27:30 +000064 return ((fileio *)self)->fd < 0;
Antoine Pitrou19690592009-06-12 20:14:08 +000065}
66
Antoine Pitroue741cc62009-01-21 00:45:36 +000067static PyObject *
68portable_lseek(int fd, PyObject *posobj, int whence);
69
Antoine Pitrou19690592009-06-12 20:14:08 +000070static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
71
72/* Returns 0 on success, -1 with exception set on failure. */
Christian Heimes7f39c9f2008-01-25 12:18:43 +000073static int
Antoine Pitrou19690592009-06-12 20:14:08 +000074internal_close(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +000075{
Antoine Pitroub26dc462010-05-05 16:27:30 +000076 int err = 0;
77 int save_errno = 0;
78 if (self->fd >= 0) {
79 int fd = self->fd;
80 self->fd = -1;
81 /* fd is accessible and someone else may have closed it */
82 if (_PyVerify_fd(fd)) {
83 Py_BEGIN_ALLOW_THREADS
84 err = close(fd);
85 if (err < 0)
86 save_errno = errno;
87 Py_END_ALLOW_THREADS
88 } else {
89 save_errno = errno;
90 err = -1;
91 }
92 }
93 if (err < 0) {
94 errno = save_errno;
95 PyErr_SetFromErrno(PyExc_IOError);
96 return -1;
97 }
98 return 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000099}
100
101static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000102fileio_close(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000103{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000104 if (!self->closefd) {
105 self->fd = -1;
106 Py_RETURN_NONE;
107 }
108 errno = internal_close(self);
109 if (errno < 0)
110 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000111
Antoine Pitroub26dc462010-05-05 16:27:30 +0000112 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
113 "close", "O", self);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000114}
115
116static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000117fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000118{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000119 fileio *self;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000120
Antoine Pitroub26dc462010-05-05 16:27:30 +0000121 assert(type != NULL && type->tp_alloc != NULL);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000122
Antoine Pitroub26dc462010-05-05 16:27:30 +0000123 self = (fileio *) type->tp_alloc(type, 0);
124 if (self != NULL) {
125 self->fd = -1;
126 self->readable = 0;
127 self->writable = 0;
Antoine Pitrou213fec42013-09-04 20:46:33 +0200128 self->appending = 0;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000129 self->seekable = -1;
130 self->closefd = 1;
131 self->weakreflist = NULL;
132 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000133
Antoine Pitroub26dc462010-05-05 16:27:30 +0000134 return (PyObject *) self;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000135}
136
137/* On Unix, open will succeed for directories.
138 In Python, there should be no file objects referring to
139 directories, so we need a check. */
140
141static int
Antoine Pitrouc2ec9922012-07-06 18:48:24 +0200142dircheck(fileio* self, PyObject *nameobj)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000143{
144#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000145 struct stat buf;
146 if (self->fd < 0)
147 return 0;
148 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
Antoine Pitrouc2ec9922012-07-06 18:48:24 +0200149 errno = EISDIR;
150 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
Antoine Pitroub26dc462010-05-05 16:27:30 +0000151 return -1;
152 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000153#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000154 return 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000155}
156
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000157static int
158check_fd(int fd)
159{
160#if defined(HAVE_FSTAT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000161 struct stat buf;
162 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
163 PyObject *exc;
164 char *msg = strerror(EBADF);
165 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
166 EBADF, msg);
167 PyErr_SetObject(PyExc_OSError, exc);
168 Py_XDECREF(exc);
169 return -1;
170 }
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000171#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000172 return 0;
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000173}
174
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000175
176static int
177fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
178{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000179 fileio *self = (fileio *) oself;
180 static char *kwlist[] = {"file", "mode", "closefd", NULL};
181 const char *name = NULL;
182 PyObject *nameobj, *stringobj = NULL;
183 char *mode = "r";
184 char *s;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000185#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000186 Py_UNICODE *widename = NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000187#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000188 int ret = 0;
Antoine Pitrou213fec42013-09-04 20:46:33 +0200189 int rwa = 0, plus = 0;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000190 int flags = 0;
191 int fd = -1;
192 int closefd = 1;
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200193 int fd_is_own = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000194
Antoine Pitroub26dc462010-05-05 16:27:30 +0000195 assert(PyFileIO_Check(oself));
196 if (self->fd >= 0) {
Hynek Schlawack877effc2012-05-25 09:24:18 +0200197 if (self->closefd) {
198 /* Have to close the existing file first. */
199 if (internal_close(self) < 0)
200 return -1;
201 }
202 else
203 self->fd = -1;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000204 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000205
Antoine Pitroub26dc462010-05-05 16:27:30 +0000206 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
207 kwlist, &nameobj, &mode, &closefd))
208 return -1;
Antoine Pitrou19690592009-06-12 20:14:08 +0000209
Antoine Pitroub26dc462010-05-05 16:27:30 +0000210 if (PyFloat_Check(nameobj)) {
211 PyErr_SetString(PyExc_TypeError,
212 "integer argument expected, got float");
213 return -1;
214 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000215
Serhiy Storchaka74f49ab2013-01-19 12:55:39 +0200216 fd = _PyLong_AsInt(nameobj);
Antoine Pitroub26dc462010-05-05 16:27:30 +0000217 if (fd < 0) {
218 if (!PyErr_Occurred()) {
219 PyErr_SetString(PyExc_ValueError,
220 "Negative filedescriptor");
221 return -1;
222 }
223 PyErr_Clear();
224 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000225
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +0000226#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000227 if (PyUnicode_Check(nameobj))
228 widename = PyUnicode_AS_UNICODE(nameobj);
229 if (widename == NULL)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000230#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000231 if (fd < 0)
232 {
233 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
234 Py_ssize_t namelen;
235 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
236 return -1;
237 }
238 else {
239 PyObject *u = PyUnicode_FromObject(nameobj);
Antoine Pitrou19690592009-06-12 20:14:08 +0000240
Antoine Pitroub26dc462010-05-05 16:27:30 +0000241 if (u == NULL)
242 return -1;
Antoine Pitrou19690592009-06-12 20:14:08 +0000243
Antoine Pitroub26dc462010-05-05 16:27:30 +0000244 stringobj = PyUnicode_AsEncodedString(
245 u, Py_FileSystemDefaultEncoding, NULL);
246 Py_DECREF(u);
247 if (stringobj == NULL)
248 return -1;
249 if (!PyBytes_Check(stringobj)) {
250 PyErr_SetString(PyExc_TypeError,
251 "encoder failed to return bytes");
252 goto error;
253 }
254 name = PyBytes_AS_STRING(stringobj);
255 }
256 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000257
Antoine Pitroub26dc462010-05-05 16:27:30 +0000258 s = mode;
259 while (*s) {
260 switch (*s++) {
261 case 'r':
262 if (rwa) {
263 bad_mode:
264 PyErr_SetString(PyExc_ValueError,
Georg Brandl10603802010-11-26 08:10:41 +0000265 "Must have exactly one of read/write/append "
266 "mode and at most one plus");
Antoine Pitroub26dc462010-05-05 16:27:30 +0000267 goto error;
268 }
269 rwa = 1;
270 self->readable = 1;
271 break;
272 case 'w':
273 if (rwa)
274 goto bad_mode;
275 rwa = 1;
276 self->writable = 1;
277 flags |= O_CREAT | O_TRUNC;
278 break;
279 case 'a':
280 if (rwa)
281 goto bad_mode;
282 rwa = 1;
283 self->writable = 1;
Antoine Pitrou213fec42013-09-04 20:46:33 +0200284 self->appending = 1;
285 flags |= O_APPEND | O_CREAT;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000286 break;
287 case 'b':
288 break;
289 case '+':
290 if (plus)
291 goto bad_mode;
292 self->readable = self->writable = 1;
293 plus = 1;
294 break;
295 default:
296 PyErr_Format(PyExc_ValueError,
297 "invalid mode: %.200s", mode);
298 goto error;
299 }
300 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000301
Antoine Pitroub26dc462010-05-05 16:27:30 +0000302 if (!rwa)
303 goto bad_mode;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000304
Antoine Pitroub26dc462010-05-05 16:27:30 +0000305 if (self->readable && self->writable)
306 flags |= O_RDWR;
307 else if (self->readable)
308 flags |= O_RDONLY;
309 else
310 flags |= O_WRONLY;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000311
312#ifdef O_BINARY
Antoine Pitroub26dc462010-05-05 16:27:30 +0000313 flags |= O_BINARY;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000314#endif
315
Antoine Pitroub26dc462010-05-05 16:27:30 +0000316 if (fd >= 0) {
317 if (check_fd(fd))
318 goto error;
319 self->fd = fd;
320 self->closefd = closefd;
321 }
322 else {
323 self->closefd = 1;
324 if (!closefd) {
325 PyErr_SetString(PyExc_ValueError,
326 "Cannot use closefd=False with file name");
327 goto error;
328 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000329
Antoine Pitroub26dc462010-05-05 16:27:30 +0000330 Py_BEGIN_ALLOW_THREADS
331 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000332#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000333 if (widename != NULL)
334 self->fd = _wopen(widename, flags, 0666);
335 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000336#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000337 self->fd = open(name, flags, 0666);
338 Py_END_ALLOW_THREADS
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200339 fd_is_own = 1;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000340 if (self->fd < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000341#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000342 if (widename != NULL)
343 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
344 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000345#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000346 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
347 goto error;
348 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000349 }
Antoine Pitrouc2ec9922012-07-06 18:48:24 +0200350 if (dircheck(self, nameobj) < 0)
351 goto error;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000352
Antoine Pitroub26dc462010-05-05 16:27:30 +0000353 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
354 goto error;
Antoine Pitrou19690592009-06-12 20:14:08 +0000355
Antoine Pitrou213fec42013-09-04 20:46:33 +0200356 if (self->appending) {
Antoine Pitroub26dc462010-05-05 16:27:30 +0000357 /* For consistent behaviour, we explicitly seek to the
358 end of file (otherwise, it might be done only on the
359 first write()). */
360 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200361 if (pos == NULL)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000362 goto error;
363 Py_DECREF(pos);
364 }
Antoine Pitroue741cc62009-01-21 00:45:36 +0000365
Antoine Pitroub26dc462010-05-05 16:27:30 +0000366 goto done;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000367
368 error:
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200369 if (!fd_is_own)
370 self->fd = -1;
371
Antoine Pitroub26dc462010-05-05 16:27:30 +0000372 ret = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000373
374 done:
Antoine Pitroub26dc462010-05-05 16:27:30 +0000375 Py_CLEAR(stringobj);
376 return ret;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000377}
378
Antoine Pitrou19690592009-06-12 20:14:08 +0000379static int
380fileio_traverse(fileio *self, visitproc visit, void *arg)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000381{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000382 Py_VISIT(self->dict);
383 return 0;
Antoine Pitrou19690592009-06-12 20:14:08 +0000384}
385
386static int
387fileio_clear(fileio *self)
388{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000389 Py_CLEAR(self->dict);
390 return 0;
Antoine Pitrou19690592009-06-12 20:14:08 +0000391}
392
393static void
394fileio_dealloc(fileio *self)
395{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000396 if (_PyIOBase_finalize((PyObject *) self) < 0)
397 return;
398 _PyObject_GC_UNTRACK(self);
399 if (self->weakreflist != NULL)
400 PyObject_ClearWeakRefs((PyObject *) self);
401 Py_CLEAR(self->dict);
402 Py_TYPE(self)->tp_free((PyObject *)self);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000403}
404
405static PyObject *
406err_closed(void)
407{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000408 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
409 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000410}
411
412static PyObject *
413err_mode(char *action)
414{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000415 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
416 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000417}
418
419static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000420fileio_fileno(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000421{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000422 if (self->fd < 0)
423 return err_closed();
424 return PyInt_FromLong((long) self->fd);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000425}
426
427static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000428fileio_readable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000429{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000430 if (self->fd < 0)
431 return err_closed();
432 return PyBool_FromLong((long) self->readable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000433}
434
435static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000436fileio_writable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000437{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000438 if (self->fd < 0)
439 return err_closed();
440 return PyBool_FromLong((long) self->writable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000441}
442
443static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000444fileio_seekable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000445{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000446 if (self->fd < 0)
447 return err_closed();
448 if (self->seekable < 0) {
449 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
450 if (pos == NULL) {
451 PyErr_Clear();
452 self->seekable = 0;
453 } else {
454 Py_DECREF(pos);
455 self->seekable = 1;
456 }
457 }
458 return PyBool_FromLong((long) self->seekable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000459}
460
461static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000462fileio_readinto(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000463{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000464 Py_buffer pbuf;
Victor Stinner59729ff2011-07-05 11:28:19 +0200465 Py_ssize_t n, len;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000466
Antoine Pitroub26dc462010-05-05 16:27:30 +0000467 if (self->fd < 0)
468 return err_closed();
469 if (!self->readable)
470 return err_mode("reading");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000471
Antoine Pitroub26dc462010-05-05 16:27:30 +0000472 if (!PyArg_ParseTuple(args, "w*", &pbuf))
473 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000474
Antoine Pitroub26dc462010-05-05 16:27:30 +0000475 if (_PyVerify_fd(self->fd)) {
Victor Stinner59729ff2011-07-05 11:28:19 +0200476 len = pbuf.len;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000477 Py_BEGIN_ALLOW_THREADS
478 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200479#if defined(MS_WIN64) || defined(MS_WINDOWS)
480 if (len > INT_MAX)
481 len = INT_MAX;
482 n = read(self->fd, pbuf.buf, (int)len);
483#else
484 n = read(self->fd, pbuf.buf, len);
485#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000486 Py_END_ALLOW_THREADS
487 } else
488 n = -1;
489 PyBuffer_Release(&pbuf);
490 if (n < 0) {
491 if (errno == EAGAIN)
492 Py_RETURN_NONE;
493 PyErr_SetFromErrno(PyExc_IOError);
494 return NULL;
495 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000496
Antoine Pitroub26dc462010-05-05 16:27:30 +0000497 return PyLong_FromSsize_t(n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000498}
499
Antoine Pitrou19690592009-06-12 20:14:08 +0000500static size_t
501new_buffersize(fileio *self, size_t currentsize)
502{
503#ifdef HAVE_FSTAT
Antoine Pitroub26dc462010-05-05 16:27:30 +0000504 off_t pos, end;
505 struct stat st;
506 if (fstat(self->fd, &st) == 0) {
507 end = st.st_size;
508 pos = lseek(self->fd, 0L, SEEK_CUR);
509 /* Files claiming a size smaller than SMALLCHUNK may
510 actually be streaming pseudo-files. In this case, we
511 apply the more aggressive algorithm below.
512 */
513 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
514 /* Add 1 so if the file were to grow we'd notice. */
515 return currentsize + end - pos + 1;
516 }
517 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000518#endif
Nadeem Vawda36248152011-10-13 13:52:46 +0200519 /* Expand the buffer by an amount proportional to the current size,
520 giving us amortized linear-time behavior. Use a less-than-double
521 growth factor to avoid excessive allocation. */
522 return currentsize + (currentsize >> 3) + 6;
Antoine Pitrou19690592009-06-12 20:14:08 +0000523}
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000524
525static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000526fileio_readall(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000527{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000528 PyObject *result;
529 Py_ssize_t total = 0;
Victor Stinner23a32ba2013-01-03 03:33:21 +0100530 Py_ssize_t n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000531
Victor Stinner5100a402011-05-25 22:15:36 +0200532 if (self->fd < 0)
533 return err_closed();
Antoine Pitroub26dc462010-05-05 16:27:30 +0000534 if (!_PyVerify_fd(self->fd))
535 return PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou19690592009-06-12 20:14:08 +0000536
Antoine Pitroub26dc462010-05-05 16:27:30 +0000537 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
538 if (result == NULL)
539 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000540
Antoine Pitroub26dc462010-05-05 16:27:30 +0000541 while (1) {
542 size_t newsize = new_buffersize(self, total);
543 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
544 PyErr_SetString(PyExc_OverflowError,
545 "unbounded read returned more bytes "
546 "than a Python string can hold ");
547 Py_DECREF(result);
548 return NULL;
549 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000550
Antoine Pitroub26dc462010-05-05 16:27:30 +0000551 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
552 if (_PyBytes_Resize(&result, newsize) < 0) {
553 if (total == 0) {
554 Py_DECREF(result);
555 return NULL;
556 }
557 PyErr_Clear();
558 break;
559 }
560 }
561 Py_BEGIN_ALLOW_THREADS
562 errno = 0;
Victor Stinner23a32ba2013-01-03 03:33:21 +0100563 n = newsize - total;
564#if defined(MS_WIN64) || defined(MS_WINDOWS)
565 if (n > INT_MAX)
566 n = INT_MAX;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000567 n = read(self->fd,
568 PyBytes_AS_STRING(result) + total,
Victor Stinner23a32ba2013-01-03 03:33:21 +0100569 (int)n);
570#else
571 n = read(self->fd,
572 PyBytes_AS_STRING(result) + total,
573 n);
574#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000575 Py_END_ALLOW_THREADS
576 if (n == 0)
577 break;
578 if (n < 0) {
Gregory P. Smith99716162012-10-12 13:02:06 -0700579 if (errno == EINTR) {
580 if (PyErr_CheckSignals()) {
581 Py_DECREF(result);
582 return NULL;
583 }
584 continue;
585 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000586 if (total > 0)
587 break;
588 if (errno == EAGAIN) {
589 Py_DECREF(result);
590 Py_RETURN_NONE;
591 }
592 Py_DECREF(result);
593 PyErr_SetFromErrno(PyExc_IOError);
594 return NULL;
595 }
596 total += n;
597 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000598
Antoine Pitroub26dc462010-05-05 16:27:30 +0000599 if (PyBytes_GET_SIZE(result) > total) {
600 if (_PyBytes_Resize(&result, total) < 0) {
601 /* This should never happen, but just in case */
602 Py_DECREF(result);
603 return NULL;
604 }
605 }
606 return result;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000607}
608
609static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000610fileio_read(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000611{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000612 char *ptr;
613 Py_ssize_t n;
614 Py_ssize_t size = -1;
615 PyObject *bytes;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000616
Antoine Pitroub26dc462010-05-05 16:27:30 +0000617 if (self->fd < 0)
618 return err_closed();
619 if (!self->readable)
620 return err_mode("reading");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000621
Antoine Pitroub26dc462010-05-05 16:27:30 +0000622 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
623 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000624
Antoine Pitroub26dc462010-05-05 16:27:30 +0000625 if (size < 0) {
626 return fileio_readall(self);
627 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000628
Victor Stinner59729ff2011-07-05 11:28:19 +0200629#if defined(MS_WIN64) || defined(MS_WINDOWS)
630 if (size > INT_MAX)
631 size = INT_MAX;
632#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000633 bytes = PyBytes_FromStringAndSize(NULL, size);
634 if (bytes == NULL)
635 return NULL;
636 ptr = PyBytes_AS_STRING(bytes);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000637
Antoine Pitroub26dc462010-05-05 16:27:30 +0000638 if (_PyVerify_fd(self->fd)) {
639 Py_BEGIN_ALLOW_THREADS
640 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200641#if defined(MS_WIN64) || defined(MS_WINDOWS)
642 n = read(self->fd, ptr, (int)size);
643#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000644 n = read(self->fd, ptr, size);
Victor Stinner59729ff2011-07-05 11:28:19 +0200645#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000646 Py_END_ALLOW_THREADS
647 } else
648 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000649
Antoine Pitroub26dc462010-05-05 16:27:30 +0000650 if (n < 0) {
651 Py_DECREF(bytes);
652 if (errno == EAGAIN)
653 Py_RETURN_NONE;
654 PyErr_SetFromErrno(PyExc_IOError);
655 return NULL;
656 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000657
Antoine Pitroub26dc462010-05-05 16:27:30 +0000658 if (n != size) {
659 if (_PyBytes_Resize(&bytes, n) < 0) {
660 Py_DECREF(bytes);
661 return NULL;
662 }
663 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000664
Antoine Pitroub26dc462010-05-05 16:27:30 +0000665 return (PyObject *) bytes;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000666}
667
668static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000669fileio_write(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000670{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000671 Py_buffer pbuf;
Victor Stinner59729ff2011-07-05 11:28:19 +0200672 Py_ssize_t n, len;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000673
Antoine Pitroub26dc462010-05-05 16:27:30 +0000674 if (self->fd < 0)
675 return err_closed();
676 if (!self->writable)
677 return err_mode("writing");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000678
Antoine Pitroub26dc462010-05-05 16:27:30 +0000679 if (!PyArg_ParseTuple(args, "s*", &pbuf))
680 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000681
Antoine Pitroub26dc462010-05-05 16:27:30 +0000682 if (_PyVerify_fd(self->fd)) {
683 Py_BEGIN_ALLOW_THREADS
684 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200685 len = pbuf.len;
686#if defined(MS_WIN64) || defined(MS_WINDOWS)
687 if (len > INT_MAX)
688 len = INT_MAX;
689 n = write(self->fd, pbuf.buf, (int)len);
690#else
691 n = write(self->fd, pbuf.buf, len);
692#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000693 Py_END_ALLOW_THREADS
694 } else
695 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000696
Antoine Pitroub26dc462010-05-05 16:27:30 +0000697 PyBuffer_Release(&pbuf);
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000698
Antoine Pitroub26dc462010-05-05 16:27:30 +0000699 if (n < 0) {
700 if (errno == EAGAIN)
701 Py_RETURN_NONE;
702 PyErr_SetFromErrno(PyExc_IOError);
703 return NULL;
704 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000705
Antoine Pitroub26dc462010-05-05 16:27:30 +0000706 return PyLong_FromSsize_t(n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000707}
708
709/* XXX Windows support below is likely incomplete */
710
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000711/* Cribbed from posix_lseek() */
712static PyObject *
713portable_lseek(int fd, PyObject *posobj, int whence)
714{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000715 Py_off_t pos, res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000716
717#ifdef SEEK_SET
Antoine Pitroub26dc462010-05-05 16:27:30 +0000718 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
719 switch (whence) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000720#if SEEK_SET != 0
Antoine Pitroub26dc462010-05-05 16:27:30 +0000721 case 0: whence = SEEK_SET; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000722#endif
723#if SEEK_CUR != 1
Antoine Pitroub26dc462010-05-05 16:27:30 +0000724 case 1: whence = SEEK_CUR; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000725#endif
Benjamin Peterson8024cec2009-01-20 14:31:08 +0000726#if SEEK_END != 2
Antoine Pitroub26dc462010-05-05 16:27:30 +0000727 case 2: whence = SEEK_END; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000728#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000729 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000730#endif /* SEEK_SET */
731
Antoine Pitroub26dc462010-05-05 16:27:30 +0000732 if (posobj == NULL)
733 pos = 0;
734 else {
735 if(PyFloat_Check(posobj)) {
736 PyErr_SetString(PyExc_TypeError, "an integer is required");
737 return NULL;
738 }
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000739#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000740 pos = PyLong_AsLongLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000741#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000742 pos = PyLong_AsLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000743#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000744 if (PyErr_Occurred())
745 return NULL;
746 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000747
Antoine Pitroub26dc462010-05-05 16:27:30 +0000748 if (_PyVerify_fd(fd)) {
749 Py_BEGIN_ALLOW_THREADS
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000750#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000751 res = _lseeki64(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000752#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000753 res = lseek(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000754#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000755 Py_END_ALLOW_THREADS
756 } else
757 res = -1;
758 if (res < 0)
759 return PyErr_SetFromErrno(PyExc_IOError);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000760
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000761#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000762 return PyLong_FromLongLong(res);
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000763#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000764 return PyLong_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000765#endif
766}
767
768static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000769fileio_seek(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000770{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000771 PyObject *posobj;
772 int whence = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000773
Antoine Pitroub26dc462010-05-05 16:27:30 +0000774 if (self->fd < 0)
775 return err_closed();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000776
Antoine Pitroub26dc462010-05-05 16:27:30 +0000777 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
778 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000779
Antoine Pitroub26dc462010-05-05 16:27:30 +0000780 return portable_lseek(self->fd, posobj, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000781}
782
783static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000784fileio_tell(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000785{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000786 if (self->fd < 0)
787 return err_closed();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000788
Antoine Pitroub26dc462010-05-05 16:27:30 +0000789 return portable_lseek(self->fd, NULL, 1);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000790}
791
792#ifdef HAVE_FTRUNCATE
793static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000794fileio_truncate(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000795{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000796 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000797#ifndef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000798 Py_off_t pos;
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000799#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000800 int ret;
801 int fd;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000802
Antoine Pitroub26dc462010-05-05 16:27:30 +0000803 fd = self->fd;
804 if (fd < 0)
805 return err_closed();
806 if (!self->writable)
807 return err_mode("writing");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000808
Antoine Pitroub26dc462010-05-05 16:27:30 +0000809 if (!PyArg_ParseTuple(args, "|O", &posobj))
810 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000811
Antoine Pitroub26dc462010-05-05 16:27:30 +0000812 if (posobj == Py_None || posobj == NULL) {
813 /* Get the current position. */
814 posobj = portable_lseek(fd, NULL, 1);
815 if (posobj == NULL)
816 return NULL;
817 }
818 else {
819 Py_INCREF(posobj);
820 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000821
822#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000823 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
824 so don't even try using it. */
825 {
826 PyObject *oldposobj, *tempposobj;
827 HANDLE hFile;
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000828
Antoine Pitroub26dc462010-05-05 16:27:30 +0000829 /* we save the file pointer position */
830 oldposobj = portable_lseek(fd, NULL, 1);
831 if (oldposobj == NULL) {
832 Py_DECREF(posobj);
833 return NULL;
834 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000835
Antoine Pitroub26dc462010-05-05 16:27:30 +0000836 /* we then move to the truncation position */
837 tempposobj = portable_lseek(fd, posobj, 0);
838 if (tempposobj == NULL) {
839 Py_DECREF(oldposobj);
840 Py_DECREF(posobj);
841 return NULL;
842 }
843 Py_DECREF(tempposobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000844
Antoine Pitroub26dc462010-05-05 16:27:30 +0000845 /* Truncate. Note that this may grow the file! */
846 Py_BEGIN_ALLOW_THREADS
847 errno = 0;
848 hFile = (HANDLE)_get_osfhandle(fd);
849 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
850 if (ret == 0) {
851 ret = SetEndOfFile(hFile) == 0;
852 if (ret)
853 errno = EACCES;
854 }
855 Py_END_ALLOW_THREADS
856
857 /* we restore the file pointer position in any case */
858 tempposobj = portable_lseek(fd, oldposobj, 0);
859 Py_DECREF(oldposobj);
860 if (tempposobj == NULL) {
861 Py_DECREF(posobj);
862 return NULL;
863 }
864 Py_DECREF(tempposobj);
865 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000866#else
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000867
868#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000869 pos = PyLong_AsLongLong(posobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000870#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000871 pos = PyLong_AsLong(posobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000872#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000873 if (PyErr_Occurred()){
874 Py_DECREF(posobj);
875 return NULL;
876 }
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000877
Antoine Pitroub26dc462010-05-05 16:27:30 +0000878 Py_BEGIN_ALLOW_THREADS
879 errno = 0;
880 ret = ftruncate(fd, pos);
881 Py_END_ALLOW_THREADS
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000882
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000883#endif /* !MS_WINDOWS */
884
Antoine Pitroub26dc462010-05-05 16:27:30 +0000885 if (ret != 0) {
886 Py_DECREF(posobj);
887 PyErr_SetFromErrno(PyExc_IOError);
888 return NULL;
889 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000890
Antoine Pitroub26dc462010-05-05 16:27:30 +0000891 return posobj;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000892}
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000893#endif /* HAVE_FTRUNCATE */
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000894
895static char *
Antoine Pitrou19690592009-06-12 20:14:08 +0000896mode_string(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000897{
Antoine Pitrou213fec42013-09-04 20:46:33 +0200898 if (self->appending) {
899 if (self->readable)
900 return "ab+";
901 else
902 return "ab";
903 }
904 else if (self->readable) {
Antoine Pitroub26dc462010-05-05 16:27:30 +0000905 if (self->writable)
906 return "rb+";
907 else
908 return "rb";
909 }
910 else
911 return "wb";
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000912}
913
914static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000915fileio_repr(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000916{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000917 PyObject *nameobj, *res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000918
Antoine Pitroub26dc462010-05-05 16:27:30 +0000919 if (self->fd < 0)
920 return PyString_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou19690592009-06-12 20:14:08 +0000921
Antoine Pitroub26dc462010-05-05 16:27:30 +0000922 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
923 if (nameobj == NULL) {
924 if (PyErr_ExceptionMatches(PyExc_AttributeError))
925 PyErr_Clear();
926 else
927 return NULL;
928 res = PyString_FromFormat("<_io.FileIO fd=%d mode='%s'>",
929 self->fd, mode_string(self));
930 }
931 else {
932 PyObject *repr = PyObject_Repr(nameobj);
933 Py_DECREF(nameobj);
934 if (repr == NULL)
935 return NULL;
936 res = PyString_FromFormat("<_io.FileIO name=%s mode='%s'>",
937 PyString_AS_STRING(repr),
938 mode_string(self));
939 Py_DECREF(repr);
940 }
941 return res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000942}
943
944static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000945fileio_isatty(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000946{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000947 long res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000948
Antoine Pitroub26dc462010-05-05 16:27:30 +0000949 if (self->fd < 0)
950 return err_closed();
951 Py_BEGIN_ALLOW_THREADS
952 res = isatty(self->fd);
953 Py_END_ALLOW_THREADS
954 return PyBool_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000955}
956
957
958PyDoc_STRVAR(fileio_doc,
959"file(name: str[, mode: str]) -> file IO object\n"
960"\n"
961"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitroub26dc462010-05-05 16:27:30 +0000962"writing or appending. The file will be created if it doesn't exist\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000963"when opened for writing or appending; it will be truncated when\n"
964"opened for writing. Add a '+' to the mode to allow simultaneous\n"
965"reading and writing.");
966
967PyDoc_STRVAR(read_doc,
968"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
969"\n"
970"Only makes one system call, so less data may be returned than requested\n"
971"In non-blocking mode, returns None if no data is available.\n"
972"On end-of-file, returns ''.");
973
974PyDoc_STRVAR(readall_doc,
975"readall() -> bytes. read all data from the file, returned as bytes.\n"
976"\n"
977"In non-blocking mode, returns as much as is immediately available,\n"
978"or None if no data is available. On end-of-file, returns ''.");
979
980PyDoc_STRVAR(write_doc,
981"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
982"\n"
983"Only makes one system call, so not all of the data may be written.\n"
984"The number of bytes actually written is returned.");
985
986PyDoc_STRVAR(fileno_doc,
987"fileno() -> int. \"file descriptor\".\n"
988"\n"
989"This is needed for lower-level file interfaces, such the fcntl module.");
990
991PyDoc_STRVAR(seek_doc,
992"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
993"\n"
994"Argument offset is a byte count. Optional argument whence defaults to\n"
995"0 (offset from start of file, offset should be >= 0); other values are 1\n"
996"(move relative to current position, positive or negative), and 2 (move\n"
997"relative to end of file, usually negative, although many platforms allow\n"
998"seeking beyond the end of a file)."
999"\n"
1000"Note that not all file objects are seekable.");
1001
1002#ifdef HAVE_FTRUNCATE
1003PyDoc_STRVAR(truncate_doc,
Antoine Pitroub26dc462010-05-05 16:27:30 +00001004"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001005"\n"
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001006"Size defaults to the current file position, as returned by tell()."
1007"The current file position is changed to the value of size.");
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001008#endif
1009
1010PyDoc_STRVAR(tell_doc,
Antoine Pitroub26dc462010-05-05 16:27:30 +00001011"tell() -> int. Current file position");
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001012
1013PyDoc_STRVAR(readinto_doc,
Antoine Pitrou19690592009-06-12 20:14:08 +00001014"readinto() -> Same as RawIOBase.readinto().");
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001015
1016PyDoc_STRVAR(close_doc,
1017"close() -> None. Close the file.\n"
1018"\n"
1019"A closed file cannot be used for further I/O operations. close() may be\n"
1020"called more than once without error. Changes the fileno to -1.");
1021
1022PyDoc_STRVAR(isatty_doc,
1023"isatty() -> bool. True if the file is connected to a tty device.");
1024
1025PyDoc_STRVAR(seekable_doc,
1026"seekable() -> bool. True if file supports random-access.");
1027
1028PyDoc_STRVAR(readable_doc,
1029"readable() -> bool. True if file was opened in a read mode.");
1030
1031PyDoc_STRVAR(writable_doc,
1032"writable() -> bool. True if file was opened in a write mode.");
1033
1034static PyMethodDef fileio_methods[] = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001035 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1036 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1037 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1038 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1039 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1040 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001041#ifdef HAVE_FTRUNCATE
Antoine Pitroub26dc462010-05-05 16:27:30 +00001042 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001043#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +00001044 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1045 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1046 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1047 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1048 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1049 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
1050 {NULL, NULL} /* sentinel */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001051};
1052
1053/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1054
1055static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001056get_closed(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001057{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001058 return PyBool_FromLong((long)(self->fd < 0));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001059}
1060
1061static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001062get_closefd(fileio *self, void *closure)
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001063{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001064 return PyBool_FromLong((long)(self->closefd));
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001065}
1066
1067static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001068get_mode(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001069{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001070 return PyUnicode_FromString(mode_string(self));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001071}
1072
1073static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001074 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1075 {"closefd", (getter)get_closefd, NULL,
1076 "True if the file descriptor will be closed"},
1077 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1078 {NULL},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001079};
1080
1081PyTypeObject PyFileIO_Type = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001082 PyVarObject_HEAD_INIT(NULL, 0)
1083 "_io.FileIO",
1084 sizeof(fileio),
1085 0,
1086 (destructor)fileio_dealloc, /* tp_dealloc */
1087 0, /* tp_print */
1088 0, /* tp_getattr */
1089 0, /* tp_setattr */
1090 0, /* tp_reserved */
1091 (reprfunc)fileio_repr, /* tp_repr */
1092 0, /* tp_as_number */
1093 0, /* tp_as_sequence */
1094 0, /* tp_as_mapping */
1095 0, /* tp_hash */
1096 0, /* tp_call */
1097 0, /* tp_str */
1098 PyObject_GenericGetAttr, /* tp_getattro */
1099 0, /* tp_setattro */
1100 0, /* tp_as_buffer */
1101 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1102 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1103 fileio_doc, /* tp_doc */
1104 (traverseproc)fileio_traverse, /* tp_traverse */
1105 (inquiry)fileio_clear, /* tp_clear */
1106 0, /* tp_richcompare */
1107 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1108 0, /* tp_iter */
1109 0, /* tp_iternext */
1110 fileio_methods, /* tp_methods */
1111 0, /* tp_members */
1112 fileio_getsetlist, /* tp_getset */
1113 0, /* tp_base */
1114 0, /* tp_dict */
1115 0, /* tp_descr_get */
1116 0, /* tp_descr_set */
1117 offsetof(fileio, dict), /* tp_dictoffset */
1118 fileio_init, /* tp_init */
1119 PyType_GenericAlloc, /* tp_alloc */
1120 fileio_new, /* tp_new */
1121 PyObject_GC_Del, /* tp_free */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001122};