blob: d5b03eec26aa0d676c9301401c76d60ed1ee6a5c [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
Guido van Rossuma9e20242007-03-08 00:43:48 +000046typedef struct {
Antoine Pitrouae4b4722010-05-05 16:31:07 +000047 PyObject_HEAD
48 int fd;
49 unsigned int readable : 1;
50 unsigned int writable : 1;
51 signed int seekable : 2; /* -1 means unknown */
52 unsigned int closefd : 1;
Antoine Pitroue033e062010-10-29 10:38:18 +000053 unsigned int deallocating: 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +000054 PyObject *weakreflist;
55 PyObject *dict;
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000056} fileio;
Guido van Rossuma9e20242007-03-08 00:43:48 +000057
Collin Winteraf334382007-03-08 21:46:15 +000058PyTypeObject PyFileIO_Type;
59
Guido van Rossuma9e20242007-03-08 00:43:48 +000060#define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type))
61
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000062int
63_PyFileIO_closed(PyObject *self)
64{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000065 return ((fileio *)self)->fd < 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000066}
Antoine Pitrou08838b62009-01-21 00:55:13 +000067
Antoine Pitroue033e062010-10-29 10:38:18 +000068/* Because this can call arbitrary code, it shouldn't be called when
69 the refcount is 0 (that is, not directly from tp_dealloc unless
70 the refcount has been temporarily re-incremented). */
71static PyObject *
72fileio_dealloc_warn(fileio *self, PyObject *source)
73{
74 if (self->fd >= 0 && self->closefd) {
75 PyObject *exc, *val, *tb;
76 PyErr_Fetch(&exc, &val, &tb);
77 if (PyErr_WarnFormat(PyExc_ResourceWarning, 1,
78 "unclosed file %R", source)) {
79 /* Spurious errors can appear at shutdown */
80 if (PyErr_ExceptionMatches(PyExc_Warning))
81 PyErr_WriteUnraisable((PyObject *) self);
82 }
83 PyErr_Restore(exc, val, tb);
84 }
85 Py_RETURN_NONE;
86}
87
Antoine Pitrou7fb111b2009-03-04 11:14:01 +000088static PyObject *
89portable_lseek(int fd, PyObject *posobj, int whence);
90
Antoine Pitroua28fcfd2009-03-13 23:42:55 +000091static PyObject *portable_lseek(int fd, PyObject *posobj, int whence);
92
Kristján Valur Jónsson19288c22008-12-18 17:15:54 +000093/* Returns 0 on success, -1 with exception set on failure. */
Neal Norwitz88b44da2007-08-12 17:23:54 +000094static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000095internal_close(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +000096{
Antoine Pitrouae4b4722010-05-05 16:31:07 +000097 int err = 0;
98 int save_errno = 0;
99 if (self->fd >= 0) {
100 int fd = self->fd;
101 self->fd = -1;
102 /* fd is accessible and someone else may have closed it */
103 if (_PyVerify_fd(fd)) {
104 Py_BEGIN_ALLOW_THREADS
105 err = close(fd);
106 if (err < 0)
107 save_errno = errno;
108 Py_END_ALLOW_THREADS
109 } else {
110 save_errno = errno;
111 err = -1;
112 }
113 }
114 if (err < 0) {
115 errno = save_errno;
116 PyErr_SetFromErrno(PyExc_IOError);
117 return -1;
118 }
119 return 0;
Neal Norwitz88b44da2007-08-12 17:23:54 +0000120}
121
122static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000123fileio_close(fileio *self)
Neal Norwitz88b44da2007-08-12 17:23:54 +0000124{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000125 if (!self->closefd) {
126 self->fd = -1;
127 Py_RETURN_NONE;
128 }
Antoine Pitroue033e062010-10-29 10:38:18 +0000129 if (self->deallocating) {
130 PyObject *r = fileio_dealloc_warn(self, (PyObject *) self);
131 if (r)
132 Py_DECREF(r);
133 else
134 PyErr_Clear();
135 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000136 errno = internal_close(self);
137 if (errno < 0)
138 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000139
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000140 return PyObject_CallMethod((PyObject*)&PyRawIOBase_Type,
141 "close", "O", self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000142}
143
144static PyObject *
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000145fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000146{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000147 fileio *self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000148
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000149 assert(type != NULL && type->tp_alloc != NULL);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000150
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000151 self = (fileio *) type->tp_alloc(type, 0);
152 if (self != NULL) {
153 self->fd = -1;
154 self->readable = 0;
155 self->writable = 0;
156 self->seekable = -1;
157 self->closefd = 1;
158 self->weakreflist = NULL;
159 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000160
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000161 return (PyObject *) self;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000162}
163
164/* On Unix, open will succeed for directories.
165 In Python, there should be no file objects referring to
166 directories, so we need a check. */
167
168static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000169dircheck(fileio* self, const char *name)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000170{
171#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000172 struct stat buf;
173 if (self->fd < 0)
174 return 0;
175 if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
176 char *msg = strerror(EISDIR);
177 PyObject *exc;
178 if (internal_close(self))
179 return -1;
Guido van Rossum53807da2007-04-10 19:01:47 +0000180
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000181 exc = PyObject_CallFunction(PyExc_IOError, "(iss)",
182 EISDIR, msg, name);
183 PyErr_SetObject(PyExc_IOError, exc);
184 Py_XDECREF(exc);
185 return -1;
186 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000187#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000188 return 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000189}
190
Benjamin Peterson806d4022009-01-19 15:11:51 +0000191static int
192check_fd(int fd)
193{
194#if defined(HAVE_FSTAT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000195 struct stat buf;
196 if (!_PyVerify_fd(fd) || (fstat(fd, &buf) < 0 && errno == EBADF)) {
197 PyObject *exc;
198 char *msg = strerror(EBADF);
199 exc = PyObject_CallFunction(PyExc_OSError, "(is)",
200 EBADF, msg);
201 PyErr_SetObject(PyExc_OSError, exc);
202 Py_XDECREF(exc);
203 return -1;
204 }
Benjamin Peterson806d4022009-01-19 15:11:51 +0000205#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000206 return 0;
Benjamin Peterson806d4022009-01-19 15:11:51 +0000207}
208
Guido van Rossuma9e20242007-03-08 00:43:48 +0000209
210static int
211fileio_init(PyObject *oself, PyObject *args, PyObject *kwds)
212{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000213 fileio *self = (fileio *) oself;
214 static char *kwlist[] = {"file", "mode", "closefd", NULL};
215 const char *name = NULL;
216 PyObject *nameobj, *stringobj = NULL;
217 char *mode = "r";
218 char *s;
Thomas Helleraf2be262007-07-12 11:03:13 +0000219#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000220 Py_UNICODE *widename = NULL;
Thomas Helleraf2be262007-07-12 11:03:13 +0000221#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000222 int ret = 0;
223 int rwa = 0, plus = 0, append = 0;
224 int flags = 0;
225 int fd = -1;
226 int closefd = 1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000227
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000228 assert(PyFileIO_Check(oself));
229 if (self->fd >= 0) {
230 /* Have to close the existing file first. */
231 if (internal_close(self) < 0)
232 return -1;
233 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000234
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000235 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:fileio",
236 kwlist, &nameobj, &mode, &closefd))
237 return -1;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000238
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000239 if (PyFloat_Check(nameobj)) {
240 PyErr_SetString(PyExc_TypeError,
241 "integer argument expected, got float");
242 return -1;
243 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000244
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000245 fd = PyLong_AsLong(nameobj);
246 if (fd < 0) {
247 if (!PyErr_Occurred()) {
248 PyErr_SetString(PyExc_ValueError,
249 "Negative filedescriptor");
250 return -1;
251 }
252 PyErr_Clear();
253 }
Guido van Rossumb0428152007-04-08 17:44:42 +0000254
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +0000255#ifdef MS_WINDOWS
Antoine Pitrou13348842012-01-29 18:36:34 +0100256 if (PyUnicode_Check(nameobj)) {
257 int rv = _PyUnicode_HasNULChars(nameobj);
258 if (rv) {
259 if (rv != -1)
260 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
261 return -1;
262 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000263 widename = PyUnicode_AS_UNICODE(nameobj);
Antoine Pitrou13348842012-01-29 18:36:34 +0100264 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000265 if (widename == NULL)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000266#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000267 if (fd < 0)
268 {
Antoine Pitrou13348842012-01-29 18:36:34 +0100269 if (!PyUnicode_FSConverter(nameobj, &stringobj)) {
270 return -1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000271 }
Antoine Pitrou13348842012-01-29 18:36:34 +0100272 name = PyBytes_AS_STRING(stringobj);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000273 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000274
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000275 s = mode;
276 while (*s) {
277 switch (*s++) {
278 case 'r':
279 if (rwa) {
280 bad_mode:
281 PyErr_SetString(PyExc_ValueError,
Georg Brandl28928ae2010-10-21 13:45:52 +0000282 "Must have exactly one of read/write/append "
283 "mode and at most one plus");
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000284 goto error;
285 }
286 rwa = 1;
287 self->readable = 1;
288 break;
289 case 'w':
290 if (rwa)
291 goto bad_mode;
292 rwa = 1;
293 self->writable = 1;
294 flags |= O_CREAT | O_TRUNC;
295 break;
296 case 'a':
297 if (rwa)
298 goto bad_mode;
299 rwa = 1;
300 self->writable = 1;
301 flags |= O_CREAT;
302 append = 1;
303 break;
304 case 'b':
305 break;
306 case '+':
307 if (plus)
308 goto bad_mode;
309 self->readable = self->writable = 1;
310 plus = 1;
311 break;
312 default:
313 PyErr_Format(PyExc_ValueError,
314 "invalid mode: %.200s", mode);
315 goto error;
316 }
317 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000318
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000319 if (!rwa)
320 goto bad_mode;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000321
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000322 if (self->readable && self->writable)
323 flags |= O_RDWR;
324 else if (self->readable)
325 flags |= O_RDONLY;
326 else
327 flags |= O_WRONLY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000328
329#ifdef O_BINARY
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000330 flags |= O_BINARY;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000331#endif
332
Walter Dörwald0e411482007-06-06 16:55:38 +0000333#ifdef O_APPEND
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000334 if (append)
335 flags |= O_APPEND;
Walter Dörwald0e411482007-06-06 16:55:38 +0000336#endif
337
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000338 if (fd >= 0) {
339 if (check_fd(fd))
340 goto error;
341 self->fd = fd;
342 self->closefd = closefd;
343 }
344 else {
345 self->closefd = 1;
346 if (!closefd) {
347 PyErr_SetString(PyExc_ValueError,
348 "Cannot use closefd=False with file name");
349 goto error;
350 }
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000351
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000352 Py_BEGIN_ALLOW_THREADS
353 errno = 0;
Thomas Helleraf2be262007-07-12 11:03:13 +0000354#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000355 if (widename != NULL)
356 self->fd = _wopen(widename, flags, 0666);
357 else
Thomas Helleraf2be262007-07-12 11:03:13 +0000358#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000359 self->fd = open(name, flags, 0666);
360 Py_END_ALLOW_THREADS
361 if (self->fd < 0) {
Christian Heimes0b489542007-10-31 19:20:48 +0000362#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000363 if (widename != NULL)
364 PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename);
365 else
Christian Heimes0b489542007-10-31 19:20:48 +0000366#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000367 PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
368 goto error;
369 }
Benjamin Peterson430d4692010-10-30 23:13:57 +0000370 if (dircheck(self, name) < 0)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000371 goto error;
372 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000373
Victor Stinner89e34362011-01-07 18:47:22 +0000374#if defined(MS_WINDOWS) || defined(__CYGWIN__)
375 /* don't translate newlines (\r\n <=> \n) */
376 _setmode(self->fd, O_BINARY);
377#endif
378
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000379 if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
380 goto error;
Antoine Pitrou08838b62009-01-21 00:55:13 +0000381
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000382 if (append) {
383 /* For consistent behaviour, we explicitly seek to the
384 end of file (otherwise, it might be done only on the
385 first write()). */
386 PyObject *pos = portable_lseek(self->fd, NULL, 2);
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000387 if (pos == NULL) {
388 if (closefd) {
389 close(self->fd);
390 self->fd = -1;
391 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000392 goto error;
Antoine Pitrou8d2b51b2010-10-30 16:19:14 +0000393 }
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000394 Py_DECREF(pos);
395 }
Antoine Pitrou7fb111b2009-03-04 11:14:01 +0000396
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000397 goto done;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000398
399 error:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000400 ret = -1;
Benjamin Petersonbbb04122010-10-30 23:16:28 +0000401 if (self->fd >= 0)
402 internal_close(self);
Guido van Rossum53807da2007-04-10 19:01:47 +0000403
Guido van Rossuma9e20242007-03-08 00:43:48 +0000404 done:
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000405 Py_CLEAR(stringobj);
406 return ret;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000407}
408
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000409static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000410fileio_traverse(fileio *self, visitproc visit, void *arg)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000411{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000412 Py_VISIT(self->dict);
413 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000414}
415
416static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000417fileio_clear(fileio *self)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000418{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000419 Py_CLEAR(self->dict);
420 return 0;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000421}
422
Guido van Rossuma9e20242007-03-08 00:43:48 +0000423static void
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000424fileio_dealloc(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000425{
Antoine Pitroue033e062010-10-29 10:38:18 +0000426 self->deallocating = 1;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000427 if (_PyIOBase_finalize((PyObject *) self) < 0)
428 return;
429 _PyObject_GC_UNTRACK(self);
430 if (self->weakreflist != NULL)
431 PyObject_ClearWeakRefs((PyObject *) self);
432 Py_CLEAR(self->dict);
433 Py_TYPE(self)->tp_free((PyObject *)self);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000434}
435
436static PyObject *
437err_closed(void)
438{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000439 PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
440 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000441}
442
443static PyObject *
Guido van Rossum53807da2007-04-10 19:01:47 +0000444err_mode(char *action)
445{
Antoine Pitrou0d739d72010-09-05 23:01:12 +0000446 PyErr_Format(IO_STATE->unsupported_operation,
447 "File not open for %s", action);
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000448 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000449}
450
451static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000452fileio_fileno(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000453{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000454 if (self->fd < 0)
455 return err_closed();
456 return PyLong_FromLong((long) self->fd);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000457}
458
459static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000460fileio_readable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000461{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000462 if (self->fd < 0)
463 return err_closed();
464 return PyBool_FromLong((long) self->readable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000465}
466
467static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000468fileio_writable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000469{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000470 if (self->fd < 0)
471 return err_closed();
472 return PyBool_FromLong((long) self->writable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000473}
474
475static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000476fileio_seekable(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000477{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000478 if (self->fd < 0)
479 return err_closed();
480 if (self->seekable < 0) {
481 PyObject *pos = portable_lseek(self->fd, NULL, SEEK_CUR);
482 if (pos == NULL) {
483 PyErr_Clear();
484 self->seekable = 0;
485 } else {
486 Py_DECREF(pos);
487 self->seekable = 1;
488 }
489 }
490 return PyBool_FromLong((long) self->seekable);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000491}
492
493static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000494fileio_readinto(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000495{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000496 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000497 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100498 int err;
Guido van Rossum53807da2007-04-10 19:01:47 +0000499
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000500 if (self->fd < 0)
501 return err_closed();
502 if (!self->readable)
503 return err_mode("reading");
Guido van Rossum53807da2007-04-10 19:01:47 +0000504
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000505 if (!PyArg_ParseTuple(args, "w*", &pbuf))
506 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000507
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000508 if (_PyVerify_fd(self->fd)) {
Victor Stinnere6edec22011-01-04 00:29:35 +0000509 len = pbuf.len;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000510 Py_BEGIN_ALLOW_THREADS
511 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000512#if defined(MS_WIN64) || defined(MS_WINDOWS)
513 if (len > INT_MAX)
514 len = INT_MAX;
515 n = read(self->fd, pbuf.buf, (int)len);
516#else
Victor Stinner72344792011-01-11 00:04:12 +0000517 n = read(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000518#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000519 Py_END_ALLOW_THREADS
520 } else
521 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100522 err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000523 PyBuffer_Release(&pbuf);
524 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100525 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000526 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100527 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000528 PyErr_SetFromErrno(PyExc_IOError);
529 return NULL;
530 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000531
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000532 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000533}
534
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000535static size_t
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000536new_buffersize(fileio *self, size_t currentsize)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000537{
538#ifdef HAVE_FSTAT
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000539 off_t pos, end;
540 struct stat st;
541 if (fstat(self->fd, &st) == 0) {
542 end = st.st_size;
543 pos = lseek(self->fd, 0L, SEEK_CUR);
544 /* Files claiming a size smaller than SMALLCHUNK may
545 actually be streaming pseudo-files. In this case, we
546 apply the more aggressive algorithm below.
547 */
548 if (end >= SMALLCHUNK && end >= pos && pos >= 0) {
549 /* Add 1 so if the file were to grow we'd notice. */
550 return currentsize + end - pos + 1;
551 }
552 }
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000553#endif
Nadeem Vawdad41a98b2011-10-13 13:34:16 +0200554 /* Expand the buffer by an amount proportional to the current size,
555 giving us amortized linear-time behavior. Use a less-than-double
556 growth factor to avoid excessive allocation. */
557 return currentsize + (currentsize >> 3) + 6;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000558}
559
Guido van Rossum7165cb12007-07-10 06:54:34 +0000560static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000561fileio_readall(fileio *self)
Guido van Rossum7165cb12007-07-10 06:54:34 +0000562{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000563 PyObject *result;
564 Py_ssize_t total = 0;
565 int n;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000566
Victor Stinnerb79f28c2011-05-25 22:09:03 +0200567 if (self->fd < 0)
568 return err_closed();
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000569 if (!_PyVerify_fd(self->fd))
570 return PyErr_SetFromErrno(PyExc_IOError);
Kristján Valur Jónssona8abe862009-03-24 15:27:42 +0000571
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000572 result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
573 if (result == NULL)
574 return NULL;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000575
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000576 while (1) {
577 size_t newsize = new_buffersize(self, total);
578 if (newsize > PY_SSIZE_T_MAX || newsize <= 0) {
579 PyErr_SetString(PyExc_OverflowError,
580 "unbounded read returned more bytes "
581 "than a Python string can hold ");
582 Py_DECREF(result);
583 return NULL;
584 }
Christian Heimesa872de52008-12-05 08:26:55 +0000585
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000586 if (PyBytes_GET_SIZE(result) < (Py_ssize_t)newsize) {
587 if (_PyBytes_Resize(&result, newsize) < 0) {
588 if (total == 0) {
589 Py_DECREF(result);
590 return NULL;
591 }
592 PyErr_Clear();
593 break;
594 }
595 }
596 Py_BEGIN_ALLOW_THREADS
597 errno = 0;
598 n = read(self->fd,
599 PyBytes_AS_STRING(result) + total,
600 newsize - total);
601 Py_END_ALLOW_THREADS
602 if (n == 0)
603 break;
604 if (n < 0) {
605 if (total > 0)
606 break;
607 if (errno == EAGAIN) {
608 Py_DECREF(result);
609 Py_RETURN_NONE;
610 }
611 Py_DECREF(result);
612 PyErr_SetFromErrno(PyExc_IOError);
613 return NULL;
614 }
615 total += n;
616 }
Guido van Rossum7165cb12007-07-10 06:54:34 +0000617
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000618 if (PyBytes_GET_SIZE(result) > total) {
619 if (_PyBytes_Resize(&result, total) < 0) {
620 /* This should never happen, but just in case */
621 Py_DECREF(result);
622 return NULL;
623 }
624 }
625 return result;
Guido van Rossum7165cb12007-07-10 06:54:34 +0000626}
627
Guido van Rossuma9e20242007-03-08 00:43:48 +0000628static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000629fileio_read(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000630{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000631 char *ptr;
632 Py_ssize_t n;
633 Py_ssize_t size = -1;
634 PyObject *bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000635
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000636 if (self->fd < 0)
637 return err_closed();
638 if (!self->readable)
639 return err_mode("reading");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000640
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000641 if (!PyArg_ParseTuple(args, "|O&", &_PyIO_ConvertSsize_t, &size))
642 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000643
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000644 if (size < 0) {
645 return fileio_readall(self);
646 }
Guido van Rossumc2f93dc2007-05-24 00:50:02 +0000647
Victor Stinnerc655a722011-07-05 11:31:49 +0200648#if defined(MS_WIN64) || defined(MS_WINDOWS)
649 if (size > INT_MAX)
650 size = INT_MAX;
651#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000652 bytes = PyBytes_FromStringAndSize(NULL, size);
653 if (bytes == NULL)
654 return NULL;
655 ptr = PyBytes_AS_STRING(bytes);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000656
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000657 if (_PyVerify_fd(self->fd)) {
658 Py_BEGIN_ALLOW_THREADS
659 errno = 0;
Victor Stinnerc655a722011-07-05 11:31:49 +0200660#if defined(MS_WIN64) || defined(MS_WINDOWS)
661 n = read(self->fd, ptr, (int)size);
662#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000663 n = read(self->fd, ptr, size);
Victor Stinnerc655a722011-07-05 11:31:49 +0200664#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000665 Py_END_ALLOW_THREADS
666 } else
667 n = -1;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000668
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000669 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100670 int err = errno;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000671 Py_DECREF(bytes);
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100672 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000673 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100674 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000675 PyErr_SetFromErrno(PyExc_IOError);
676 return NULL;
677 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000678
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000679 if (n != size) {
680 if (_PyBytes_Resize(&bytes, n) < 0) {
681 Py_DECREF(bytes);
682 return NULL;
683 }
684 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000685
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000686 return (PyObject *) bytes;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000687}
688
689static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000690fileio_write(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000691{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000692 Py_buffer pbuf;
Victor Stinnere6edec22011-01-04 00:29:35 +0000693 Py_ssize_t n, len;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100694 int err;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000695
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000696 if (self->fd < 0)
697 return err_closed();
698 if (!self->writable)
699 return err_mode("writing");
Guido van Rossum53807da2007-04-10 19:01:47 +0000700
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000701 if (!PyArg_ParseTuple(args, "y*", &pbuf))
702 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000703
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000704 if (_PyVerify_fd(self->fd)) {
705 Py_BEGIN_ALLOW_THREADS
706 errno = 0;
Victor Stinnere6edec22011-01-04 00:29:35 +0000707 len = pbuf.len;
708#if defined(MS_WIN64) || defined(MS_WINDOWS)
Victor Stinnere0daff12011-03-20 23:36:35 +0100709 if (len > 32767 && isatty(self->fd)) {
710 /* Issue #11395: the Windows console returns an error (12: not
711 enough space error) on writing into stdout if stdout mode is
712 binary and the length is greater than 66,000 bytes (or less,
713 depending on heap usage). */
714 len = 32767;
715 }
716 else if (len > INT_MAX)
Victor Stinnere6edec22011-01-04 00:29:35 +0000717 len = INT_MAX;
718 n = write(self->fd, pbuf.buf, (int)len);
719#else
Victor Stinner72344792011-01-11 00:04:12 +0000720 n = write(self->fd, pbuf.buf, len);
Victor Stinnere6edec22011-01-04 00:29:35 +0000721#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000722 Py_END_ALLOW_THREADS
723 } else
724 n = -1;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100725 err = errno;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000726
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000727 PyBuffer_Release(&pbuf);
Martin v. Löwis423be952008-08-13 15:53:07 +0000728
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000729 if (n < 0) {
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100730 if (err == EAGAIN)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000731 Py_RETURN_NONE;
Antoine Pitrouc345ce12011-12-16 12:28:32 +0100732 errno = err;
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000733 PyErr_SetFromErrno(PyExc_IOError);
734 return NULL;
735 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000736
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000737 return PyLong_FromSsize_t(n);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000738}
739
Guido van Rossum53807da2007-04-10 19:01:47 +0000740/* XXX Windows support below is likely incomplete */
741
Guido van Rossum53807da2007-04-10 19:01:47 +0000742/* Cribbed from posix_lseek() */
743static PyObject *
744portable_lseek(int fd, PyObject *posobj, int whence)
745{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000746 Py_off_t pos, res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000747
748#ifdef SEEK_SET
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000749 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
750 switch (whence) {
Guido van Rossum53807da2007-04-10 19:01:47 +0000751#if SEEK_SET != 0
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000752 case 0: whence = SEEK_SET; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000753#endif
754#if SEEK_CUR != 1
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000755 case 1: whence = SEEK_CUR; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000756#endif
Antoine Pitrou4f7945f2009-01-20 11:42:11 +0000757#if SEEK_END != 2
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000758 case 2: whence = SEEK_END; break;
Guido van Rossum53807da2007-04-10 19:01:47 +0000759#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000760 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000761#endif /* SEEK_SET */
762
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000763 if (posobj == NULL)
764 pos = 0;
765 else {
766 if(PyFloat_Check(posobj)) {
767 PyErr_SetString(PyExc_TypeError, "an integer is required");
768 return NULL;
769 }
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000770#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000771 pos = PyLong_AsLongLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000772#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000773 pos = PyLong_AsLong(posobj);
Guido van Rossum53807da2007-04-10 19:01:47 +0000774#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000775 if (PyErr_Occurred())
776 return NULL;
777 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000778
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000779 if (_PyVerify_fd(fd)) {
780 Py_BEGIN_ALLOW_THREADS
Guido van Rossum53807da2007-04-10 19:01:47 +0000781#if defined(MS_WIN64) || defined(MS_WINDOWS)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000782 res = _lseeki64(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000783#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000784 res = lseek(fd, pos, whence);
Guido van Rossum53807da2007-04-10 19:01:47 +0000785#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000786 Py_END_ALLOW_THREADS
787 } else
788 res = -1;
789 if (res < 0)
790 return PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum53807da2007-04-10 19:01:47 +0000791
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000792#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000793 return PyLong_FromLongLong(res);
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000794#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000795 return PyLong_FromLong(res);
Guido van Rossum53807da2007-04-10 19:01:47 +0000796#endif
797}
798
Guido van Rossuma9e20242007-03-08 00:43:48 +0000799static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000800fileio_seek(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000801{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000802 PyObject *posobj;
803 int whence = 0;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000804
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000805 if (self->fd < 0)
806 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000807
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000808 if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence))
809 return NULL;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000810
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000811 return portable_lseek(self->fd, posobj, whence);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000812}
813
814static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000815fileio_tell(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000816{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000817 if (self->fd < 0)
818 return err_closed();
Guido van Rossuma9e20242007-03-08 00:43:48 +0000819
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000820 return portable_lseek(self->fd, NULL, 1);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000821}
822
Thomas Hellerc6a55ee2007-07-11 12:45:46 +0000823#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +0000824static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000825fileio_truncate(fileio *self, PyObject *args)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000826{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000827 PyObject *posobj = NULL; /* the new size wanted by the user */
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000828#ifndef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000829 Py_off_t pos;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000830#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000831 int ret;
832 int fd;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000833
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000834 fd = self->fd;
835 if (fd < 0)
836 return err_closed();
837 if (!self->writable)
838 return err_mode("writing");
Guido van Rossuma9e20242007-03-08 00:43:48 +0000839
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000840 if (!PyArg_ParseTuple(args, "|O", &posobj))
841 return NULL;
Guido van Rossum53807da2007-04-10 19:01:47 +0000842
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000843 if (posobj == Py_None || posobj == NULL) {
844 /* Get the current position. */
845 posobj = portable_lseek(fd, NULL, 1);
846 if (posobj == NULL)
847 return NULL;
848 }
849 else {
850 Py_INCREF(posobj);
851 }
Guido van Rossum53807da2007-04-10 19:01:47 +0000852
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000853#ifdef MS_WINDOWS
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000854 /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
855 so don't even try using it. */
856 {
857 PyObject *oldposobj, *tempposobj;
858 HANDLE hFile;
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000859
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000860 /* we save the file pointer position */
861 oldposobj = portable_lseek(fd, NULL, 1);
862 if (oldposobj == NULL) {
863 Py_DECREF(posobj);
864 return NULL;
865 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000866
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000867 /* we then move to the truncation position */
868 tempposobj = portable_lseek(fd, posobj, 0);
869 if (tempposobj == NULL) {
870 Py_DECREF(oldposobj);
871 Py_DECREF(posobj);
872 return NULL;
873 }
874 Py_DECREF(tempposobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000875
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000876 /* Truncate. Note that this may grow the file! */
877 Py_BEGIN_ALLOW_THREADS
878 errno = 0;
879 hFile = (HANDLE)_get_osfhandle(fd);
880 ret = hFile == (HANDLE)-1; /* testing for INVALID_HANDLE value */
881 if (ret == 0) {
882 ret = SetEndOfFile(hFile) == 0;
883 if (ret)
884 errno = EACCES;
885 }
886 Py_END_ALLOW_THREADS
887
888 /* we restore the file pointer position in any case */
889 tempposobj = portable_lseek(fd, oldposobj, 0);
890 Py_DECREF(oldposobj);
891 if (tempposobj == NULL) {
892 Py_DECREF(posobj);
893 return NULL;
894 }
895 Py_DECREF(tempposobj);
896 }
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000897#else
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000898
899#if defined(HAVE_LARGEFILE_SUPPORT)
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000900 pos = PyLong_AsLongLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000901#else
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000902 pos = PyLong_AsLong(posobj);
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000903#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000904 if (PyErr_Occurred()){
905 Py_DECREF(posobj);
906 return NULL;
907 }
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000908
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000909 Py_BEGIN_ALLOW_THREADS
910 errno = 0;
911 ret = ftruncate(fd, pos);
912 Py_END_ALLOW_THREADS
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000913
Thomas Hellerfdeee3a2007-07-12 11:21:36 +0000914#endif /* !MS_WINDOWS */
Guido van Rossuma9e20242007-03-08 00:43:48 +0000915
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000916 if (ret != 0) {
917 Py_DECREF(posobj);
918 PyErr_SetFromErrno(PyExc_IOError);
919 return NULL;
920 }
Guido van Rossuma9e20242007-03-08 00:43:48 +0000921
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000922 return posobj;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000923}
Antoine Pitrou905a2ff2010-01-31 22:47:27 +0000924#endif /* HAVE_FTRUNCATE */
Guido van Rossum53807da2007-04-10 19:01:47 +0000925
926static char *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000927mode_string(fileio *self)
Guido van Rossum53807da2007-04-10 19:01:47 +0000928{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000929 if (self->readable) {
930 if (self->writable)
931 return "rb+";
932 else
933 return "rb";
934 }
935 else
936 return "wb";
Guido van Rossum53807da2007-04-10 19:01:47 +0000937}
Guido van Rossuma9e20242007-03-08 00:43:48 +0000938
939static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000940fileio_repr(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000941{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000942 PyObject *nameobj, *res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000943
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000944 if (self->fd < 0)
945 return PyUnicode_FromFormat("<_io.FileIO [closed]>");
Antoine Pitrou716c4442009-05-23 19:04:03 +0000946
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000947 nameobj = PyObject_GetAttrString((PyObject *) self, "name");
948 if (nameobj == NULL) {
949 if (PyErr_ExceptionMatches(PyExc_AttributeError))
950 PyErr_Clear();
951 else
952 return NULL;
953 res = PyUnicode_FromFormat("<_io.FileIO fd=%d mode='%s'>",
954 self->fd, mode_string(self));
955 }
956 else {
957 res = PyUnicode_FromFormat("<_io.FileIO name=%R mode='%s'>",
958 nameobj, mode_string(self));
959 Py_DECREF(nameobj);
960 }
961 return res;
Guido van Rossuma9e20242007-03-08 00:43:48 +0000962}
963
964static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000965fileio_isatty(fileio *self)
Guido van Rossuma9e20242007-03-08 00:43:48 +0000966{
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000967 long res;
Guido van Rossum53807da2007-04-10 19:01:47 +0000968
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000969 if (self->fd < 0)
970 return err_closed();
971 Py_BEGIN_ALLOW_THREADS
972 res = isatty(self->fd);
973 Py_END_ALLOW_THREADS
974 return PyBool_FromLong(res);
Guido van Rossuma9e20242007-03-08 00:43:48 +0000975}
976
Antoine Pitrou243757e2010-11-05 21:15:39 +0000977static PyObject *
978fileio_getstate(fileio *self)
979{
980 PyErr_Format(PyExc_TypeError,
981 "cannot serialize '%s' object", Py_TYPE(self)->tp_name);
982 return NULL;
983}
984
Guido van Rossuma9e20242007-03-08 00:43:48 +0000985
986PyDoc_STRVAR(fileio_doc,
987"file(name: str[, mode: str]) -> file IO object\n"
988"\n"
989"Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n"
Antoine Pitrouae4b4722010-05-05 16:31:07 +0000990"writing or appending. The file will be created if it doesn't exist\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +0000991"when opened for writing or appending; it will be truncated when\n"
992"opened for writing. Add a '+' to the mode to allow simultaneous\n"
993"reading and writing.");
994
995PyDoc_STRVAR(read_doc,
996"read(size: int) -> bytes. read at most size bytes, returned as bytes.\n"
997"\n"
998"Only makes one system call, so less data may be returned than requested\n"
Guido van Rossum7165cb12007-07-10 06:54:34 +0000999"In non-blocking mode, returns None if no data is available.\n"
1000"On end-of-file, returns ''.");
1001
1002PyDoc_STRVAR(readall_doc,
1003"readall() -> bytes. read all data from the file, returned as bytes.\n"
1004"\n"
1005"In non-blocking mode, returns as much as is immediately available,\n"
1006"or None if no data is available. On end-of-file, returns ''.");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001007
1008PyDoc_STRVAR(write_doc,
1009"write(b: bytes) -> int. Write bytes b to file, return number written.\n"
1010"\n"
1011"Only makes one system call, so not all of the data may be written.\n"
1012"The number of bytes actually written is returned.");
1013
1014PyDoc_STRVAR(fileno_doc,
1015"fileno() -> int. \"file descriptor\".\n"
1016"\n"
1017"This is needed for lower-level file interfaces, such the fcntl module.");
1018
1019PyDoc_STRVAR(seek_doc,
1020"seek(offset: int[, whence: int]) -> None. Move to new file position.\n"
1021"\n"
1022"Argument offset is a byte count. Optional argument whence defaults to\n"
1023"0 (offset from start of file, offset should be >= 0); other values are 1\n"
1024"(move relative to current position, positive or negative), and 2 (move\n"
1025"relative to end of file, usually negative, although many platforms allow\n"
1026"seeking beyond the end of a file)."
1027"\n"
1028"Note that not all file objects are seekable.");
1029
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001030#ifdef HAVE_FTRUNCATE
Guido van Rossuma9e20242007-03-08 00:43:48 +00001031PyDoc_STRVAR(truncate_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001032"truncate([size: int]) -> None. Truncate the file to at most size bytes.\n"
Guido van Rossuma9e20242007-03-08 00:43:48 +00001033"\n"
Alexandre Vassalotti77250f42008-05-06 19:48:38 +00001034"Size defaults to the current file position, as returned by tell()."
1035"The current file position is changed to the value of size.");
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001036#endif
Guido van Rossuma9e20242007-03-08 00:43:48 +00001037
1038PyDoc_STRVAR(tell_doc,
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001039"tell() -> int. Current file position");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001040
1041PyDoc_STRVAR(readinto_doc,
Benjamin Peterson9a8082f2009-03-05 00:55:56 +00001042"readinto() -> Same as RawIOBase.readinto().");
Guido van Rossuma9e20242007-03-08 00:43:48 +00001043
1044PyDoc_STRVAR(close_doc,
1045"close() -> None. Close the file.\n"
1046"\n"
1047"A closed file cannot be used for further I/O operations. close() may be\n"
1048"called more than once without error. Changes the fileno to -1.");
1049
1050PyDoc_STRVAR(isatty_doc,
1051"isatty() -> bool. True if the file is connected to a tty device.");
1052
Guido van Rossuma9e20242007-03-08 00:43:48 +00001053PyDoc_STRVAR(seekable_doc,
1054"seekable() -> bool. True if file supports random-access.");
1055
1056PyDoc_STRVAR(readable_doc,
1057"readable() -> bool. True if file was opened in a read mode.");
1058
1059PyDoc_STRVAR(writable_doc,
1060"writable() -> bool. True if file was opened in a write mode.");
1061
1062static PyMethodDef fileio_methods[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001063 {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc},
1064 {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc},
1065 {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc},
1066 {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc},
1067 {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc},
1068 {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001069#ifdef HAVE_FTRUNCATE
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001070 {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc},
Thomas Hellerc6a55ee2007-07-11 12:45:46 +00001071#endif
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001072 {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc},
1073 {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc},
1074 {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc},
1075 {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc},
1076 {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc},
1077 {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc},
Antoine Pitroue033e062010-10-29 10:38:18 +00001078 {"_dealloc_warn", (PyCFunction)fileio_dealloc_warn, METH_O, NULL},
Antoine Pitrou243757e2010-11-05 21:15:39 +00001079 {"__getstate__", (PyCFunction)fileio_getstate, METH_NOARGS, NULL},
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001080 {NULL, NULL} /* sentinel */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001081};
1082
Guido van Rossum53807da2007-04-10 19:01:47 +00001083/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1084
Guido van Rossumb0428152007-04-08 17:44:42 +00001085static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001086get_closed(fileio *self, void *closure)
Guido van Rossumb0428152007-04-08 17:44:42 +00001087{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001088 return PyBool_FromLong((long)(self->fd < 0));
Guido van Rossum53807da2007-04-10 19:01:47 +00001089}
1090
1091static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001092get_closefd(fileio *self, void *closure)
Christian Heimesecc42a22008-11-05 19:30:32 +00001093{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001094 return PyBool_FromLong((long)(self->closefd));
Christian Heimesecc42a22008-11-05 19:30:32 +00001095}
1096
1097static PyObject *
Benjamin Peterson680bf1a2009-06-12 02:07:12 +00001098get_mode(fileio *self, void *closure)
Guido van Rossum53807da2007-04-10 19:01:47 +00001099{
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001100 return PyUnicode_FromString(mode_string(self));
Guido van Rossumb0428152007-04-08 17:44:42 +00001101}
1102
1103static PyGetSetDef fileio_getsetlist[] = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001104 {"closed", (getter)get_closed, NULL, "True if the file is closed"},
1105 {"closefd", (getter)get_closefd, NULL,
1106 "True if the file descriptor will be closed"},
1107 {"mode", (getter)get_mode, NULL, "String giving the file mode"},
1108 {NULL},
Guido van Rossumb0428152007-04-08 17:44:42 +00001109};
1110
Guido van Rossuma9e20242007-03-08 00:43:48 +00001111PyTypeObject PyFileIO_Type = {
Antoine Pitrouae4b4722010-05-05 16:31:07 +00001112 PyVarObject_HEAD_INIT(NULL, 0)
1113 "_io.FileIO",
1114 sizeof(fileio),
1115 0,
1116 (destructor)fileio_dealloc, /* tp_dealloc */
1117 0, /* tp_print */
1118 0, /* tp_getattr */
1119 0, /* tp_setattr */
1120 0, /* tp_reserved */
1121 (reprfunc)fileio_repr, /* tp_repr */
1122 0, /* tp_as_number */
1123 0, /* tp_as_sequence */
1124 0, /* tp_as_mapping */
1125 0, /* tp_hash */
1126 0, /* tp_call */
1127 0, /* tp_str */
1128 PyObject_GenericGetAttr, /* tp_getattro */
1129 0, /* tp_setattro */
1130 0, /* tp_as_buffer */
1131 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
1132 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1133 fileio_doc, /* tp_doc */
1134 (traverseproc)fileio_traverse, /* tp_traverse */
1135 (inquiry)fileio_clear, /* tp_clear */
1136 0, /* tp_richcompare */
1137 offsetof(fileio, weakreflist), /* tp_weaklistoffset */
1138 0, /* tp_iter */
1139 0, /* tp_iternext */
1140 fileio_methods, /* tp_methods */
1141 0, /* tp_members */
1142 fileio_getsetlist, /* tp_getset */
1143 0, /* tp_base */
1144 0, /* tp_dict */
1145 0, /* tp_descr_get */
1146 0, /* tp_descr_set */
1147 offsetof(fileio, dict), /* tp_dictoffset */
1148 fileio_init, /* tp_init */
1149 PyType_GenericAlloc, /* tp_alloc */
1150 fileio_new, /* tp_new */
1151 PyObject_GC_Del, /* tp_free */
Guido van Rossuma9e20242007-03-08 00:43:48 +00001152};