blob: ba5e0960297c12e7530dd7d97c9db2af4487cbb6 [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"
Antoine Pitroue033e062010-10-29 10:38:18 +00005#include "structmember.h"
Benjamin Peterson2614cda2010-03-21 22:36:19 +00006#ifdef HAVE_SYS_TYPES_H
Guido van Rossuma9e20242007-03-08 00:43:48 +00007#include <sys/types.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +00008#endif
9#ifdef HAVE_SYS_STAT_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000010#include <sys/stat.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000011#endif
12#ifdef HAVE_FCNTL_H
Guido van Rossuma9e20242007-03-08 00:43:48 +000013#include <fcntl.h>
Benjamin Peterson2614cda2010-03-21 22:36:19 +000014#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +000015#include <stddef.h> /* For offsetof */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000016#include "_iomodule.h"
Guido van Rossuma9e20242007-03-08 00:43:48 +000017
18/*
19 * Known likely problems:
20 *
21 * - Files larger then 2**32-1
22 * - Files with unicode filenames
23 * - Passing numbers greater than 2**32-1 when an integer is expected
24 * - Making it work on Windows and other oddball platforms
25 *
26 * To Do:
27 *
28 * - autoconfify header file inclusion
Guido van Rossuma9e20242007-03-08 00:43:48 +000029 */
30
31#ifdef MS_WINDOWS
32/* can simulate truncate with Win32 API functions; see file_truncate */
Thomas Hellerfdeee3a2007-07-12 11:21:36 +000033#define HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +000034#define WIN32_LEAN_AND_MEAN
35#include <windows.h>
36#endif
37
Christian Heimesa872de52008-12-05 08:26:55 +000038#if BUFSIZ < (8*1024)
39#define SMALLCHUNK (8*1024)
40#elif (BUFSIZ >= (2 << 25))
41#error "unreasonable BUFSIZ > 64MB defined"
42#else
43#define SMALLCHUNK BUFSIZ
44#endif
45
46#if SIZEOF_INT < 4
47#define BIGCHUNK (512 * 32)
48#else
49#define BIGCHUNK (512 * 1024)
50#endif
51
Guido van Rossuma9e20242007-03-08 00:43:48 +000052typedef struct {
Antoine Pitrouae4b4722010-05-05 16:31:07 +000053 PyObject_HEAD
54 int fd;
55 unsigned int readable : 1;
56 unsigned int writable : 1;
57 signed int seekable : 2; /* -1 means unknown */
58 unsigned int closefd : 1;
Antoine Pitroue033e062010-10-29 10:38:18 +000059 unsigned int deallocating: 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000060 PyObject *weakreflist;
61 PyObject *dict;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000062} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000063
Collin Winteraf334382007-03-08 21:46:15 +000064PyTypeObject PyFileIO_Type;
65
Guido van Rossuma9e20242007-03-08 00:43:48 +000066#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
67
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000068int
69_PyFileIO_closed(PyObject *self)
70{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000071 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000072}
Antoine Pitrou08838b62009-01-21 00:55:13 +000073
Antoine Pitroue033e062010-10-29 10:38:18 +000074/* Because this can call arbitrary code, it shouldn't be called when
75 the refcount is 0 (that is, not directly from tp_dealloc unless
76 the refcount has been temporarily re-incremented). */
77static PyObject *
78fileio_dealloc_warn(fileio *self, PyObject *source)
79{
80 if (self->fd >= 0 && self->closefd) {
81 PyObject *exc, *val, *tb;
82 PyErr_Fetch(&exc, &val, &tb);
83 if (PyErr_WarnFormat(PyExc_ResourceWarning, 1,
84 "unclosed file %R", source)) {
85 /* Spurious errors can appear at shutdown */
86 if (PyErr_ExceptionMatches(PyExc_Warning))
87 PyErr_WriteUnraisable((PyObject *) self);
88 }
89 PyErr_Restore(exc, val, tb);
90 }
91 Py_RETURN_NONE;
92}
93
Antoine Pitrou7fb111b2009-03-04 11:14:01 +000094static PyObject *
95portable_lseek(int fd, PyObject *posobj, int whence);
96
Antoine Pitroua28fcfd2009-03-13 23:42:55 +000097static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
98
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +000099/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +0000100static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000101internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000102{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000103 int err = 0;
104 int save_errno = 0;
105 if (self->fd >= 0) {
106 int fd = self->fd;
107 self->fd = -1;
108 /* fd is accessible and someone else may have closed it */
109 if (_PyVerify_fd(fd)) {
110 Py_BEGIN_ALLOW_THREADS
111 err = close(fd);
112 if (err < 0)
113 save_errno = errno;
114 Py_END_ALLOW_THREADS
115 } else {
116 save_errno = errno;
117 err = -1;
118 }
119 }
120 if (err < 0) {
121 errno = save_errno;
122 PyErr_SetFromErrno(PyExc_IOError);
123 return -1;
124 }
125 return 0;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000126}
127
128static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000129fileio_close(fileio *self)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000130{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200131 _Py_identifier(close);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000132 if (!self->closefd) {
133 self->fd = -1;
134 Py_RETURN_NONE;
135 }
Antoine Pitroue033e062010-10-29 10:38:18 +0000136 if (self->deallocating) {
137 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
138 if (r)
139 Py_DECREF(r);
140 else
141 PyErr_Clear();
142 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000143 errno = internal_close(self);
144 if (errno < 0)
145 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000146
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200147 return _PyObject_CallMethodId((PyObject*)&PyRawIOBase_Type,
148 &PyId_close, "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000149}
150
151static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000152fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000153{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000154 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000155
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000156 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000157
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000158 self = (fileio *) type->tp_alloc(type, 0);
159 if (self != NULL) {
160 self->fd = -1;
161 self->readable = 0;
162 self->writable = 0;
163 self->seekable = -1;
164 self->closefd = 1;
165 self->weakreflist = NULL;
166 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000167
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000168 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000169}
170
171/* On Unix, open will succeed for directories.
172 In Python, there should be no file objects referring to
173 directories, so we need a check. */
174
175static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000176dircheck(fileio* self, const char *name)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000177{
178#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000179 struct stat buf;
180 if (self->fd < 0)
181 return 0;
182 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
183 char *msg = strerror(EISDIR);
184 PyObject *exc;
185 if (internal_close(self))
186 return -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000187
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000188 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
189 EISDIR, msg, name);
190 PyErr_SetObject(PyExc_IOError, exc);
191 Py_XDECREF(exc);
192 return -1;
193 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000194#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000195 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000196}
197
Benjamin Peterson806d4022009-01-19 15:11:51 +0000198static int
199check_fd(int fd)
200{
201#if defined(HAVE_FSTAT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000202 struct stat buf;
203 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
204 PyObject *exc;
205 char *msg = strerror(EBADF);
206 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
207 EBADF, msg);
208 PyErr_SetObject(PyExc_OSError, exc);
209 Py_XDECREF(exc);
210 return -1;
211 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000212#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000213 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000214}
215
Guido van Rossuma9e20242007-03-08 00:43:48 +0000216
217static int
218fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
219{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000220 fileio *self = (fileio *) oself;
221 static char *kwlist[] = {"file", "mode", "closefd", NULL};
222 const char *name = NULL;
223 PyObject *nameobj, *stringobj = NULL;
224 char *mode = "r";
225 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000226#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000227 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000228#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000229 int ret = 0;
230 int rwa = 0, plus = 0, append = 0;
231 int flags = 0;
232 int fd = -1;
233 int closefd = 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000234
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000235 assert(PyFileIO_Check(oself));
236 if (self->fd >= 0) {
237 /* Have to close the existing file first. */
238 if (internal_close(self) < 0)
239 return -1;
240 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000241
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000242 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
243 kwlist, &nameobj, &mode, &closefd))
244 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000245
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000246 if (PyFloat_Check(nameobj)) {
247 PyErr_SetString(PyExc_TypeError,
248 "integer argument expected, got float");
249 return -1;
250 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000251
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000252 fd = PyLong_AsLong(nameobj);
253 if (fd < 0) {
254 if (!PyErr_Occurred()) {
255 PyErr_SetString(PyExc_ValueError,
256 "Negative filedescriptor");
257 return -1;
258 }
259 PyErr_Clear();
260 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000261
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000262#ifdef MS_WINDOWS
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200263 if (PyUnicode_Check(nameobj)) {
264 widename = PyUnicode_AsUnicode(nameobj);
265 if (widename == NULL)
266 return -1;
267 } else
Guido van Rossuma9e20242007-03-08 00:43:48 +0000268#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000269 if (fd < 0)
270 {
271 if (PyBytes_Check(nameobj) || PyByteArray_Check(nameobj)) {
272 Py_ssize_t namelen;
273 if (PyObject_AsCharBuffer(nameobj, &name, &namelen) < 0)
274 return -1;
275 }
276 else {
277 PyObject *u = PyUnicode_FromObject(nameobj);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000278
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000279 if (u == NULL)
280 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000281
Victor Stinnerae6265f2010-05-15 16:27:27 +0000282 stringobj = PyUnicode_EncodeFSDefault(u);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000283 Py_DECREF(u);
284 if (stringobj == NULL)
285 return -1;
286 if (!PyBytes_Check(stringobj)) {
287 PyErr_SetString(PyExc_TypeError,
288 "encoder failed to return bytes");
289 goto error;
290 }
291 name = PyBytes_AS_STRING(stringobj);
292 }
293 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000294
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000295 s = mode;
296 while (*s) {
297 switch (*s++) {
298 case 'r':
299 if (rwa) {
300 bad_mode:
301 PyErr_SetString(PyExc_ValueError,
Georg Brandl28928ae2010-10-21 13:45:52 +0000302 "Must have exactly one of read/write/append "
303 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000304 goto error;
305 }
306 rwa = 1;
307 self->readable = 1;
308 break;
309 case 'w':
310 if (rwa)
311 goto bad_mode;
312 rwa = 1;
313 self->writable = 1;
314 flags |= O_CREAT | O_TRUNC;
315 break;
316 case 'a':
317 if (rwa)
318 goto bad_mode;
319 rwa = 1;
320 self->writable = 1;
321 flags |= O_CREAT;
322 append = 1;
323 break;
324 case 'b':
325 break;
326 case '+':
327 if (plus)
328 goto bad_mode;
329 self->readable = self->writable = 1;
330 plus = 1;
331 break;
332 default:
333 PyErr_Format(PyExc_ValueError,
334 "invalid mode: %.200s", mode);
335 goto error;
336 }
337 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000338
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000339 if (!rwa)
340 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000341
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000342 if (self->readable && self->writable)
343 flags |= O_RDWR;
344 else if (self->readable)
345 flags |= O_RDONLY;
346 else
347 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000348
349#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000350 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000351#endif
352
Walter Dörwald0e411482007-06-06 16:55:38 +0000353#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000354 if (append)
355 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000356#endif
357
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000358 if (fd >= 0) {
359 if (check_fd(fd))
360 goto error;
361 self->fd = fd;
362 self->closefd = closefd;
363 }
364 else {
365 self->closefd = 1;
366 if (!closefd) {
367 PyErr_SetString(PyExc_ValueError,
368 "Cannot use closefd=False with file name");
369 goto error;
370 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000371
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000372 Py_BEGIN_ALLOW_THREADS
373 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000374#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000375 if (widename != NULL)
376 self->fd = _wopen(widename, flags, 0666);
377 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000378#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000379 self->fd = open(name, flags, 0666);
380 Py_END_ALLOW_THREADS
381 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000382#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000383 if (widename != NULL)
Victor Stinnerfe9a8612011-09-29 23:19:04 +0200384 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, nameobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000385 else
Christian Heimes0b489542007-10-31 19:20:48 +0000386#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000387 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
388 goto error;
389 }
Benjamin Peterson430d4692010-10-30 23:13:57 +0000390 if (dircheck(self, name) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000391 goto error;
392 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000393
Victor Stinner89e34362011-01-07 18:47:22 +0000394#if defined(MS_WINDOWS) || defined(__CYGWIN__)
395 /* don't translate newlines (\r\n <=> \n) */
396 _setmode(self->fd, O_BINARY);
397#endif
398
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000399 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
400 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000401
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000402 if (append) {
403 /* For consistent behaviour, we explicitly seek to the
404 end of file (otherwise, it might be done only on the
405 first write()). */
406 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000407 if (pos == NULL) {
408 if (closefd) {
409 close(self->fd);
410 self->fd = -1;
411 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000412 goto error;
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000413 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000414 Py_DECREF(pos);
415 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000416
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000417 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000418
419 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000420 ret = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000421 if (self->fd >= 0)
422 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000423
Guido van Rossuma9e20242007-03-08 00:43:48 +0000424 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000425 Py_CLEAR(stringobj);
426 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000427}
428
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000429static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000430fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000431{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000432 Py_VISIT(self->dict);
433 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000434}
435
436static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000437fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000438{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000439 Py_CLEAR(self->dict);
440 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000441}
442
Guido van Rossuma9e20242007-03-08 00:43:48 +0000443static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000444fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000445{
Antoine Pitroue033e062010-10-29 10:38:18 +0000446 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000447 if (_PyIOBase_finalize((PyObject *) self) < 0)
448 return;
449 _PyObject_GC_UNTRACK(self);
450 if (self->weakreflist != NULL)
451 PyObject_ClearWeakRefs((PyObject *) self);
452 Py_CLEAR(self->dict);
453 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000454}
455
456static PyObject *
457err_closed(void)
458{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000459 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
460 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000461}
462
463static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000464err_mode(char *action)
465{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000466 PyErr_Format(IO_STATE->unsupported_operation,
467 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000468 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000469}
470
471static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000472fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000473{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000474 if (self->fd < 0)
475 return err_closed();
476 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000477}
478
479static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000480fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000481{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000482 if (self->fd < 0)
483 return err_closed();
484 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000485}
486
487static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000488fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000489{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000490 if (self->fd < 0)
491 return err_closed();
492 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000493}
494
495static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000496fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000497{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000498 if (self->fd < 0)
499 return err_closed();
500 if (self->seekable < 0) {
501 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
502 if (pos == NULL) {
503 PyErr_Clear();
504 self->seekable = 0;
505 } else {
506 Py_DECREF(pos);
507 self->seekable = 1;
508 }
509 }
510 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000511}
512
513static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000514fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000515{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000516 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000517 Py_ssize_t n, len;
Guido van Rossum53807da2007-04-10 19:01:47 +0000518
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000519 if (self->fd < 0)
520 return err_closed();
521 if (!self->readable)
522 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000523
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000524 if (!PyArg_ParseTuple(args, "w*", &pbuf))
525 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000526
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000527 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000528 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000529 Py_BEGIN_ALLOW_THREADS
530 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000531#if defined(MS_WIN64) || defined(MS_WINDOWS)
532 if (len > INT_MAX)
533 len = INT_MAX;
534 n = read(self->fd, pbuf.buf, (int)len);
535#else
Victor Stinner72344792011-01-11 00:04:12 +0000536 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000537#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000538 Py_END_ALLOW_THREADS
539 } else
540 n = -1;
541 PyBuffer_Release(&pbuf);
542 if (n < 0) {
543 if (errno == EAGAIN)
544 Py_RETURN_NONE;
545 PyErr_SetFromErrno(PyExc_IOError);
546 return NULL;
547 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000548
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000549 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000550}
551
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000552static size_t
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200553new_buffersize(fileio *self, size_t currentsize
554#ifdef HAVE_FSTAT
Victor Stinnera2a64772011-10-11 22:45:02 +0200555 , Py_off_t pos, Py_off_t end
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200556#endif
557 )
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000558{
559#ifdef HAVE_FSTAT
Victor Stinnera2a64772011-10-11 22:45:02 +0200560 if (end != (Py_off_t)-1) {
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000561 /* Files claiming a size smaller than SMALLCHUNK may
562 actually be streaming pseudo-files. In this case, we
563 apply the more aggressive algorithm below.
564 */
565 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
566 /* Add 1 so if the file were to grow we'd notice. */
Victor Stinnerc5af7732011-10-11 23:00:31 +0200567 Py_off_t bufsize = currentsize + end - pos + 1;
568 if (bufsize < PY_SSIZE_T_MAX)
569 return (size_t)bufsize;
570 else
571 return PY_SSIZE_T_MAX;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000572 }
573 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000574#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000575 if (currentsize > SMALLCHUNK) {
576 /* Keep doubling until we reach BIGCHUNK;
577 then keep adding BIGCHUNK. */
578 if (currentsize <= BIGCHUNK)
579 return currentsize + currentsize;
580 else
581 return currentsize + BIGCHUNK;
582 }
583 return currentsize + SMALLCHUNK;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000584}
585
Guido van Rossum7165cb12007-07-10 06:54:34 +0000586static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000587fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000588{
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200589#ifdef HAVE_FSTAT
590 struct stat st;
Victor Stinnera2a64772011-10-11 22:45:02 +0200591 Py_off_t pos, end;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200592#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000593 PyObject *result;
594 Py_ssize_t total = 0;
595 int n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200596 size_t newsize;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000597
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200598 if (self->fd < 0)
599 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000600 if (!_PyVerify_fd(self->fd))
601 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000602
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000603 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
604 if (result == NULL)
605 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000606
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200607#ifdef HAVE_FSTAT
608#if defined(MS_WIN64) || defined(MS_WINDOWS)
609 pos = _lseeki64(self->fd, 0L, SEEK_CUR);
610#else
611 pos = lseek(self->fd, 0L, SEEK_CUR);
612#endif
613 if (fstat(self->fd, &st) == 0)
614 end = st.st_size;
615 else
Victor Stinnera2a64772011-10-11 22:45:02 +0200616 end = (Py_off_t)-1;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200617#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000618 while (1) {
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200619#ifdef HAVE_FSTAT
620 newsize = new_buffersize(self, total, pos, end);
621#else
622 newsize = new_buffersize(self, total);
623#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000624 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
625 PyErr_SetString(PyExc_OverflowError,
626 "unbounded read returned more bytes "
627 "than a Python string can hold ");
628 Py_DECREF(result);
629 return NULL;
630 }
Christian Heimesa872de52008-12-05 08:26:55 +0000631
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000632 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
633 if (_PyBytes_Resize(&result, newsize) < 0) {
634 if (total == 0) {
635 Py_DECREF(result);
636 return NULL;
637 }
638 PyErr_Clear();
639 break;
640 }
641 }
642 Py_BEGIN_ALLOW_THREADS
643 errno = 0;
644 n = read(self->fd,
645 PyBytes_AS_STRING(result) + total,
646 newsize - total);
647 Py_END_ALLOW_THREADS
648 if (n == 0)
649 break;
650 if (n < 0) {
651 if (total > 0)
652 break;
653 if (errno == EAGAIN) {
654 Py_DECREF(result);
655 Py_RETURN_NONE;
656 }
657 Py_DECREF(result);
658 PyErr_SetFromErrno(PyExc_IOError);
659 return NULL;
660 }
661 total += n;
Victor Stinnere9d44ccb2011-05-26 00:16:44 +0200662#ifdef HAVE_FSTAT
663 pos += n;
664#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000665 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000666
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000667 if (PyBytes_GET_SIZE(result) > total) {
668 if (_PyBytes_Resize(&result, total) < 0) {
669 /* This should never happen, but just in case */
670 Py_DECREF(result);
671 return NULL;
672 }
673 }
674 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000675}
676
Guido van Rossuma9e20242007-03-08 00:43:48 +0000677static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000678fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000679{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000680 char *ptr;
681 Py_ssize_t n;
682 Py_ssize_t size = -1;
683 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000684
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000685 if (self->fd < 0)
686 return err_closed();
687 if (!self->readable)
688 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000689
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000690 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
691 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000692
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000693 if (size < 0) {
694 return fileio_readall(self);
695 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000696
Victor Stinnerc655a722011-07-05 11:31:49 +0200697#if defined(MS_WIN64) || defined(MS_WINDOWS)
698 if (size > INT_MAX)
699 size = INT_MAX;
700#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000701 bytes = PyBytes_FromStringAndSize(NULL, size);
702 if (bytes == NULL)
703 return NULL;
704 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000705
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000706 if (_PyVerify_fd(self->fd)) {
707 Py_BEGIN_ALLOW_THREADS
708 errno = 0;
Victor Stinnerc655a722011-07-05 11:31:49 +0200709#if defined(MS_WIN64) || defined(MS_WINDOWS)
710 n = read(self->fd, ptr, (int)size);
711#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000712 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200713#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000714 Py_END_ALLOW_THREADS
715 } else
716 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000717
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000718 if (n < 0) {
719 Py_DECREF(bytes);
720 if (errno == EAGAIN)
721 Py_RETURN_NONE;
722 PyErr_SetFromErrno(PyExc_IOError);
723 return NULL;
724 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000725
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000726 if (n != size) {
727 if (_PyBytes_Resize(&bytes, n) < 0) {
728 Py_DECREF(bytes);
729 return NULL;
730 }
731 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000732
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000733 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000734}
735
736static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000737fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000738{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000739 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000740 Py_ssize_t n, len;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000741
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000742 if (self->fd < 0)
743 return err_closed();
744 if (!self->writable)
745 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000746
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000747 if (!PyArg_ParseTuple(args, "y*", &pbuf))
748 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000749
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000750 if (_PyVerify_fd(self->fd)) {
751 Py_BEGIN_ALLOW_THREADS
752 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000753 len = pbuf.len;
754#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100755 if (len > 32767 && isatty(self->fd)) {
756 /* Issue #11395: the Windows console returns an error (12: not
757 enough space error) on writing into stdout if stdout mode is
758 binary and the length is greater than 66,000 bytes (or less,
759 depending on heap usage). */
760 len = 32767;
761 }
762 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000763 len = INT_MAX;
764 n = write(self->fd, pbuf.buf, (int)len);
765#else
Victor Stinner72344792011-01-11 00:04:12 +0000766 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000767#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000768 Py_END_ALLOW_THREADS
769 } else
770 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000771
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000772 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000773
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000774 if (n < 0) {
775 if (errno == EAGAIN)
776 Py_RETURN_NONE;
777 PyErr_SetFromErrno(PyExc_IOError);
778 return NULL;
779 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000780
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000781 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000782}
783
Guido van Rossum53807da2007-04-10 19:01:47 +0000784/* XXX Windows support below is likely incomplete */
785
Guido van Rossum53807da2007-04-10 19:01:47 +0000786/* Cribbed from posix_lseek() */
787static PyObject *
788portable_lseek(int fd, PyObject *posobj, int whence)
789{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000790 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000791
792#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000793 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
794 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000795#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000796 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000797#endif
798#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000799 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000800#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000801#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000802 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000803#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000804 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000805#endif /* SEEK_SET */
806
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000807 if (posobj == NULL)
808 pos = 0;
809 else {
810 if(PyFloat_Check(posobj)) {
811 PyErr_SetString(PyExc_TypeError, "an integer is required");
812 return NULL;
813 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000814#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000815 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000816#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000817 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000818#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000819 if (PyErr_Occurred())
820 return NULL;
821 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000822
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000823 if (_PyVerify_fd(fd)) {
824 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000825#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000826 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000827#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000828 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000829#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000830 Py_END_ALLOW_THREADS
831 } else
832 res = -1;
833 if (res < 0)
834 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000835
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000836#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000837 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000838#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000839 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000840#endif
841}
842
Guido van Rossuma9e20242007-03-08 00:43:48 +0000843static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000844fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000845{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000846 PyObject *posobj;
847 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000848
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000849 if (self->fd < 0)
850 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000851
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000852 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
853 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000854
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000855 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000856}
857
858static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000859fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000860{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000861 if (self->fd < 0)
862 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000863
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000864 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000865}
866
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000867#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000868static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000869fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000870{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000871 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000872#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000873 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000874#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000875 int ret;
876 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000877
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000878 fd = self->fd;
879 if (fd < 0)
880 return err_closed();
881 if (!self->writable)
882 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000883
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000884 if (!PyArg_ParseTuple(args, "|O", &posobj))
885 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000886
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000887 if (posobj == Py_None || posobj == NULL) {
888 /* Get the current position. */
889 posobj = portable_lseek(fd, NULL, 1);
890 if (posobj == NULL)
891 return NULL;
892 }
893 else {
894 Py_INCREF(posobj);
895 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000896
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000897#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000898 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
899 so don't even try using it. */
900 {
901 PyObject *oldposobj, *tempposobj;
902 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000903
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000904 /* we save the file pointer position */
905 oldposobj = portable_lseek(fd, NULL, 1);
906 if (oldposobj == NULL) {
907 Py_DECREF(posobj);
908 return NULL;
909 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000910
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000911 /* we then move to the truncation position */
912 tempposobj = portable_lseek(fd, posobj, 0);
913 if (tempposobj == NULL) {
914 Py_DECREF(oldposobj);
915 Py_DECREF(posobj);
916 return NULL;
917 }
918 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000919
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000920 /* Truncate. Note that this may grow the file! */
921 Py_BEGIN_ALLOW_THREADS
922 errno = 0;
923 hFile = (HANDLE)_get_osfhandle(fd);
924 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
925 if (ret == 0) {
926 ret = SetEndOfFile(hFile) == 0;
927 if (ret)
928 errno = EACCES;
929 }
930 Py_END_ALLOW_THREADS
931
932 /* we restore the file pointer position in any case */
933 tempposobj = portable_lseek(fd, oldposobj, 0);
934 Py_DECREF(oldposobj);
935 if (tempposobj == NULL) {
936 Py_DECREF(posobj);
937 return NULL;
938 }
939 Py_DECREF(tempposobj);
940 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000941#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000942
943#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000944 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000945#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000946 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000947#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000948 if (PyErr_Occurred()){
949 Py_DECREF(posobj);
950 return NULL;
951 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000952
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000953 Py_BEGIN_ALLOW_THREADS
954 errno = 0;
955 ret = ftruncate(fd, pos);
956 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000957
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000958#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000959
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000960 if (ret != 0) {
961 Py_DECREF(posobj);
962 PyErr_SetFromErrno(PyExc_IOError);
963 return NULL;
964 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000965
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000966 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000967}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000968#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000969
970static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000971mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000972{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000973 if (self->readable) {
974 if (self->writable)
975 return "rb+";
976 else
977 return "rb";
978 }
979 else
980 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000981}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000982
983static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000984fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000985{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000986 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000987
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000988 if (self->fd < 0)
989 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000990
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000991 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
992 if (nameobj == NULL) {
993 if (PyErr_ExceptionMatches(PyExc_AttributeError))
994 PyErr_Clear();
995 else
996 return NULL;
997 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
998 self->fd, mode_string(self));
999 }
1000 else {
1001 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
1002 nameobj, mode_string(self));
1003 Py_DECREF(nameobj);
1004 }
1005 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +00001006}
1007
1008static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001009fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +00001010{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001011 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +00001012
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001013 if (self->fd < 0)
1014 return err_closed();
1015 Py_BEGIN_ALLOW_THREADS
1016 res = isatty(self->fd);
1017 Py_END_ALLOW_THREADS
1018 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +00001019}
1020
Antoine Pitrou243757e2010-11-05 21:15:39 +00001021static PyObject *
1022fileio_getstate(fileio *self)
1023{
1024 PyErr_Format(PyExc_TypeError,
1025 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
1026 return NULL;
1027}
1028
Guido van Rossuma9e20242007-03-08 00:43:48 +00001029
1030PyDoc_STRVAR(fileio_doc,
1031"file(name: str[, mode: str]) -> file IO object\n"
1032"\n"
1033"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001034"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001035"when opened for writing or appending; it will be truncated when\n"
1036"opened for writing. Add a '+' to the mode to allow simultaneous\n"
1037"reading and writing.");
1038
1039PyDoc_STRVAR(read_doc,
1040"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
1041"\n"
1042"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +00001043"In non-blocking mode, returns None if no data is available.\n"
1044"On end-of-file, returns ''.");
1045
1046PyDoc_STRVAR(readall_doc,
1047"readall() -> bytes. read all data from the file, returned as bytes.\n"
1048"\n"
1049"In non-blocking mode, returns as much as is immediately available,\n"
1050"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001051
1052PyDoc_STRVAR(write_doc,
1053"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1054"\n"
1055"Only makes one system call, so not all of the data may be written.\n"
1056"The number of bytes actually written is returned.");
1057
1058PyDoc_STRVAR(fileno_doc,
1059"fileno() -> int. \"file descriptor\".\n"
1060"\n"
1061"This is needed for lower-level file interfaces, such the fcntl module.");
1062
1063PyDoc_STRVAR(seek_doc,
1064"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1065"\n"
1066"Argument offset is a byte count. Optional argument whence defaults to\n"
1067"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1068"(move relative to current position, positive or negative), and 2 (move\n"
1069"relative to end of file, usually negative, although many platforms allow\n"
1070"seeking beyond the end of a file)."
1071"\n"
1072"Note that not all file objects are seekable.");
1073
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001074#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001075PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001076"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001077"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001078"Size defaults to the current file position, as returned by tell()."
1079"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001080#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001081
1082PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001083"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001084
1085PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001086"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001087
1088PyDoc_STRVAR(close_doc,
1089"close() -> None. Close the file.\n"
1090"\n"
1091"A closed file cannot be used for further I/O operations. close() may be\n"
1092"called more than once without error. Changes the fileno to -1.");
1093
1094PyDoc_STRVAR(isatty_doc,
1095"isatty() -> bool. True if the file is connected to a tty device.");
1096
Guido van Rossuma9e20242007-03-08 00:43:48 +00001097PyDoc_STRVAR(seekable_doc,
1098"seekable() -> bool. True if file supports random-access.");
1099
1100PyDoc_STRVAR(readable_doc,
1101"readable() -> bool. True if file was opened in a read mode.");
1102
1103PyDoc_STRVAR(writable_doc,
1104"writable() -> bool. True if file was opened in a write mode.");
1105
1106static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001107 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1108 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1109 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1110 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1111 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1112 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001113#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001114 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001115#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001116 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1117 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1118 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1119 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1120 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1121 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001122 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001123 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001124 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001125};
1126
Guido van Rossum53807da2007-04-10 19:01:47 +00001127/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1128
Guido van Rossumb0428152007-04-08 17:44:42 +00001129static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001130get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001131{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001132 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001133}
1134
1135static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001136get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001137{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001138 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001139}
1140
1141static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001142get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001143{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001144 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001145}
1146
1147static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001148 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1149 {"closefd", (getter)get_closefd, NULL,
1150 "True if the file descriptor will be closed"},
1151 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1152 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001153};
1154
Guido van Rossuma9e20242007-03-08 00:43:48 +00001155PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001156 PyVarObject_HEAD_INIT(NULL, 0)
1157 "_io.FileIO",
1158 sizeof(fileio),
1159 0,
1160 (destructor)fileio_dealloc, /* tp_dealloc */
1161 0, /* tp_print */
1162 0, /* tp_getattr */
1163 0, /* tp_setattr */
1164 0, /* tp_reserved */
1165 (reprfunc)fileio_repr, /* tp_repr */
1166 0, /* tp_as_number */
1167 0, /* tp_as_sequence */
1168 0, /* tp_as_mapping */
1169 0, /* tp_hash */
1170 0, /* tp_call */
1171 0, /* tp_str */
1172 PyObject_GenericGetAttr, /* tp_getattro */
1173 0, /* tp_setattro */
1174 0, /* tp_as_buffer */
1175 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1176 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1177 fileio_doc, /* tp_doc */
1178 (traverseproc)fileio_traverse, /* tp_traverse */
1179 (inquiry)fileio_clear, /* tp_clear */
1180 0, /* tp_richcompare */
1181 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1182 0, /* tp_iter */
1183 0, /* tp_iternext */
1184 fileio_methods, /* tp_methods */
1185 0, /* tp_members */
1186 fileio_getsetlist, /* tp_getset */
1187 0, /* tp_base */
1188 0, /* tp_dict */
1189 0, /* tp_descr_get */
1190 0, /* tp_descr_set */
1191 offsetof(fileio, dict), /* tp_dictoffset */
1192 fileio_init, /* tp_init */
1193 PyType_GenericAlloc, /* tp_alloc */
1194 fileio_new, /* tp_new */
1195 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001196};