blob: 473919b7a7137f04bf141a345c2532bbba83ddf1 [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,
Georg Brandld62ecbf2010-11-26 08:52:36 +0000268 "Must have exactly one of read/write/append "
269 "mode and at most one plus");
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000270 goto error;
271 }
272 rwa = 1;
273 self->readable = 1;
274 break;
275 case 'w':
276 if (rwa)
277 goto bad_mode;
278 rwa = 1;
279 self->writable = 1;
280 flags |= O_CREAT | O_TRUNC;
281 break;
282 case 'a':
283 if (rwa)
284 goto bad_mode;
285 rwa = 1;
286 self->writable = 1;
287 flags |= O_CREAT;
288 append = 1;
289 break;
290 case 'b':
291 break;
292 case '+':
293 if (plus)
294 goto bad_mode;
295 self->readable = self->writable = 1;
296 plus = 1;
297 break;
298 default:
299 PyErr_Format(PyExc_ValueError,
300 "invalid mode: %.200s", mode);
301 goto error;
302 }
303 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000304
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000305 if (!rwa)
306 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000307
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000308 if (self->readable && self->writable)
309 flags |= O_RDWR;
310 else if (self->readable)
311 flags |= O_RDONLY;
312 else
313 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000314
315#ifdef O_BINARY
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000316 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000317#endif
318
Walter Dörwald0e411482007-06-06 16:55:38 +0000319#ifdef O_APPEND
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000320 if (append)
321 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000322#endif
323
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000324 if (fd >= 0) {
325 if (check_fd(fd))
326 goto error;
327 self->fd = fd;
328 self->closefd = closefd;
329 }
330 else {
331 self->closefd = 1;
332 if (!closefd) {
333 PyErr_SetString(PyExc_ValueError,
334 "Cannot use closefd=False with file name");
335 goto error;
336 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000337
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000338 Py_BEGIN_ALLOW_THREADS
339 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000340#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000341 if (widename != NULL)
342 self->fd = _wopen(widename, flags, 0666);
343 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000344#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000345 self->fd = open(name, flags, 0666);
346 Py_END_ALLOW_THREADS
347 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000348#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000349 if (widename != NULL)
350 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
351 else
Christian Heimes0b489542007-10-31 19:20:48 +0000352#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000353 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
354 goto error;
355 }
356 if(dircheck(self, name) < 0)
357 goto error;
358 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000359
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000360 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
361 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000362
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000363 if (append) {
364 /* For consistent behaviour, we explicitly seek to the
365 end of file (otherwise, it might be done only on the
366 first write()). */
367 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou735e3b12010-10-31 13:05:21 +0000368 if (pos == NULL) {
369 if (closefd) {
370 close(self->fd);
371 self->fd = -1;
372 }
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000373 goto error;
Antoine Pitrou735e3b12010-10-31 13:05:21 +0000374 }
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000375 Py_DECREF(pos);
376 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000377
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000378 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000379
380 error:
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000381 ret = -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000382
Guido van Rossuma9e20242007-03-08 00:43:48 +0000383 done:
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000384 Py_CLEAR(stringobj);
385 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000386}
387
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000388static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000389fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000390{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000391 Py_VISIT(self->dict);
392 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000393}
394
395static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000396fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000397{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000398 Py_CLEAR(self->dict);
399 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000400}
401
Guido van Rossuma9e20242007-03-08 00:43:48 +0000402static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000403fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000404{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000405 if (_PyIOBase_finalize((PyObject *) self) < 0)
406 return;
407 _PyObject_GC_UNTRACK(self);
408 if (self->weakreflist != NULL)
409 PyObject_ClearWeakRefs((PyObject *) self);
410 Py_CLEAR(self->dict);
411 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000412}
413
414static PyObject *
415err_closed(void)
416{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000417 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
418 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000419}
420
421static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000422err_mode(char *action)
423{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000424 PyErr_Format(PyExc_ValueError, "File not open for %s", action);
425 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000426}
427
428static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000429fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000430{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000431 if (self->fd < 0)
432 return err_closed();
433 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000434}
435
436static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000437fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000438{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000439 if (self->fd < 0)
440 return err_closed();
441 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000442}
443
444static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000445fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000446{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000447 if (self->fd < 0)
448 return err_closed();
449 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000450}
451
452static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000453fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000454{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000455 if (self->fd < 0)
456 return err_closed();
457 if (self->seekable < 0) {
458 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
459 if (pos == NULL) {
460 PyErr_Clear();
461 self->seekable = 0;
462 } else {
463 Py_DECREF(pos);
464 self->seekable = 1;
465 }
466 }
467 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000468}
469
470static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000471fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000472{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000473 Py_buffer pbuf;
474 Py_ssize_t n;
Guido van Rossum53807da2007-04-10 19:01:47 +0000475
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000476 if (self->fd < 0)
477 return err_closed();
478 if (!self->readable)
479 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000480
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000481 if (!PyArg_ParseTuple(args, "w*", &pbuf))
482 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000483
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000484 if (_PyVerify_fd(self->fd)) {
485 Py_BEGIN_ALLOW_THREADS
486 errno = 0;
487 n = read(self->fd, pbuf.buf, pbuf.len);
488 Py_END_ALLOW_THREADS
489 } else
490 n = -1;
491 PyBuffer_Release(&pbuf);
492 if (n < 0) {
493 if (errno == EAGAIN)
494 Py_RETURN_NONE;
495 PyErr_SetFromErrno(PyExc_IOError);
496 return NULL;
497 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000498
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000499 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000500}
501
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000502static size_t
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000503new_buffersize(fileio *self, size_t currentsize)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000504{
505#ifdef HAVE_FSTAT
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000506 off_t pos, end;
507 struct stat st;
508 if (fstat(self->fd, &st) == 0) {
509 end = st.st_size;
510 pos = lseek(self->fd, 0L, SEEK_CUR);
511 /* Files claiming a size smaller than SMALLCHUNK may
512 actually be streaming pseudo-files. In this case, we
513 apply the more aggressive algorithm below.
514 */
515 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
516 /* Add 1 so if the file were to grow we'd notice. */
517 return currentsize + end - pos + 1;
518 }
519 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000520#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000521 if (currentsize > SMALLCHUNK) {
522 /* Keep doubling until we reach BIGCHUNK;
523 then keep adding BIGCHUNK. */
524 if (currentsize <= BIGCHUNK)
525 return currentsize + currentsize;
526 else
527 return currentsize + BIGCHUNK;
528 }
529 return currentsize + SMALLCHUNK;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000530}
531
Guido van Rossum7165cb12007-07-10 06:54:34 +0000532static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000533fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000534{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000535 PyObject *result;
536 Py_ssize_t total = 0;
537 int n;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000538
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000539 if (!_PyVerify_fd(self->fd))
540 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000541
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000542 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
543 if (result == NULL)
544 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000545
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000546 while (1) {
547 size_t newsize = new_buffersize(self, total);
548 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
549 PyErr_SetString(PyExc_OverflowError,
550 "unbounded read returned more bytes "
551 "than a Python string can hold ");
552 Py_DECREF(result);
553 return NULL;
554 }
Christian Heimesa872de52008-12-05 08:26:55 +0000555
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000556 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
557 if (_PyBytes_Resize(&result, newsize) < 0) {
558 if (total == 0) {
559 Py_DECREF(result);
560 return NULL;
561 }
562 PyErr_Clear();
563 break;
564 }
565 }
566 Py_BEGIN_ALLOW_THREADS
567 errno = 0;
568 n = read(self->fd,
569 PyBytes_AS_STRING(result) + total,
570 newsize - total);
571 Py_END_ALLOW_THREADS
572 if (n == 0)
573 break;
574 if (n < 0) {
575 if (total > 0)
576 break;
577 if (errno == EAGAIN) {
578 Py_DECREF(result);
579 Py_RETURN_NONE;
580 }
581 Py_DECREF(result);
582 PyErr_SetFromErrno(PyExc_IOError);
583 return NULL;
584 }
585 total += n;
586 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000587
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000588 if (PyBytes_GET_SIZE(result) > total) {
589 if (_PyBytes_Resize(&result, total) < 0) {
590 /* This should never happen, but just in case */
591 Py_DECREF(result);
592 return NULL;
593 }
594 }
595 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000596}
597
Guido van Rossuma9e20242007-03-08 00:43:48 +0000598static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000599fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000600{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000601 char *ptr;
602 Py_ssize_t n;
603 Py_ssize_t size = -1;
604 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000605
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000606 if (self->fd < 0)
607 return err_closed();
608 if (!self->readable)
609 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000610
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000611 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
612 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000613
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000614 if (size < 0) {
615 return fileio_readall(self);
616 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000617
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000618 bytes = PyBytes_FromStringAndSize(NULL, size);
619 if (bytes == NULL)
620 return NULL;
621 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000622
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000623 if (_PyVerify_fd(self->fd)) {
624 Py_BEGIN_ALLOW_THREADS
625 errno = 0;
626 n = read(self->fd, ptr, size);
627 Py_END_ALLOW_THREADS
628 } else
629 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000630
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000631 if (n < 0) {
632 Py_DECREF(bytes);
633 if (errno == EAGAIN)
634 Py_RETURN_NONE;
635 PyErr_SetFromErrno(PyExc_IOError);
636 return NULL;
637 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000638
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000639 if (n != size) {
640 if (_PyBytes_Resize(&bytes, n) < 0) {
641 Py_DECREF(bytes);
642 return NULL;
643 }
644 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000645
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000646 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000647}
648
649static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000650fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000651{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000652 Py_buffer pbuf;
653 Py_ssize_t n;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000654
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000655 if (self->fd < 0)
656 return err_closed();
657 if (!self->writable)
658 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000659
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000660 if (!PyArg_ParseTuple(args, "y*", &pbuf))
661 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000662
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000663 if (_PyVerify_fd(self->fd)) {
664 Py_BEGIN_ALLOW_THREADS
665 errno = 0;
666 n = write(self->fd, pbuf.buf, pbuf.len);
667 Py_END_ALLOW_THREADS
668 } else
669 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000670
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000671 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000672
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000673 if (n < 0) {
674 if (errno == EAGAIN)
675 Py_RETURN_NONE;
676 PyErr_SetFromErrno(PyExc_IOError);
677 return NULL;
678 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000679
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000680 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000681}
682
Guido van Rossum53807da2007-04-10 19:01:47 +0000683/* XXX Windows support below is likely incomplete */
684
Guido van Rossum53807da2007-04-10 19:01:47 +0000685/* Cribbed from posix_lseek() */
686static PyObject *
687portable_lseek(int fd, PyObject *posobj, int whence)
688{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000689 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000690
691#ifdef SEEK_SET
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000692 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
693 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000694#if SEEK_SET != 0
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000695 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000696#endif
697#if SEEK_CUR != 1
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000698 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000699#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000700#if SEEK_END != 2
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000701 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000702#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000703 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000704#endif /* SEEK_SET */
705
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000706 if (posobj == NULL)
707 pos = 0;
708 else {
709 if(PyFloat_Check(posobj)) {
710 PyErr_SetString(PyExc_TypeError, "an integer is required");
711 return NULL;
712 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000713#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000714 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000715#else
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000716 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000717#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000718 if (PyErr_Occurred())
719 return NULL;
720 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000721
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000722 if (_PyVerify_fd(fd)) {
723 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000724#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000725 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000726#else
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000727 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000728#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000729 Py_END_ALLOW_THREADS
730 } else
731 res = -1;
732 if (res < 0)
733 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000734
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000735#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000736 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000737#else
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000738 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000739#endif
740}
741
Guido van Rossuma9e20242007-03-08 00:43:48 +0000742static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000743fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000744{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000745 PyObject *posobj;
746 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000747
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000748 if (self->fd < 0)
749 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000750
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000751 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
752 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000753
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000754 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000755}
756
757static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000758fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000759{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000760 if (self->fd < 0)
761 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000762
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000763 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000764}
765
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000766#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000767static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000768fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000769{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000770 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000771#ifndef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000772 Py_off_t pos;
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000773#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000774 int ret;
775 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000776
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000777 fd = self->fd;
778 if (fd < 0)
779 return err_closed();
780 if (!self->writable)
781 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000782
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000783 if (!PyArg_ParseTuple(args, "|O", &posobj))
784 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000785
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000786 if (posobj == Py_None || posobj == NULL) {
787 /* Get the current position. */
788 posobj = portable_lseek(fd, NULL, 1);
789 if (posobj == NULL)
790 return NULL;
791 }
792 else {
793 Py_INCREF(posobj);
794 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000795
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000796#ifdef MS_WINDOWS
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000797 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
798 so don't even try using it. */
799 {
800 PyObject *oldposobj, *tempposobj;
801 HANDLE hFile;
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000802
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000803 /* we save the file pointer position */
804 oldposobj = portable_lseek(fd, NULL, 1);
805 if (oldposobj == NULL) {
806 Py_DECREF(posobj);
807 return NULL;
808 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000809
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000810 /* we then move to the truncation position */
811 tempposobj = portable_lseek(fd, posobj, 0);
812 if (tempposobj == NULL) {
813 Py_DECREF(oldposobj);
814 Py_DECREF(posobj);
815 return NULL;
816 }
817 Py_DECREF(tempposobj);
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000818
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000819 /* Truncate. Note that this may grow the file! */
820 Py_BEGIN_ALLOW_THREADS
821 errno = 0;
822 hFile = (HANDLE)_get_osfhandle(fd);
823 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
824 if (ret == 0) {
825 ret = SetEndOfFile(hFile) == 0;
826 if (ret)
827 errno = EACCES;
828 }
829 Py_END_ALLOW_THREADS
830
831 /* we restore the file pointer position in any case */
832 tempposobj = portable_lseek(fd, oldposobj, 0);
833 Py_DECREF(oldposobj);
834 if (tempposobj == NULL) {
835 Py_DECREF(posobj);
836 return NULL;
837 }
838 Py_DECREF(tempposobj);
839 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000840#else
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000841
842#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000843 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000844#else
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000845 pos = PyLong_AsLong(posobj);
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000846#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000847 if (PyErr_Occurred()){
848 Py_DECREF(posobj);
849 return NULL;
850 }
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000851
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000852 Py_BEGIN_ALLOW_THREADS
853 errno = 0;
854 ret = ftruncate(fd, pos);
855 Py_END_ALLOW_THREADS
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000856
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000857#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000858
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000859 if (ret != 0) {
860 Py_DECREF(posobj);
861 PyErr_SetFromErrno(PyExc_IOError);
862 return NULL;
863 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000864
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000865 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000866}
Antoine Pitrou66f9fea2010-01-31 23:20:26 +0000867#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000868
869static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000870mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000871{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000872 if (self->readable) {
873 if (self->writable)
874 return "rb+";
875 else
876 return "rb";
877 }
878 else
879 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000880}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000881
882static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000883fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000884{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000885 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000886
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000887 if (self->fd < 0)
888 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000889
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000890 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
891 if (nameobj == NULL) {
892 if (PyErr_ExceptionMatches(PyExc_AttributeError))
893 PyErr_Clear();
894 else
895 return NULL;
896 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
897 self->fd, mode_string(self));
898 }
899 else {
900 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
901 nameobj, mode_string(self));
902 Py_DECREF(nameobj);
903 }
904 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000905}
906
907static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000908fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000909{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000910 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000911
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000912 if (self->fd < 0)
913 return err_closed();
914 Py_BEGIN_ALLOW_THREADS
915 res = isatty(self->fd);
916 Py_END_ALLOW_THREADS
917 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000918}
919
Guido van Rossuma9e20242007-03-08 00:43:48 +0000920
921PyDoc_STRVAR(fileio_doc,
922"file(name: str[, mode: str]) -> file IO object\n"
923"\n"
924"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000925"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +0000926"when opened for writing or appending; it will be truncated when\n"
927"opened for writing. Add a '+' to the mode to allow simultaneous\n"
928"reading and writing.");
929
930PyDoc_STRVAR(read_doc,
931"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
932"\n"
933"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +0000934"In non-blocking mode, returns None if no data is available.\n"
935"On end-of-file, returns ''.");
936
937PyDoc_STRVAR(readall_doc,
938"readall() -> bytes. read all data from the file, returned as bytes.\n"
939"\n"
940"In non-blocking mode, returns as much as is immediately available,\n"
941"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000942
943PyDoc_STRVAR(write_doc,
944"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
945"\n"
946"Only makes one system call, so not all of the data may be written.\n"
947"The number of bytes actually written is returned.");
948
949PyDoc_STRVAR(fileno_doc,
950"fileno() -> int. \"file descriptor\".\n"
951"\n"
952"This is needed for lower-level file interfaces, such the fcntl module.");
953
954PyDoc_STRVAR(seek_doc,
955"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
956"\n"
957"Argument offset is a byte count. Optional argument whence defaults to\n"
958"0 (offset from start of file, offset should be >= 0); other values are 1\n"
959"(move relative to current position, positive or negative), and 2 (move\n"
960"relative to end of file, usually negative, although many platforms allow\n"
961"seeking beyond the end of a file)."
962"\n"
963"Note that not all file objects are seekable.");
964
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000965#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000966PyDoc_STRVAR(truncate_doc,
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000967"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +0000968"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000969"Size defaults to the current file position, as returned by tell()."
970"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000971#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +0000972
973PyDoc_STRVAR(tell_doc,
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000974"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000975
976PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +0000977"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000978
979PyDoc_STRVAR(close_doc,
980"close() -> None. Close the file.\n"
981"\n"
982"A closed file cannot be used for further I/O operations. close() may be\n"
983"called more than once without error. Changes the fileno to -1.");
984
985PyDoc_STRVAR(isatty_doc,
986"isatty() -> bool. True if the file is connected to a tty device.");
987
Guido van Rossuma9e20242007-03-08 00:43:48 +0000988PyDoc_STRVAR(seekable_doc,
989"seekable() -> bool. True if file supports random-access.");
990
991PyDoc_STRVAR(readable_doc,
992"readable() -> bool. True if file was opened in a read mode.");
993
994PyDoc_STRVAR(writable_doc,
995"writable() -> bool. True if file was opened in a write mode.");
996
997static PyMethodDef fileio_methods[] = {
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +0000998 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
999 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1000 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1001 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1002 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1003 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001004#ifdef HAVE_FTRUNCATE
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001005 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001006#endif
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001007 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1008 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1009 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1010 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1011 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1012 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
1013 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001014};
1015
Guido van Rossum53807da2007-04-10 19:01:47 +00001016/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1017
Guido van Rossumb0428152007-04-08 17:44:42 +00001018static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001019get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001020{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001021 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001022}
1023
1024static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001025get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001026{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001027 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001028}
1029
1030static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001031get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001032{
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001033 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001034}
1035
1036static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001037 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1038 {"closefd", (getter)get_closefd, NULL,
1039 "True if the file descriptor will be closed"},
1040 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1041 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001042};
1043
Guido van Rossuma9e20242007-03-08 00:43:48 +00001044PyTypeObject PyFileIO_Type = {
Antoine Pitrouf7ec1fd2010-05-05 16:34:37 +00001045 PyVarObject_HEAD_INIT(NULL, 0)
1046 "_io.FileIO",
1047 sizeof(fileio),
1048 0,
1049 (destructor)fileio_dealloc, /* tp_dealloc */
1050 0, /* tp_print */
1051 0, /* tp_getattr */
1052 0, /* tp_setattr */
1053 0, /* tp_reserved */
1054 (reprfunc)fileio_repr, /* tp_repr */
1055 0, /* tp_as_number */
1056 0, /* tp_as_sequence */
1057 0, /* tp_as_mapping */
1058 0, /* tp_hash */
1059 0, /* tp_call */
1060 0, /* tp_str */
1061 PyObject_GenericGetAttr, /* tp_getattro */
1062 0, /* tp_setattro */
1063 0, /* tp_as_buffer */
1064 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1065 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1066 fileio_doc, /* tp_doc */
1067 (traverseproc)fileio_traverse, /* tp_traverse */
1068 (inquiry)fileio_clear, /* tp_clear */
1069 0, /* tp_richcompare */
1070 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1071 0, /* tp_iter */
1072 0, /* tp_iternext */
1073 fileio_methods, /* tp_methods */
1074 0, /* tp_members */
1075 fileio_getsetlist, /* tp_getset */
1076 0, /* tp_base */
1077 0, /* tp_dict */
1078 0, /* tp_descr_get */
1079 0, /* tp_descr_set */
1080 offsetof(fileio, dict), /* tp_dictoffset */
1081 fileio_init, /* tp_init */
1082 PyType_GenericAlloc, /* tp_alloc */
1083 fileio_new, /* tp_new */
1084 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001085};