blob: a365c9fe46c2c196c9f10b6110e93bf08c7fe743 [file] [log] [blame]
Guido van Rossuma9e20242007-03-08 00:43:48 +00001/* Author: Daniel Stutzbach */
2
3#define PY_SSIZE_T_CLEAN
4#include "Python.h"
5#include <sys/types.h>
6#include <sys/stat.h>
7#include <fcntl.h>
8#include <stddef.h> /* For offsetof */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00009#include "_iomodule.h"
Guido van Rossuma9e20242007-03-08 00:43:48 +000010
11/*
12 * Known likely problems:
13 *
14 * - Files larger then 2**32-1
15 * - Files with unicode filenames
16 * - Passing numbers greater than 2**32-1 when an integer is expected
17 * - Making it work on Windows and other oddball platforms
18 *
19 * To Do:
20 *
21 * - autoconfify header file inclusion
Guido van Rossuma9e20242007-03-08 00:43:48 +000022 */
23
24#ifdef MS_WINDOWS
25/* can simulate truncate with Win32 API functions; see file_truncate */
Thomas Hellerfdeee3a2007-07-12 11:21:36 +000026#define HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +000027#define WIN32_LEAN_AND_MEAN
28#include <windows.h>
29#endif
30
Christian Heimesa872de52008-12-05 08:26:55 +000031#if BUFSIZ < (8*1024)
32#define SMALLCHUNK (8*1024)
33#elif (BUFSIZ >= (2 << 25))
34#error "unreasonable BUFSIZ > 64MB defined"
35#else
36#define SMALLCHUNK BUFSIZ
37#endif
38
39#if SIZEOF_INT < 4
40#define BIGCHUNK (512 * 32)
41#else
42#define BIGCHUNK (512 * 1024)
43#endif
44
Guido van Rossuma9e20242007-03-08 00:43:48 +000045typedef struct {
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +000046 PyObject_HEAD
47 int fd;
48 unsigned int readable : 1;
49 unsigned int writable : 1;
50 signed int seekable : 2; /* -1 means unknown */
51 unsigned int closefd : 1;
52 PyObject *weakreflist;
53 PyObject *dict;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000054} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000055
Collin Winteraf334382007-03-08 21:46:15 +000056PyTypeObject PyFileIO_Type;
57
Guido van Rossuma9e20242007-03-08 00:43:48 +000058#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
59
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000060int
61_PyFileIO_closed(PyObject *self)
62{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +000063 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000064}
Antoine Pitrou08838b62009-01-21 00:55:13 +000065
Antoine Pitrou7fb111b2009-03-04 11:14:01 +000066static PyObject *
67portable_lseek(int fd, PyObject *posobj, int whence);
68
Antoine Pitroua28fcfd2009-03-13 23:42:55 +000069static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
70
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +000071/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +000072static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000073internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +000074{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +000075 int err = 0;
76 int save_errno = 0;
77 if (self->fd >= 0) {
78 int fd = self->fd;
79 self->fd = -1;
80 /* fd is accessible and someone else may have closed it */
81 if (_PyVerify_fd(fd)) {
82 Py_BEGIN_ALLOW_THREADS
83 err = close(fd);
84 if (err < 0)
85 save_errno = errno;
86 Py_END_ALLOW_THREADS
87 } else {
88 save_errno = errno;
89 err = -1;
90 }
91 }
92 if (err < 0) {
93 errno = save_errno;
94 PyErr_SetFromErrno(PyExc_IOError);
95 return -1;
96 }
97 return 0;
Neal Norwitz88b44da2007-08-12 17:23:54 +000098}
99
100static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000101fileio_close(fileio *self)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000102{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000103 if (!self->closefd) {
104 self->fd = -1;
105 Py_RETURN_NONE;
106 }
107 errno = internal_close(self);
108 if (errno < 0)
109 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000110
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000111 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
112 "close", "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000113}
114
115static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000116fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000117{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000118 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000119
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000120 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000121
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000122 self = (fileio *) type->tp_alloc(type, 0);
123 if (self != NULL) {
124 self->fd = -1;
125 self->readable = 0;
126 self->writable = 0;
127 self->seekable = -1;
128 self->closefd = 1;
129 self->weakreflist = NULL;
130 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000131
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000132 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000133}
134
135/* On Unix, open will succeed for directories.
136 In Python, there should be no file objects referring to
137 directories, so we need a check. */
138
139static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000140dircheck(fileio* self, const char *name)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000141{
142#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000143 struct stat buf;
144 if (self->fd < 0)
145 return 0;
146 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
147 char *msg = strerror(EISDIR);
148 PyObject *exc;
149 if (internal_close(self))
150 return -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000151
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000152 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
153 EISDIR, msg, name);
154 PyErr_SetObject(PyExc_IOError, exc);
155 Py_XDECREF(exc);
156 return -1;
157 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000158#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000159 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000160}
161
Benjamin Peterson806d4022009-01-19 15:11:51 +0000162static int
163check_fd(int fd)
164{
165#if defined(HAVE_FSTAT)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000166 struct stat buf;
167 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
168 PyObject *exc;
169 char *msg = strerror(EBADF);
170 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
171 EBADF, msg);
172 PyErr_SetObject(PyExc_OSError, exc);
173 Py_XDECREF(exc);
174 return -1;
175 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000176#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000177 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000178}
179
Guido van Rossuma9e20242007-03-08 00:43:48 +0000180
181static int
182fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
183{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000184 fileio *self = (fileio *) oself;
185 static char *kwlist[] = {"file", "mode", "closefd", NULL};
186 const char *name = NULL;
187 PyObject *nameobj, *stringobj = NULL;
188 char *mode = "r";
189 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000190#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000191 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000192#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000193 int ret = 0;
194 int rwa = 0, plus = 0, append = 0;
195 int flags = 0;
196 int fd = -1;
197 int closefd = 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000198
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000199 assert(PyFileIO_Check(oself));
200 if (self->fd >= 0) {
201 /* Have to close the existing file first. */
202 if (internal_close(self) < 0)
203 return -1;
204 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000205
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000206 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
207 kwlist, &nameobj, &mode, &closefd))
208 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000209
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000210 if (PyFloat_Check(nameobj)) {
211 PyErr_SetString(PyExc_TypeError,
212 "integer argument expected, got float");
213 return -1;
214 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000215
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000216 fd = PyLong_AsLong(nameobj);
217 if (fd < 0) {
218 if (!PyErr_Occurred()) {
219 PyErr_SetString(PyExc_ValueError,
220 "Negative filedescriptor");
221 return -1;
222 }
223 PyErr_Clear();
224 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000225
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000226#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000227 if (GetVersion() < 0x80000000) {
228 /* On NT, so wide API available */
229 if (PyUnicode_Check(nameobj))
230 widename = PyUnicode_AS_UNICODE(nameobj);
231 }
232 if (widename == NULL)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000233#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000234 if (fd < 0)
235 {
236 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
237 Py_ssize_t namelen;
238 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
239 return -1;
240 }
241 else {
242 PyObject *u = PyUnicode_FromObject(nameobj);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000243
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000244 if (u == NULL)
245 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000246
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000247 stringobj = PyUnicode_AsEncodedString(
248 u, Py_FileSystemDefaultEncoding, "surrogateescape");
249 Py_DECREF(u);
250 if (stringobj == NULL)
251 return -1;
252 if (!PyBytes_Check(stringobj)) {
253 PyErr_SetString(PyExc_TypeError,
254 "encoder failed to return bytes");
255 goto error;
256 }
257 name = PyBytes_AS_STRING(stringobj);
258 }
259 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000260
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000261 s = mode;
262 while (*s) {
263 switch (*s++) {
264 case 'r':
265 if (rwa) {
266 bad_mode:
267 PyErr_SetString(PyExc_ValueError,
268 "Must have exactly one of read/write/append mode");
269 goto error;
270 }
271 rwa = 1;
272 self->readable = 1;
273 break;
274 case 'w':
275 if (rwa)
276 goto bad_mode;
277 rwa = 1;
278 self->writable = 1;
279 flags |= O_CREAT | O_TRUNC;
280 break;
281 case 'a':
282 if (rwa)
283 goto bad_mode;
284 rwa = 1;
285 self->writable = 1;
286 flags |= O_CREAT;
287 append = 1;
288 break;
289 case 'b':
290 break;
291 case '+':
292 if (plus)
293 goto bad_mode;
294 self->readable = self->writable = 1;
295 plus = 1;
296 break;
297 default:
298 PyErr_Format(PyExc_ValueError,
299 "invalid mode: %.200s", mode);
300 goto error;
301 }
302 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000303
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000304 if (!rwa)
305 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000306
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000307 if (self->readable && self->writable)
308 flags |= O_RDWR;
309 else if (self->readable)
310 flags |= O_RDONLY;
311 else
312 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000313
314#ifdef O_BINARY
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000315 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000316#endif
317
Walter Dörwald0e411482007-06-06 16:55:38 +0000318#ifdef O_APPEND
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000319 if (append)
320 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000321#endif
322
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000323 if (fd >= 0) {
324 if (check_fd(fd))
325 goto error;
326 self->fd = fd;
327 self->closefd = closefd;
328 }
329 else {
330 self->closefd = 1;
331 if (!closefd) {
332 PyErr_SetString(PyExc_ValueError,
333 "Cannot use closefd=False with file name");
334 goto error;
335 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000336
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000337 Py_BEGIN_ALLOW_THREADS
338 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000339#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000340 if (widename != NULL)
341 self->fd = _wopen(widename, flags, 0666);
342 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000343#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000344 self->fd = open(name, flags, 0666);
345 Py_END_ALLOW_THREADS
346 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000347#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000348 if (widename != NULL)
349 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
350 else
Christian Heimes0b489542007-10-31 19:20:48 +0000351#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000352 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
353 goto error;
354 }
355 if(dircheck(self, name) < 0)
356 goto error;
357 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000358
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000359 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
360 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000361
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000362 if (append) {
363 /* For consistent behaviour, we explicitly seek to the
364 end of file (otherwise, it might be done only on the
365 first write()). */
366 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou735e3b12010-10-31 13:05:21 +0000367 if (pos == NULL) {
368 if (closefd) {
369 close(self->fd);
370 self->fd = -1;
371 }
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000372 goto error;
Antoine Pitrou735e3b12010-10-31 13:05:21 +0000373 }
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000374 Py_DECREF(pos);
375 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000376
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000377 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000378
379 error:
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000380 ret = -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000381
Guido van Rossuma9e20242007-03-08 00:43:48 +0000382 done:
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000383 Py_CLEAR(stringobj);
384 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000385}
386
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000387static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000388fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000389{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000390 Py_VISIT(self->dict);
391 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000392}
393
394static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000395fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000396{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000397 Py_CLEAR(self->dict);
398 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000399}
400
Guido van Rossuma9e20242007-03-08 00:43:48 +0000401static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000402fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000403{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000404 if (_PyIOBase_finalize((PyObject *) self) < 0)
405 return;
406 _PyObject_GC_UNTRACK(self);
407 if (self->weakreflist != NULL)
408 PyObject_ClearWeakRefs((PyObject *) self);
409 Py_CLEAR(self->dict);
410 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000411}
412
413static PyObject *
414err_closed(void)
415{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000416 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
417 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000418}
419
420static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000421err_mode(char *action)
422{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000423 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
424 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000425}
426
427static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000428fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000429{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000430 if (self->fd < 0)
431 return err_closed();
432 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000433}
434
435static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000436fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000437{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000438 if (self->fd < 0)
439 return err_closed();
440 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000441}
442
443static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000444fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000445{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000446 if (self->fd < 0)
447 return err_closed();
448 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000449}
450
451static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000452fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000453{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000454 if (self->fd < 0)
455 return err_closed();
456 if (self->seekable < 0) {
457 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
458 if (pos == NULL) {
459 PyErr_Clear();
460 self->seekable = 0;
461 } else {
462 Py_DECREF(pos);
463 self->seekable = 1;
464 }
465 }
466 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000467}
468
469static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000470fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000471{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000472 Py_buffer pbuf;
473 Py_ssize_t n;
Guido van Rossum53807da2007-04-10 19:01:47 +0000474
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000475 if (self->fd < 0)
476 return err_closed();
477 if (!self->readable)
478 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000479
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000480 if (!PyArg_ParseTuple(args, "w*", &pbuf))
481 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000482
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000483 if (_PyVerify_fd(self->fd)) {
484 Py_BEGIN_ALLOW_THREADS
485 errno = 0;
486 n = read(self->fd, pbuf.buf, pbuf.len);
487 Py_END_ALLOW_THREADS
488 } else
489 n = -1;
490 PyBuffer_Release(&pbuf);
491 if (n < 0) {
492 if (errno == EAGAIN)
493 Py_RETURN_NONE;
494 PyErr_SetFromErrno(PyExc_IOError);
495 return NULL;
496 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000497
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000498 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000499}
500
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000501static size_t
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000502new_buffersize(fileio *self, size_t currentsize)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000503{
504#ifdef HAVE_FSTAT
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000505 off_t pos, end;
506 struct stat st;
507 if (fstat(self->fd, &st) == 0) {
508 end = st.st_size;
509 pos = lseek(self->fd, 0L, SEEK_CUR);
510 /* Files claiming a size smaller than SMALLCHUNK may
511 actually be streaming pseudo-files. In this case, we
512 apply the more aggressive algorithm below.
513 */
514 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
515 /* Add 1 so if the file were to grow we'd notice. */
516 return currentsize + end - pos + 1;
517 }
518 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000519#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000520 if (currentsize > SMALLCHUNK) {
521 /* Keep doubling until we reach BIGCHUNK;
522 then keep adding BIGCHUNK. */
523 if (currentsize <= BIGCHUNK)
524 return currentsize + currentsize;
525 else
526 return currentsize + BIGCHUNK;
527 }
528 return currentsize + SMALLCHUNK;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000529}
530
Guido van Rossum7165cb12007-07-10 06:54:34 +0000531static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000532fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000533{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000534 PyObject *result;
535 Py_ssize_t total = 0;
536 int n;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000537
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000538 if (!_PyVerify_fd(self->fd))
539 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000540
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000541 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
542 if (result == NULL)
543 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000544
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000545 while (1) {
546 size_t newsize = new_buffersize(self, total);
547 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
548 PyErr_SetString(PyExc_OverflowError,
549 "unbounded read returned more bytes "
550 "than a Python string can hold ");
551 Py_DECREF(result);
552 return NULL;
553 }
Christian Heimesa872de52008-12-05 08:26:55 +0000554
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000555 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
556 if (_PyBytes_Resize(&result, newsize) < 0) {
557 if (total == 0) {
558 Py_DECREF(result);
559 return NULL;
560 }
561 PyErr_Clear();
562 break;
563 }
564 }
565 Py_BEGIN_ALLOW_THREADS
566 errno = 0;
567 n = read(self->fd,
568 PyBytes_AS_STRING(result) + total,
569 newsize - total);
570 Py_END_ALLOW_THREADS
571 if (n == 0)
572 break;
573 if (n < 0) {
574 if (total > 0)
575 break;
576 if (errno == EAGAIN) {
577 Py_DECREF(result);
578 Py_RETURN_NONE;
579 }
580 Py_DECREF(result);
581 PyErr_SetFromErrno(PyExc_IOError);
582 return NULL;
583 }
584 total += n;
585 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000586
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000587 if (PyBytes_GET_SIZE(result) > total) {
588 if (_PyBytes_Resize(&result, total) < 0) {
589 /* This should never happen, but just in case */
590 Py_DECREF(result);
591 return NULL;
592 }
593 }
594 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000595}
596
Guido van Rossuma9e20242007-03-08 00:43:48 +0000597static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000598fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000599{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000600 char *ptr;
601 Py_ssize_t n;
602 Py_ssize_t size = -1;
603 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000604
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000605 if (self->fd < 0)
606 return err_closed();
607 if (!self->readable)
608 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000609
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000610 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
611 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000612
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000613 if (size < 0) {
614 return fileio_readall(self);
615 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000616
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000617 bytes = PyBytes_FromStringAndSize(NULL, size);
618 if (bytes == NULL)
619 return NULL;
620 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000621
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000622 if (_PyVerify_fd(self->fd)) {
623 Py_BEGIN_ALLOW_THREADS
624 errno = 0;
625 n = read(self->fd, ptr, size);
626 Py_END_ALLOW_THREADS
627 } else
628 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000629
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000630 if (n < 0) {
631 Py_DECREF(bytes);
632 if (errno == EAGAIN)
633 Py_RETURN_NONE;
634 PyErr_SetFromErrno(PyExc_IOError);
635 return NULL;
636 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000637
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000638 if (n != size) {
639 if (_PyBytes_Resize(&bytes, n) < 0) {
640 Py_DECREF(bytes);
641 return NULL;
642 }
643 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000644
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000645 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000646}
647
648static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000649fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000650{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000651 Py_buffer pbuf;
652 Py_ssize_t n;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000653
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000654 if (self->fd < 0)
655 return err_closed();
656 if (!self->writable)
657 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000658
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000659 if (!PyArg_ParseTuple(args, "y*", &pbuf))
660 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000661
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000662 if (_PyVerify_fd(self->fd)) {
663 Py_BEGIN_ALLOW_THREADS
664 errno = 0;
665 n = write(self->fd, pbuf.buf, pbuf.len);
666 Py_END_ALLOW_THREADS
667 } else
668 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000669
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000670 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000671
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000672 if (n < 0) {
673 if (errno == EAGAIN)
674 Py_RETURN_NONE;
675 PyErr_SetFromErrno(PyExc_IOError);
676 return NULL;
677 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000678
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000679 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000680}
681
Guido van Rossum53807da2007-04-10 19:01:47 +0000682/* XXX Windows support below is likely incomplete */
683
Guido van Rossum53807da2007-04-10 19:01:47 +0000684/* Cribbed from posix_lseek() */
685static PyObject *
686portable_lseek(int fd, PyObject *posobj, int whence)
687{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000688 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000689
690#ifdef SEEK_SET
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000691 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
692 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000693#if SEEK_SET != 0
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000694 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000695#endif
696#if SEEK_CUR != 1
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000697 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000698#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000699#if SEEK_END != 2
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000700 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000701#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000702 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000703#endif /* SEEK_SET */
704
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000705 if (posobj == NULL)
706 pos = 0;
707 else {
708 if(PyFloat_Check(posobj)) {
709 PyErr_SetString(PyExc_TypeError, "an integer is required");
710 return NULL;
711 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000712#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000713 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000714#else
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000715 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000716#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000717 if (PyErr_Occurred())
718 return NULL;
719 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000720
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000721 if (_PyVerify_fd(fd)) {
722 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000723#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000724 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000725#else
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000726 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000727#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000728 Py_END_ALLOW_THREADS
729 } else
730 res = -1;
731 if (res < 0)
732 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000733
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000734#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000735 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000736#else
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000737 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000738#endif
739}
740
Guido van Rossuma9e20242007-03-08 00:43:48 +0000741static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000742fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000743{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000744 PyObject *posobj;
745 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000746
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000747 if (self->fd < 0)
748 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000749
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000750 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
751 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000752
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000753 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000754}
755
756static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000757fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000758{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000759 if (self->fd < 0)
760 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000761
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000762 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000763}
764
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000765#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000766static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000767fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000768{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000769 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000770#ifndef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000771 Py_off_t pos;
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000772#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000773 int ret;
774 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000775
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000776 fd = self->fd;
777 if (fd < 0)
778 return err_closed();
779 if (!self->writable)
780 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000781
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000782 if (!PyArg_ParseTuple(args, "|O", &posobj))
783 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000784
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000785 if (posobj == Py_None || posobj == NULL) {
786 /* Get the current position. */
787 posobj = portable_lseek(fd, NULL, 1);
788 if (posobj == NULL)
789 return NULL;
790 }
791 else {
792 Py_INCREF(posobj);
793 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000794
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000795#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000796 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
797 so don't even try using it. */
798 {
799 PyObject *oldposobj, *tempposobj;
800 HANDLE hFile;
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000801
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000802 /* we save the file pointer position */
803 oldposobj = portable_lseek(fd, NULL, 1);
804 if (oldposobj == NULL) {
805 Py_DECREF(posobj);
806 return NULL;
807 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000808
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000809 /* we then move to the truncation position */
810 tempposobj = portable_lseek(fd, posobj, 0);
811 if (tempposobj == NULL) {
812 Py_DECREF(oldposobj);
813 Py_DECREF(posobj);
814 return NULL;
815 }
816 Py_DECREF(tempposobj);
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000817
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000818 /* Truncate. Note that this may grow the file! */
819 Py_BEGIN_ALLOW_THREADS
820 errno = 0;
821 hFile = (HANDLE)_get_osfhandle(fd);
822 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
823 if (ret == 0) {
824 ret = SetEndOfFile(hFile) == 0;
825 if (ret)
826 errno = EACCES;
827 }
828 Py_END_ALLOW_THREADS
829
830 /* we restore the file pointer position in any case */
831 tempposobj = portable_lseek(fd, oldposobj, 0);
832 Py_DECREF(oldposobj);
833 if (tempposobj == NULL) {
834 Py_DECREF(posobj);
835 return NULL;
836 }
837 Py_DECREF(tempposobj);
838 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000839#else
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000840
841#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000842 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000843#else
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000844 pos = PyLong_AsLong(posobj);
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000845#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000846 if (PyErr_Occurred()){
847 Py_DECREF(posobj);
848 return NULL;
849 }
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000850
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000851 Py_BEGIN_ALLOW_THREADS
852 errno = 0;
853 ret = ftruncate(fd, pos);
854 Py_END_ALLOW_THREADS
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000855
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000856#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000857
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000858 if (ret != 0) {
859 Py_DECREF(posobj);
860 PyErr_SetFromErrno(PyExc_IOError);
861 return NULL;
862 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000863
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000864 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000865}
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000866#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000867
868static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000869mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000870{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000871 if (self->readable) {
872 if (self->writable)
873 return "rb+";
874 else
875 return "rb";
876 }
877 else
878 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000879}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000880
881static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000882fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000883{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000884 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000885
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000886 if (self->fd < 0)
887 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000888
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000889 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
890 if (nameobj == NULL) {
891 if (PyErr_ExceptionMatches(PyExc_AttributeError))
892 PyErr_Clear();
893 else
894 return NULL;
895 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
896 self->fd, mode_string(self));
897 }
898 else {
899 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
900 nameobj, mode_string(self));
901 Py_DECREF(nameobj);
902 }
903 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000904}
905
906static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000907fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000908{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000909 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000910
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000911 if (self->fd < 0)
912 return err_closed();
913 Py_BEGIN_ALLOW_THREADS
914 res = isatty(self->fd);
915 Py_END_ALLOW_THREADS
916 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000917}
918
Guido van Rossuma9e20242007-03-08 00:43:48 +0000919
920PyDoc_STRVAR(fileio_doc,
921"file(name: str[, mode: str]) -> file IO object\n"
922"\n"
923"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000924"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +0000925"when opened for writing or appending; it will be truncated when\n"
926"opened for writing. Add a '+' to the mode to allow simultaneous\n"
927"reading and writing.");
928
929PyDoc_STRVAR(read_doc,
930"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
931"\n"
932"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +0000933"In non-blocking mode, returns None if no data is available.\n"
934"On end-of-file, returns ''.");
935
936PyDoc_STRVAR(readall_doc,
937"readall() -> bytes. read all data from the file, returned as bytes.\n"
938"\n"
939"In non-blocking mode, returns as much as is immediately available,\n"
940"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000941
942PyDoc_STRVAR(write_doc,
943"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
944"\n"
945"Only makes one system call, so not all of the data may be written.\n"
946"The number of bytes actually written is returned.");
947
948PyDoc_STRVAR(fileno_doc,
949"fileno() -> int. \"file descriptor\".\n"
950"\n"
951"This is needed for lower-level file interfaces, such the fcntl module.");
952
953PyDoc_STRVAR(seek_doc,
954"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
955"\n"
956"Argument offset is a byte count. Optional argument whence defaults to\n"
957"0 (offset from start of file, offset should be >= 0); other values are 1\n"
958"(move relative to current position, positive or negative), and 2 (move\n"
959"relative to end of file, usually negative, although many platforms allow\n"
960"seeking beyond the end of a file)."
961"\n"
962"Note that not all file objects are seekable.");
963
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000964#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000965PyDoc_STRVAR(truncate_doc,
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000966"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +0000967"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000968"Size defaults to the current file position, as returned by tell()."
969"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000970#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000971
972PyDoc_STRVAR(tell_doc,
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000973"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000974
975PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +0000976"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000977
978PyDoc_STRVAR(close_doc,
979"close() -> None. Close the file.\n"
980"\n"
981"A closed file cannot be used for further I/O operations. close() may be\n"
982"called more than once without error. Changes the fileno to -1.");
983
984PyDoc_STRVAR(isatty_doc,
985"isatty() -> bool. True if the file is connected to a tty device.");
986
Guido van Rossuma9e20242007-03-08 00:43:48 +0000987PyDoc_STRVAR(seekable_doc,
988"seekable() -> bool. True if file supports random-access.");
989
990PyDoc_STRVAR(readable_doc,
991"readable() -> bool. True if file was opened in a read mode.");
992
993PyDoc_STRVAR(writable_doc,
994"writable() -> bool. True if file was opened in a write mode.");
995
996static PyMethodDef fileio_methods[] = {
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000997 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
998 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
999 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1000 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1001 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1002 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001003#ifdef HAVE_FTRUNCATE
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001004 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001005#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001006 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1007 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1008 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1009 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1010 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1011 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
1012 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001013};
1014
Guido van Rossum53807da2007-04-10 19:01:47 +00001015/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1016
Guido van Rossumb0428152007-04-08 17:44:42 +00001017static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001018get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001019{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001020 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001021}
1022
1023static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001024get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001025{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001026 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001027}
1028
1029static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001030get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001031{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001032 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001033}
1034
1035static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001036 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1037 {"closefd", (getter)get_closefd, NULL,
1038 "True if the file descriptor will be closed"},
1039 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1040 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001041};
1042
Guido van Rossuma9e20242007-03-08 00:43:48 +00001043PyTypeObject PyFileIO_Type = {
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001044 PyVarObject_HEAD_INIT(NULL, 0)
1045 "_io.FileIO",
1046 sizeof(fileio),
1047 0,
1048 (destructor)fileio_dealloc, /* tp_dealloc */
1049 0, /* tp_print */
1050 0, /* tp_getattr */
1051 0, /* tp_setattr */
1052 0, /* tp_reserved */
1053 (reprfunc)fileio_repr, /* tp_repr */
1054 0, /* tp_as_number */
1055 0, /* tp_as_sequence */
1056 0, /* tp_as_mapping */
1057 0, /* tp_hash */
1058 0, /* tp_call */
1059 0, /* tp_str */
1060 PyObject_GenericGetAttr, /* tp_getattro */
1061 0, /* tp_setattro */
1062 0, /* tp_as_buffer */
1063 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1064 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1065 fileio_doc, /* tp_doc */
1066 (traverseproc)fileio_traverse, /* tp_traverse */
1067 (inquiry)fileio_clear, /* tp_clear */
1068 0, /* tp_richcompare */
1069 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1070 0, /* tp_iter */
1071 0, /* tp_iternext */
1072 fileio_methods, /* tp_methods */
1073 0, /* tp_members */
1074 fileio_getsetlist, /* tp_getset */
1075 0, /* tp_base */
1076 0, /* tp_dict */
1077 0, /* tp_descr_get */
1078 0, /* tp_descr_set */
1079 offsetof(fileio, dict), /* tp_dictoffset */
1080 fileio_init, /* tp_init */
1081 PyType_GenericAlloc, /* tp_alloc */
1082 fileio_new, /* tp_new */
1083 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001084};