blob: 4a71a57ec0dea4cd1a4f24762f63a7db1d2762aa [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
Steve Dowerf85dbfc2016-12-28 15:41:09 -080011#ifdef HAVE_IO_H
12#include <io.h>
13#endif
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +000014#ifdef HAVE_FCNTL_H
Christian Heimes7f39c9f2008-01-25 12:18:43 +000015#include <fcntl.h>
Andrew M. Kuchling4b81bc72010-02-22 23:12:00 +000016#endif
Christian Heimes7f39c9f2008-01-25 12:18:43 +000017#include <stddef.h> /* For offsetof */
Antoine Pitrou19690592009-06-12 20:14:08 +000018#include "_iomodule.h"
Christian Heimes7f39c9f2008-01-25 12:18:43 +000019
20/*
21 * Known likely problems:
22 *
23 * - Files larger then 2**32-1
24 * - Files with unicode filenames
25 * - Passing numbers greater than 2**32-1 when an integer is expected
26 * - Making it work on Windows and other oddball platforms
27 *
28 * To Do:
29 *
30 * - autoconfify header file inclusion
31 */
32
33#ifdef MS_WINDOWS
34/* can simulate truncate with Win32 API functions; see file_truncate */
35#define HAVE_FTRUNCATE
36#define WIN32_LEAN_AND_MEAN
37#include <windows.h>
38#endif
39
Antoine Pitrou19690592009-06-12 20:14:08 +000040#if BUFSIZ < (8*1024)
41#define SMALLCHUNK (8*1024)
42#elif (BUFSIZ >= (2 << 25))
43#error "unreasonable BUFSIZ > 64MB defined"
44#else
45#define SMALLCHUNK BUFSIZ
46#endif
47
Christian Heimes7f39c9f2008-01-25 12:18:43 +000048typedef struct {
Antoine Pitroub26dc462010-05-05 16:27:30 +000049 PyObject_HEAD
50 int fd;
51 unsigned int readable : 1;
52 unsigned int writable : 1;
Antoine Pitrou213fec42013-09-04 20:46:33 +020053 unsigned int appending : 1;
Antoine Pitroub26dc462010-05-05 16:27:30 +000054 signed int seekable : 2; /* -1 means unknown */
55 unsigned int closefd : 1;
56 PyObject *weakreflist;
57 PyObject *dict;
Antoine Pitrou19690592009-06-12 20:14:08 +000058} fileio;
Christian Heimes7f39c9f2008-01-25 12:18:43 +000059
60PyTypeObject PyFileIO_Type;
61
62#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
63
Antoine Pitrou19690592009-06-12 20:14:08 +000064int
65_PyFileIO_closed(PyObject *self)
66{
Antoine Pitroub26dc462010-05-05 16:27:30 +000067 return ((fileio *)self)->fd < 0;
Antoine Pitrou19690592009-06-12 20:14:08 +000068}
69
Antoine Pitroue741cc62009-01-21 00:45:36 +000070static PyObject *
71portable_lseek(int fd, PyObject *posobj, int whence);
72
Antoine Pitrou19690592009-06-12 20:14:08 +000073static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
74
75/* Returns 0 on success, -1 with exception set on failure. */
Christian Heimes7f39c9f2008-01-25 12:18:43 +000076static int
Antoine Pitrou19690592009-06-12 20:14:08 +000077internal_close(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +000078{
Antoine Pitroub26dc462010-05-05 16:27:30 +000079 int err = 0;
80 int save_errno = 0;
81 if (self->fd >= 0) {
82 int fd = self->fd;
83 self->fd = -1;
84 /* fd is accessible and someone else may have closed it */
85 if (_PyVerify_fd(fd)) {
86 Py_BEGIN_ALLOW_THREADS
87 err = close(fd);
88 if (err < 0)
89 save_errno = errno;
90 Py_END_ALLOW_THREADS
91 } else {
92 save_errno = errno;
93 err = -1;
94 }
95 }
96 if (err < 0) {
97 errno = save_errno;
98 PyErr_SetFromErrno(PyExc_IOError);
99 return -1;
100 }
101 return 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000102}
103
104static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000105fileio_close(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000106{
Serhiy Storchaka3173f7c2015-02-21 00:34:20 +0200107 PyObject *res;
108 res = PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
109 "close", "O", self);
Antoine Pitroub26dc462010-05-05 16:27:30 +0000110 if (!self->closefd) {
111 self->fd = -1;
Serhiy Storchaka3173f7c2015-02-21 00:34:20 +0200112 return res;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000113 }
Serhiy Storchaka3173f7c2015-02-21 00:34:20 +0200114 if (internal_close(self) < 0)
115 Py_CLEAR(res);
116 return res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000117}
118
119static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000120fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000121{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000122 fileio *self;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000123
Antoine Pitroub26dc462010-05-05 16:27:30 +0000124 assert(type != NULL && type->tp_alloc != NULL);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000125
Antoine Pitroub26dc462010-05-05 16:27:30 +0000126 self = (fileio *) type->tp_alloc(type, 0);
127 if (self != NULL) {
128 self->fd = -1;
129 self->readable = 0;
130 self->writable = 0;
Antoine Pitrou213fec42013-09-04 20:46:33 +0200131 self->appending = 0;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000132 self->seekable = -1;
133 self->closefd = 1;
134 self->weakreflist = NULL;
135 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000136
Antoine Pitroub26dc462010-05-05 16:27:30 +0000137 return (PyObject *) self;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000138}
139
140/* On Unix, open will succeed for directories.
141 In Python, there should be no file objects referring to
142 directories, so we need a check. */
143
144static int
Antoine Pitrouc2ec9922012-07-06 18:48:24 +0200145dircheck(fileio* self, PyObject *nameobj)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000146{
147#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000148 struct stat buf;
149 if (self->fd < 0)
150 return 0;
151 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
Antoine Pitrouc2ec9922012-07-06 18:48:24 +0200152 errno = EISDIR;
153 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
Antoine Pitroub26dc462010-05-05 16:27:30 +0000154 return -1;
155 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000156#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000157 return 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000158}
159
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000160static int
161check_fd(int fd)
162{
163#if defined(HAVE_FSTAT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000164 struct stat buf;
165 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
166 PyObject *exc;
167 char *msg = strerror(EBADF);
168 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
169 EBADF, msg);
170 PyErr_SetObject(PyExc_OSError, exc);
171 Py_XDECREF(exc);
172 return -1;
173 }
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000174#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000175 return 0;
Benjamin Peterson5848d1f2009-01-19 00:08:08 +0000176}
177
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000178
179static int
180fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
181{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000182 fileio *self = (fileio *) oself;
183 static char *kwlist[] = {"file", "mode", "closefd", NULL};
184 const char *name = NULL;
185 PyObject *nameobj, *stringobj = NULL;
186 char *mode = "r";
187 char *s;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000188#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000189 Py_UNICODE *widename = NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000190#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000191 int ret = 0;
Antoine Pitrou213fec42013-09-04 20:46:33 +0200192 int rwa = 0, plus = 0;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000193 int flags = 0;
194 int fd = -1;
195 int closefd = 1;
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200196 int fd_is_own = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000197
Antoine Pitroub26dc462010-05-05 16:27:30 +0000198 assert(PyFileIO_Check(oself));
199 if (self->fd >= 0) {
Hynek Schlawack877effc2012-05-25 09:24:18 +0200200 if (self->closefd) {
201 /* Have to close the existing file first. */
202 if (internal_close(self) < 0)
203 return -1;
204 }
205 else
206 self->fd = -1;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000207 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000208
Antoine Pitroub26dc462010-05-05 16:27:30 +0000209 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
210 kwlist, &nameobj, &mode, &closefd))
211 return -1;
Antoine Pitrou19690592009-06-12 20:14:08 +0000212
Antoine Pitroub26dc462010-05-05 16:27:30 +0000213 if (PyFloat_Check(nameobj)) {
214 PyErr_SetString(PyExc_TypeError,
215 "integer argument expected, got float");
216 return -1;
217 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000218
Serhiy Storchaka74f49ab2013-01-19 12:55:39 +0200219 fd = _PyLong_AsInt(nameobj);
Antoine Pitroub26dc462010-05-05 16:27:30 +0000220 if (fd < 0) {
221 if (!PyErr_Occurred()) {
222 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka46129542015-04-10 16:08:33 +0300223 "negative file descriptor");
Antoine Pitroub26dc462010-05-05 16:27:30 +0000224 return -1;
225 }
226 PyErr_Clear();
227 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000228
Hirokazu Yamamotob24bb272009-05-17 02:52:09 +0000229#ifdef MS_WINDOWS
Serhiy Storchaka3c9ce742016-07-01 23:34:44 +0300230 if (PyUnicode_Check(nameobj)) {
Antoine Pitroub26dc462010-05-05 16:27:30 +0000231 widename = PyUnicode_AS_UNICODE(nameobj);
Serhiy Storchaka3c9ce742016-07-01 23:34:44 +0300232 if (wcslen(widename) != (size_t)PyUnicode_GET_SIZE(nameobj)) {
233 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
234 return -1;
235 }
236 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000237 if (widename == NULL)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000238#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000239 if (fd < 0)
240 {
241 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
242 Py_ssize_t namelen;
243 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
244 return -1;
Serhiy Storchaka3c9ce742016-07-01 23:34:44 +0300245 if (strlen(name) != (size_t)namelen) {
246 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
247 return -1;
248 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000249 }
250 else {
251 PyObject *u = PyUnicode_FromObject(nameobj);
Antoine Pitrou19690592009-06-12 20:14:08 +0000252
Antoine Pitroub26dc462010-05-05 16:27:30 +0000253 if (u == NULL)
254 return -1;
Antoine Pitrou19690592009-06-12 20:14:08 +0000255
Antoine Pitroub26dc462010-05-05 16:27:30 +0000256 stringobj = PyUnicode_AsEncodedString(
257 u, Py_FileSystemDefaultEncoding, NULL);
258 Py_DECREF(u);
259 if (stringobj == NULL)
260 return -1;
261 if (!PyBytes_Check(stringobj)) {
262 PyErr_SetString(PyExc_TypeError,
263 "encoder failed to return bytes");
264 goto error;
265 }
266 name = PyBytes_AS_STRING(stringobj);
Serhiy Storchaka3c9ce742016-07-01 23:34:44 +0300267 if (strlen(name) != (size_t)PyBytes_GET_SIZE(stringobj)) {
268 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
269 goto error;
270 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000271 }
272 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000273
Antoine Pitroub26dc462010-05-05 16:27:30 +0000274 s = mode;
275 while (*s) {
276 switch (*s++) {
277 case 'r':
278 if (rwa) {
279 bad_mode:
280 PyErr_SetString(PyExc_ValueError,
Georg Brandl10603802010-11-26 08:10:41 +0000281 "Must have exactly one of read/write/append "
282 "mode and at most one plus");
Antoine Pitroub26dc462010-05-05 16:27:30 +0000283 goto error;
284 }
285 rwa = 1;
286 self->readable = 1;
287 break;
288 case 'w':
289 if (rwa)
290 goto bad_mode;
291 rwa = 1;
292 self->writable = 1;
293 flags |= O_CREAT | O_TRUNC;
294 break;
295 case 'a':
296 if (rwa)
297 goto bad_mode;
298 rwa = 1;
299 self->writable = 1;
Antoine Pitrou213fec42013-09-04 20:46:33 +0200300 self->appending = 1;
301 flags |= O_APPEND | O_CREAT;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000302 break;
303 case 'b':
304 break;
305 case '+':
306 if (plus)
307 goto bad_mode;
308 self->readable = self->writable = 1;
309 plus = 1;
310 break;
311 default:
312 PyErr_Format(PyExc_ValueError,
313 "invalid mode: %.200s", mode);
314 goto error;
315 }
316 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000317
Antoine Pitroub26dc462010-05-05 16:27:30 +0000318 if (!rwa)
319 goto bad_mode;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000320
Antoine Pitroub26dc462010-05-05 16:27:30 +0000321 if (self->readable && self->writable)
322 flags |= O_RDWR;
323 else if (self->readable)
324 flags |= O_RDONLY;
325 else
326 flags |= O_WRONLY;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000327
328#ifdef O_BINARY
Antoine Pitroub26dc462010-05-05 16:27:30 +0000329 flags |= O_BINARY;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000330#endif
331
Antoine Pitroub26dc462010-05-05 16:27:30 +0000332 if (fd >= 0) {
333 if (check_fd(fd))
334 goto error;
335 self->fd = fd;
336 self->closefd = closefd;
337 }
338 else {
339 self->closefd = 1;
340 if (!closefd) {
341 PyErr_SetString(PyExc_ValueError,
342 "Cannot use closefd=False with file name");
343 goto error;
344 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000345
Antoine Pitroub26dc462010-05-05 16:27:30 +0000346 Py_BEGIN_ALLOW_THREADS
347 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000348#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000349 if (widename != NULL)
350 self->fd = _wopen(widename, flags, 0666);
351 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000352#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000353 self->fd = open(name, flags, 0666);
354 Py_END_ALLOW_THREADS
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200355 fd_is_own = 1;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000356 if (self->fd < 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000357#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000358 if (widename != NULL)
359 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
360 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000361#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000362 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
363 goto error;
364 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000365 }
Antoine Pitrouc2ec9922012-07-06 18:48:24 +0200366 if (dircheck(self, nameobj) < 0)
367 goto error;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000368
Antoine Pitroub26dc462010-05-05 16:27:30 +0000369 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
370 goto error;
Antoine Pitrou19690592009-06-12 20:14:08 +0000371
Antoine Pitrou213fec42013-09-04 20:46:33 +0200372 if (self->appending) {
Antoine Pitroub26dc462010-05-05 16:27:30 +0000373 /* For consistent behaviour, we explicitly seek to the
374 end of file (otherwise, it might be done only on the
375 first write()). */
376 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200377 if (pos == NULL)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000378 goto error;
379 Py_DECREF(pos);
380 }
Antoine Pitroue741cc62009-01-21 00:45:36 +0000381
Antoine Pitroub26dc462010-05-05 16:27:30 +0000382 goto done;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000383
384 error:
Hynek Schlawack9bd4bf22012-06-21 19:45:19 +0200385 if (!fd_is_own)
386 self->fd = -1;
387
Antoine Pitroub26dc462010-05-05 16:27:30 +0000388 ret = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000389
390 done:
Antoine Pitroub26dc462010-05-05 16:27:30 +0000391 Py_CLEAR(stringobj);
392 return ret;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000393}
394
Antoine Pitrou19690592009-06-12 20:14:08 +0000395static int
396fileio_traverse(fileio *self, visitproc visit, void *arg)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000397{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000398 Py_VISIT(self->dict);
399 return 0;
Antoine Pitrou19690592009-06-12 20:14:08 +0000400}
401
402static int
403fileio_clear(fileio *self)
404{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000405 Py_CLEAR(self->dict);
406 return 0;
Antoine Pitrou19690592009-06-12 20:14:08 +0000407}
408
409static void
410fileio_dealloc(fileio *self)
411{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000412 if (_PyIOBase_finalize((PyObject *) self) < 0)
413 return;
414 _PyObject_GC_UNTRACK(self);
415 if (self->weakreflist != NULL)
416 PyObject_ClearWeakRefs((PyObject *) self);
417 Py_CLEAR(self->dict);
418 Py_TYPE(self)->tp_free((PyObject *)self);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000419}
420
421static PyObject *
422err_closed(void)
423{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000424 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
425 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000426}
427
428static PyObject *
429err_mode(char *action)
430{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000431 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
432 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000433}
434
435static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000436fileio_fileno(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 PyInt_FromLong((long) self->fd);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000441}
442
443static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000444fileio_readable(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 return PyBool_FromLong((long) self->readable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000449}
450
451static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000452fileio_writable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000453{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000454 if (self->fd < 0)
455 return err_closed();
456 return PyBool_FromLong((long) self->writable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000457}
458
459static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000460fileio_seekable(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000461{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000462 if (self->fd < 0)
463 return err_closed();
464 if (self->seekable < 0) {
465 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
466 if (pos == NULL) {
467 PyErr_Clear();
468 self->seekable = 0;
469 } else {
470 Py_DECREF(pos);
471 self->seekable = 1;
472 }
473 }
474 return PyBool_FromLong((long) self->seekable);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000475}
476
477static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000478fileio_readinto(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000479{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000480 Py_buffer pbuf;
Victor Stinner59729ff2011-07-05 11:28:19 +0200481 Py_ssize_t n, len;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000482
Antoine Pitroub26dc462010-05-05 16:27:30 +0000483 if (self->fd < 0)
484 return err_closed();
485 if (!self->readable)
486 return err_mode("reading");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000487
Antoine Pitroub26dc462010-05-05 16:27:30 +0000488 if (!PyArg_ParseTuple(args, "w*", &pbuf))
489 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000490
Antoine Pitroub26dc462010-05-05 16:27:30 +0000491 if (_PyVerify_fd(self->fd)) {
Victor Stinner59729ff2011-07-05 11:28:19 +0200492 len = pbuf.len;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000493 Py_BEGIN_ALLOW_THREADS
494 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200495#if defined(MS_WIN64) || defined(MS_WINDOWS)
496 if (len > INT_MAX)
497 len = INT_MAX;
498 n = read(self->fd, pbuf.buf, (int)len);
499#else
500 n = read(self->fd, pbuf.buf, len);
501#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000502 Py_END_ALLOW_THREADS
503 } else
504 n = -1;
505 PyBuffer_Release(&pbuf);
506 if (n < 0) {
507 if (errno == EAGAIN)
508 Py_RETURN_NONE;
509 PyErr_SetFromErrno(PyExc_IOError);
510 return NULL;
511 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000512
Antoine Pitroub26dc462010-05-05 16:27:30 +0000513 return PyLong_FromSsize_t(n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000514}
515
Antoine Pitrou19690592009-06-12 20:14:08 +0000516static size_t
517new_buffersize(fileio *self, size_t currentsize)
518{
519#ifdef HAVE_FSTAT
Antoine Pitroub26dc462010-05-05 16:27:30 +0000520 off_t pos, end;
521 struct stat st;
522 if (fstat(self->fd, &st) == 0) {
523 end = st.st_size;
524 pos = lseek(self->fd, 0L, SEEK_CUR);
525 /* Files claiming a size smaller than SMALLCHUNK may
526 actually be streaming pseudo-files. In this case, we
527 apply the more aggressive algorithm below.
528 */
529 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
530 /* Add 1 so if the file were to grow we'd notice. */
531 return currentsize + end - pos + 1;
532 }
533 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000534#endif
Nadeem Vawda36248152011-10-13 13:52:46 +0200535 /* Expand the buffer by an amount proportional to the current size,
536 giving us amortized linear-time behavior. Use a less-than-double
537 growth factor to avoid excessive allocation. */
538 return currentsize + (currentsize >> 3) + 6;
Antoine Pitrou19690592009-06-12 20:14:08 +0000539}
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000540
541static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000542fileio_readall(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000543{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000544 PyObject *result;
545 Py_ssize_t total = 0;
Victor Stinner23a32ba2013-01-03 03:33:21 +0100546 Py_ssize_t n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000547
Victor Stinner5100a402011-05-25 22:15:36 +0200548 if (self->fd < 0)
549 return err_closed();
Antoine Pitroub26dc462010-05-05 16:27:30 +0000550 if (!_PyVerify_fd(self->fd))
551 return PyErr_SetFromErrno(PyExc_IOError);
Antoine Pitrou19690592009-06-12 20:14:08 +0000552
Antoine Pitroub26dc462010-05-05 16:27:30 +0000553 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
554 if (result == NULL)
555 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000556
Antoine Pitroub26dc462010-05-05 16:27:30 +0000557 while (1) {
558 size_t newsize = new_buffersize(self, total);
559 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
560 PyErr_SetString(PyExc_OverflowError,
561 "unbounded read returned more bytes "
562 "than a Python string can hold ");
563 Py_DECREF(result);
564 return NULL;
565 }
Antoine Pitrou19690592009-06-12 20:14:08 +0000566
Antoine Pitroub26dc462010-05-05 16:27:30 +0000567 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
Kristján Valur Jónssonbe580f22014-04-25 09:51:21 +0000568 if (_PyBytes_Resize(&result, newsize) < 0)
569 return NULL; /* result has been freed */
Antoine Pitroub26dc462010-05-05 16:27:30 +0000570 }
571 Py_BEGIN_ALLOW_THREADS
572 errno = 0;
Victor Stinner23a32ba2013-01-03 03:33:21 +0100573 n = newsize - total;
574#if defined(MS_WIN64) || defined(MS_WINDOWS)
575 if (n > INT_MAX)
576 n = INT_MAX;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000577 n = read(self->fd,
578 PyBytes_AS_STRING(result) + total,
Victor Stinner23a32ba2013-01-03 03:33:21 +0100579 (int)n);
580#else
581 n = read(self->fd,
582 PyBytes_AS_STRING(result) + total,
583 n);
584#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000585 Py_END_ALLOW_THREADS
586 if (n == 0)
587 break;
588 if (n < 0) {
Gregory P. Smith99716162012-10-12 13:02:06 -0700589 if (errno == EINTR) {
590 if (PyErr_CheckSignals()) {
591 Py_DECREF(result);
592 return NULL;
593 }
594 continue;
595 }
Antoine Pitroub26dc462010-05-05 16:27:30 +0000596 if (errno == EAGAIN) {
Victor Stinnerf6b3c842014-07-02 23:12:48 +0200597 if (total > 0)
598 break;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000599 Py_DECREF(result);
600 Py_RETURN_NONE;
601 }
602 Py_DECREF(result);
603 PyErr_SetFromErrno(PyExc_IOError);
604 return NULL;
605 }
606 total += n;
607 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000608
Antoine Pitroub26dc462010-05-05 16:27:30 +0000609 if (PyBytes_GET_SIZE(result) > total) {
610 if (_PyBytes_Resize(&result, total) < 0) {
611 /* This should never happen, but just in case */
Antoine Pitroub26dc462010-05-05 16:27:30 +0000612 return NULL;
613 }
614 }
615 return result;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000616}
617
618static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000619fileio_read(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000620{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000621 char *ptr;
622 Py_ssize_t n;
623 Py_ssize_t size = -1;
624 PyObject *bytes;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000625
Antoine Pitroub26dc462010-05-05 16:27:30 +0000626 if (self->fd < 0)
627 return err_closed();
628 if (!self->readable)
629 return err_mode("reading");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000630
Antoine Pitroub26dc462010-05-05 16:27:30 +0000631 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
632 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000633
Antoine Pitroub26dc462010-05-05 16:27:30 +0000634 if (size < 0) {
635 return fileio_readall(self);
636 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000637
Victor Stinner59729ff2011-07-05 11:28:19 +0200638#if defined(MS_WIN64) || defined(MS_WINDOWS)
639 if (size > INT_MAX)
640 size = INT_MAX;
641#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000642 bytes = PyBytes_FromStringAndSize(NULL, size);
643 if (bytes == NULL)
644 return NULL;
645 ptr = PyBytes_AS_STRING(bytes);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000646
Antoine Pitroub26dc462010-05-05 16:27:30 +0000647 if (_PyVerify_fd(self->fd)) {
648 Py_BEGIN_ALLOW_THREADS
649 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200650#if defined(MS_WIN64) || defined(MS_WINDOWS)
651 n = read(self->fd, ptr, (int)size);
652#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000653 n = read(self->fd, ptr, size);
Victor Stinner59729ff2011-07-05 11:28:19 +0200654#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000655 Py_END_ALLOW_THREADS
656 } else
657 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000658
Antoine Pitroub26dc462010-05-05 16:27:30 +0000659 if (n < 0) {
660 Py_DECREF(bytes);
661 if (errno == EAGAIN)
662 Py_RETURN_NONE;
663 PyErr_SetFromErrno(PyExc_IOError);
664 return NULL;
665 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000666
Antoine Pitroub26dc462010-05-05 16:27:30 +0000667 if (n != size) {
Kristján Valur Jónssonbe580f22014-04-25 09:51:21 +0000668 if (_PyBytes_Resize(&bytes, n) < 0)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000669 return NULL;
Antoine Pitroub26dc462010-05-05 16:27:30 +0000670 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000671
Antoine Pitroub26dc462010-05-05 16:27:30 +0000672 return (PyObject *) bytes;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000673}
674
675static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000676fileio_write(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000677{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000678 Py_buffer pbuf;
Victor Stinner59729ff2011-07-05 11:28:19 +0200679 Py_ssize_t n, len;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000680
Antoine Pitroub26dc462010-05-05 16:27:30 +0000681 if (self->fd < 0)
682 return err_closed();
683 if (!self->writable)
684 return err_mode("writing");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000685
Antoine Pitroub26dc462010-05-05 16:27:30 +0000686 if (!PyArg_ParseTuple(args, "s*", &pbuf))
687 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000688
Antoine Pitroub26dc462010-05-05 16:27:30 +0000689 if (_PyVerify_fd(self->fd)) {
690 Py_BEGIN_ALLOW_THREADS
691 errno = 0;
Victor Stinner59729ff2011-07-05 11:28:19 +0200692 len = pbuf.len;
693#if defined(MS_WIN64) || defined(MS_WINDOWS)
694 if (len > INT_MAX)
695 len = INT_MAX;
696 n = write(self->fd, pbuf.buf, (int)len);
697#else
698 n = write(self->fd, pbuf.buf, len);
699#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000700 Py_END_ALLOW_THREADS
701 } else
702 n = -1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000703
Antoine Pitroub26dc462010-05-05 16:27:30 +0000704 PyBuffer_Release(&pbuf);
Martin v. Löwisf91d46a2008-08-12 14:49:50 +0000705
Antoine Pitroub26dc462010-05-05 16:27:30 +0000706 if (n < 0) {
707 if (errno == EAGAIN)
708 Py_RETURN_NONE;
709 PyErr_SetFromErrno(PyExc_IOError);
710 return NULL;
711 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000712
Antoine Pitroub26dc462010-05-05 16:27:30 +0000713 return PyLong_FromSsize_t(n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000714}
715
716/* XXX Windows support below is likely incomplete */
717
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000718/* Cribbed from posix_lseek() */
719static PyObject *
720portable_lseek(int fd, PyObject *posobj, int whence)
721{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000722 Py_off_t pos, res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000723
724#ifdef SEEK_SET
Antoine Pitroub26dc462010-05-05 16:27:30 +0000725 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
726 switch (whence) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000727#if SEEK_SET != 0
Antoine Pitroub26dc462010-05-05 16:27:30 +0000728 case 0: whence = SEEK_SET; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000729#endif
730#if SEEK_CUR != 1
Antoine Pitroub26dc462010-05-05 16:27:30 +0000731 case 1: whence = SEEK_CUR; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000732#endif
Benjamin Peterson8024cec2009-01-20 14:31:08 +0000733#if SEEK_END != 2
Antoine Pitroub26dc462010-05-05 16:27:30 +0000734 case 2: whence = SEEK_END; break;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000735#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000736 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000737#endif /* SEEK_SET */
738
Antoine Pitroub26dc462010-05-05 16:27:30 +0000739 if (posobj == NULL)
740 pos = 0;
741 else {
742 if(PyFloat_Check(posobj)) {
743 PyErr_SetString(PyExc_TypeError, "an integer is required");
744 return NULL;
745 }
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000746#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000747 pos = PyLong_AsLongLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000748#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000749 pos = PyLong_AsLong(posobj);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000750#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000751 if (PyErr_Occurred())
752 return NULL;
753 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000754
Antoine Pitroub26dc462010-05-05 16:27:30 +0000755 if (_PyVerify_fd(fd)) {
756 Py_BEGIN_ALLOW_THREADS
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000757#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000758 res = _lseeki64(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000759#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000760 res = lseek(fd, pos, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000761#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000762 Py_END_ALLOW_THREADS
763 } else
764 res = -1;
765 if (res < 0)
766 return PyErr_SetFromErrno(PyExc_IOError);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000767
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000768#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000769 return PyLong_FromLongLong(res);
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +0000770#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000771 return PyLong_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000772#endif
773}
774
775static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000776fileio_seek(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000777{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000778 PyObject *posobj;
779 int whence = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000780
Antoine Pitroub26dc462010-05-05 16:27:30 +0000781 if (self->fd < 0)
782 return err_closed();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000783
Antoine Pitroub26dc462010-05-05 16:27:30 +0000784 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
785 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000786
Antoine Pitroub26dc462010-05-05 16:27:30 +0000787 return portable_lseek(self->fd, posobj, whence);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000788}
789
790static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000791fileio_tell(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000792{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000793 if (self->fd < 0)
794 return err_closed();
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000795
Antoine Pitroub26dc462010-05-05 16:27:30 +0000796 return portable_lseek(self->fd, NULL, 1);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000797}
798
799#ifdef HAVE_FTRUNCATE
800static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000801fileio_truncate(fileio *self, PyObject *args)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000802{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000803 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000804#ifndef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000805 Py_off_t pos;
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000806#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000807 int ret;
808 int fd;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000809
Antoine Pitroub26dc462010-05-05 16:27:30 +0000810 fd = self->fd;
811 if (fd < 0)
812 return err_closed();
813 if (!self->writable)
814 return err_mode("writing");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000815
Antoine Pitroub26dc462010-05-05 16:27:30 +0000816 if (!PyArg_ParseTuple(args, "|O", &posobj))
817 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000818
Antoine Pitroub26dc462010-05-05 16:27:30 +0000819 if (posobj == Py_None || posobj == NULL) {
820 /* Get the current position. */
821 posobj = portable_lseek(fd, NULL, 1);
822 if (posobj == NULL)
823 return NULL;
824 }
825 else {
826 Py_INCREF(posobj);
827 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000828
829#ifdef MS_WINDOWS
Antoine Pitroub26dc462010-05-05 16:27:30 +0000830 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
831 so don't even try using it. */
832 {
833 PyObject *oldposobj, *tempposobj;
834 HANDLE hFile;
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000835
Antoine Pitroub26dc462010-05-05 16:27:30 +0000836 /* we save the file pointer position */
837 oldposobj = portable_lseek(fd, NULL, 1);
838 if (oldposobj == NULL) {
839 Py_DECREF(posobj);
840 return NULL;
841 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000842
Antoine Pitroub26dc462010-05-05 16:27:30 +0000843 /* we then move to the truncation position */
844 tempposobj = portable_lseek(fd, posobj, 0);
845 if (tempposobj == NULL) {
846 Py_DECREF(oldposobj);
847 Py_DECREF(posobj);
848 return NULL;
849 }
850 Py_DECREF(tempposobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000851
Antoine Pitroub26dc462010-05-05 16:27:30 +0000852 /* Truncate. Note that this may grow the file! */
853 Py_BEGIN_ALLOW_THREADS
854 errno = 0;
855 hFile = (HANDLE)_get_osfhandle(fd);
856 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
857 if (ret == 0) {
858 ret = SetEndOfFile(hFile) == 0;
859 if (ret)
860 errno = EACCES;
861 }
862 Py_END_ALLOW_THREADS
863
864 /* we restore the file pointer position in any case */
865 tempposobj = portable_lseek(fd, oldposobj, 0);
866 Py_DECREF(oldposobj);
867 if (tempposobj == NULL) {
868 Py_DECREF(posobj);
869 return NULL;
870 }
871 Py_DECREF(tempposobj);
872 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000873#else
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000874
875#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitroub26dc462010-05-05 16:27:30 +0000876 pos = PyLong_AsLongLong(posobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000877#else
Antoine Pitroub26dc462010-05-05 16:27:30 +0000878 pos = PyLong_AsLong(posobj);
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000879#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +0000880 if (PyErr_Occurred()){
881 Py_DECREF(posobj);
882 return NULL;
883 }
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000884
Antoine Pitroub26dc462010-05-05 16:27:30 +0000885 Py_BEGIN_ALLOW_THREADS
886 errno = 0;
887 ret = ftruncate(fd, pos);
888 Py_END_ALLOW_THREADS
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000889
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000890#endif /* !MS_WINDOWS */
891
Antoine Pitroub26dc462010-05-05 16:27:30 +0000892 if (ret != 0) {
893 Py_DECREF(posobj);
894 PyErr_SetFromErrno(PyExc_IOError);
895 return NULL;
896 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000897
Antoine Pitroub26dc462010-05-05 16:27:30 +0000898 return posobj;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000899}
Antoine Pitrouf3fa0742010-01-31 22:26:04 +0000900#endif /* HAVE_FTRUNCATE */
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000901
902static char *
Antoine Pitrou19690592009-06-12 20:14:08 +0000903mode_string(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000904{
Antoine Pitrou213fec42013-09-04 20:46:33 +0200905 if (self->appending) {
906 if (self->readable)
907 return "ab+";
908 else
909 return "ab";
910 }
911 else if (self->readable) {
Antoine Pitroub26dc462010-05-05 16:27:30 +0000912 if (self->writable)
913 return "rb+";
914 else
915 return "rb";
916 }
917 else
918 return "wb";
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000919}
920
921static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000922fileio_repr(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000923{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000924 PyObject *nameobj, *res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000925
Antoine Pitroub26dc462010-05-05 16:27:30 +0000926 if (self->fd < 0)
927 return PyString_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou19690592009-06-12 20:14:08 +0000928
Antoine Pitroub26dc462010-05-05 16:27:30 +0000929 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
930 if (nameobj == NULL) {
931 if (PyErr_ExceptionMatches(PyExc_AttributeError))
932 PyErr_Clear();
933 else
934 return NULL;
935 res = PyString_FromFormat("<_io.FileIO fd=%d mode='%s'>",
936 self->fd, mode_string(self));
937 }
938 else {
939 PyObject *repr = PyObject_Repr(nameobj);
940 Py_DECREF(nameobj);
941 if (repr == NULL)
942 return NULL;
943 res = PyString_FromFormat("<_io.FileIO name=%s mode='%s'>",
944 PyString_AS_STRING(repr),
945 mode_string(self));
946 Py_DECREF(repr);
947 }
948 return res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000949}
950
951static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +0000952fileio_isatty(fileio *self)
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000953{
Antoine Pitroub26dc462010-05-05 16:27:30 +0000954 long res;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000955
Antoine Pitroub26dc462010-05-05 16:27:30 +0000956 if (self->fd < 0)
957 return err_closed();
958 Py_BEGIN_ALLOW_THREADS
959 res = isatty(self->fd);
960 Py_END_ALLOW_THREADS
961 return PyBool_FromLong(res);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000962}
963
964
965PyDoc_STRVAR(fileio_doc,
966"file(name: str[, mode: str]) -> file IO object\n"
967"\n"
Serhiy Storchaka46129542015-04-10 16:08:33 +0300968"Open a file. The mode can be 'r' (default), 'w' or 'a' for reading,\n"
Antoine Pitroub26dc462010-05-05 16:27:30 +0000969"writing or appending. The file will be created if it doesn't exist\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000970"when opened for writing or appending; it will be truncated when\n"
971"opened for writing. Add a '+' to the mode to allow simultaneous\n"
972"reading and writing.");
973
974PyDoc_STRVAR(read_doc,
975"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
976"\n"
977"Only makes one system call, so less data may be returned than requested\n"
978"In non-blocking mode, returns None if no data is available.\n"
979"On end-of-file, returns ''.");
980
981PyDoc_STRVAR(readall_doc,
982"readall() -> bytes. read all data from the file, returned as bytes.\n"
983"\n"
984"In non-blocking mode, returns as much as is immediately available,\n"
985"or None if no data is available. On end-of-file, returns ''.");
986
987PyDoc_STRVAR(write_doc,
Martin Panterc9813d82016-06-03 05:59:20 +0000988"write(b) -> int. Write array of bytes b, return number written.\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000989"\n"
990"Only makes one system call, so not all of the data may be written.\n"
Serhiy Storchaka46129542015-04-10 16:08:33 +0300991"The number of bytes actually written is returned. In non-blocking mode,\n"
992"returns None if the write would block."
993);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000994
995PyDoc_STRVAR(fileno_doc,
Serhiy Storchaka46129542015-04-10 16:08:33 +0300996"fileno() -> int. Return the underlying file descriptor (an integer).");
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000997
998PyDoc_STRVAR(seek_doc,
Berker Peksagb5dc3dc2014-09-24 12:54:25 +0300999"seek(offset: int[, whence: int]) -> int. Move to new file position\n"
1000"and return the file position.\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001001"\n"
1002"Argument offset is a byte count. Optional argument whence defaults to\n"
Serhiy Storchaka46129542015-04-10 16:08:33 +03001003"SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values\n"
1004"are SEEK_CUR or 1 (move relative to current position, positive or negative),\n"
1005"and SEEK_END or 2 (move relative to end of file, usually negative, although\n"
1006"many platforms allow seeking beyond the end of a file).\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001007"\n"
1008"Note that not all file objects are seekable.");
1009
1010#ifdef HAVE_FTRUNCATE
1011PyDoc_STRVAR(truncate_doc,
Berker Peksagb5dc3dc2014-09-24 12:54:25 +03001012"truncate([size: int]) -> int. Truncate the file to at most size bytes and\n"
1013"return the truncated size.\n"
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001014"\n"
Berker Peksagb5dc3dc2014-09-24 12:54:25 +03001015"Size defaults to the current file position, as returned by tell().\n"
Alexandre Vassalotti1aed6242008-05-09 21:49:43 +00001016"The current file position is changed to the value of size.");
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001017#endif
1018
1019PyDoc_STRVAR(tell_doc,
Serhiy Storchaka46129542015-04-10 16:08:33 +03001020"tell() -> int. Current file position.\n"
1021"\n"
1022"Can raise OSError for non seekable files."
1023);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001024
1025PyDoc_STRVAR(readinto_doc,
Antoine Pitrou19690592009-06-12 20:14:08 +00001026"readinto() -> Same as RawIOBase.readinto().");
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001027
1028PyDoc_STRVAR(close_doc,
1029"close() -> None. Close the file.\n"
1030"\n"
1031"A closed file cannot be used for further I/O operations. close() may be\n"
Serhiy Storchaka46129542015-04-10 16:08:33 +03001032"called more than once without error.");
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001033
1034PyDoc_STRVAR(isatty_doc,
Serhiy Storchaka46129542015-04-10 16:08:33 +03001035"isatty() -> bool. True if the file is connected to a TTY device.");
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001036
1037PyDoc_STRVAR(seekable_doc,
1038"seekable() -> bool. True if file supports random-access.");
1039
1040PyDoc_STRVAR(readable_doc,
1041"readable() -> bool. True if file was opened in a read mode.");
1042
1043PyDoc_STRVAR(writable_doc,
1044"writable() -> bool. True if file was opened in a write mode.");
1045
1046static PyMethodDef fileio_methods[] = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001047 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1048 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1049 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1050 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1051 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1052 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001053#ifdef HAVE_FTRUNCATE
Antoine Pitroub26dc462010-05-05 16:27:30 +00001054 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001055#endif
Antoine Pitroub26dc462010-05-05 16:27:30 +00001056 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1057 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1058 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1059 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1060 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1061 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
1062 {NULL, NULL} /* sentinel */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001063};
1064
1065/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1066
1067static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001068get_closed(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001069{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001070 return PyBool_FromLong((long)(self->fd < 0));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001071}
1072
1073static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001074get_closefd(fileio *self, void *closure)
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001075{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001076 return PyBool_FromLong((long)(self->closefd));
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +00001077}
1078
1079static PyObject *
Antoine Pitrou19690592009-06-12 20:14:08 +00001080get_mode(fileio *self, void *closure)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001081{
Antoine Pitroub26dc462010-05-05 16:27:30 +00001082 return PyUnicode_FromString(mode_string(self));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001083}
1084
1085static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001086 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1087 {"closefd", (getter)get_closefd, NULL,
Serhiy Storchaka46129542015-04-10 16:08:33 +03001088 "True if the file descriptor will be closed by close()."},
Antoine Pitroub26dc462010-05-05 16:27:30 +00001089 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1090 {NULL},
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001091};
1092
1093PyTypeObject PyFileIO_Type = {
Antoine Pitroub26dc462010-05-05 16:27:30 +00001094 PyVarObject_HEAD_INIT(NULL, 0)
1095 "_io.FileIO",
1096 sizeof(fileio),
1097 0,
1098 (destructor)fileio_dealloc, /* tp_dealloc */
1099 0, /* tp_print */
1100 0, /* tp_getattr */
1101 0, /* tp_setattr */
1102 0, /* tp_reserved */
1103 (reprfunc)fileio_repr, /* tp_repr */
1104 0, /* tp_as_number */
1105 0, /* tp_as_sequence */
1106 0, /* tp_as_mapping */
1107 0, /* tp_hash */
1108 0, /* tp_call */
1109 0, /* tp_str */
1110 PyObject_GenericGetAttr, /* tp_getattro */
1111 0, /* tp_setattro */
1112 0, /* tp_as_buffer */
1113 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1114 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1115 fileio_doc, /* tp_doc */
1116 (traverseproc)fileio_traverse, /* tp_traverse */
1117 (inquiry)fileio_clear, /* tp_clear */
1118 0, /* tp_richcompare */
1119 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1120 0, /* tp_iter */
1121 0, /* tp_iternext */
1122 fileio_methods, /* tp_methods */
1123 0, /* tp_members */
1124 fileio_getsetlist, /* tp_getset */
1125 0, /* tp_base */
1126 0, /* tp_dict */
1127 0, /* tp_descr_get */
1128 0, /* tp_descr_set */
1129 offsetof(fileio, dict), /* tp_dictoffset */
1130 fileio_init, /* tp_init */
1131 PyType_GenericAlloc, /* tp_alloc */
1132 fileio_new, /* tp_new */
1133 PyObject_GC_Del, /* tp_free */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001134};