Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 1 | /* Author: Daniel Stutzbach */ |
| 2 | |
| 3 | #define PY_SSIZE_T_CLEAN |
| 4 | #include "Python.h" |
| 5 | #include <sys/types.h> |
| 6 | #include <sys/stat.h> |
| 7 | #include <fcntl.h> |
| 8 | #include <stddef.h> /* For offsetof */ |
| 9 | |
| 10 | /* |
| 11 | * Known likely problems: |
| 12 | * |
| 13 | * - Files larger then 2**32-1 |
| 14 | * - Files with unicode filenames |
| 15 | * - Passing numbers greater than 2**32-1 when an integer is expected |
| 16 | * - Making it work on Windows and other oddball platforms |
| 17 | * |
| 18 | * To Do: |
| 19 | * |
| 20 | * - autoconfify header file inclusion |
| 21 | */ |
| 22 | |
| 23 | #ifdef MS_WINDOWS |
| 24 | /* can simulate truncate with Win32 API functions; see file_truncate */ |
| 25 | #define HAVE_FTRUNCATE |
| 26 | #define WIN32_LEAN_AND_MEAN |
| 27 | #include <windows.h> |
| 28 | #endif |
| 29 | |
| 30 | typedef struct { |
| 31 | PyObject_HEAD |
| 32 | int fd; |
| 33 | unsigned readable : 1; |
| 34 | unsigned writable : 1; |
| 35 | int seekable : 2; /* -1 means unknown */ |
| 36 | int closefd : 1; |
| 37 | PyObject *weakreflist; |
| 38 | } PyFileIOObject; |
| 39 | |
| 40 | PyTypeObject PyFileIO_Type; |
| 41 | |
| 42 | #define PyFileIO_Check(op) (PyObject_TypeCheck((op), &PyFileIO_Type)) |
| 43 | |
| 44 | /* Returns 0 on success, errno (which is < 0) on failure. */ |
| 45 | static int |
| 46 | internal_close(PyFileIOObject *self) |
| 47 | { |
| 48 | int save_errno = 0; |
| 49 | if (self->fd >= 0) { |
| 50 | int fd = self->fd; |
| 51 | self->fd = -1; |
| 52 | Py_BEGIN_ALLOW_THREADS |
| 53 | if (close(fd) < 0) |
| 54 | save_errno = errno; |
| 55 | Py_END_ALLOW_THREADS |
| 56 | } |
| 57 | return save_errno; |
| 58 | } |
| 59 | |
| 60 | static PyObject * |
| 61 | fileio_close(PyFileIOObject *self) |
| 62 | { |
| 63 | if (!self->closefd) { |
Amaury Forgeot d'Arc | 3226565 | 2008-11-20 23:34:31 +0000 | [diff] [blame^] | 64 | self->fd = -1; |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 65 | Py_RETURN_NONE; |
| 66 | } |
| 67 | errno = internal_close(self); |
| 68 | if (errno < 0) { |
| 69 | PyErr_SetFromErrno(PyExc_IOError); |
| 70 | return NULL; |
| 71 | } |
| 72 | |
| 73 | Py_RETURN_NONE; |
| 74 | } |
| 75 | |
| 76 | static PyObject * |
| 77 | fileio_new(PyTypeObject *type, PyObject *args, PyObject *kews) |
| 78 | { |
| 79 | PyFileIOObject *self; |
| 80 | |
| 81 | assert(type != NULL && type->tp_alloc != NULL); |
| 82 | |
| 83 | self = (PyFileIOObject *) type->tp_alloc(type, 0); |
| 84 | if (self != NULL) { |
| 85 | self->fd = -1; |
Christian Heimes | ab5f879 | 2008-10-30 21:26:15 +0000 | [diff] [blame] | 86 | self->readable = 0; |
| 87 | self->writable = 0; |
| 88 | self->seekable = -1; |
| 89 | self->closefd = 1; |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 90 | self->weakreflist = NULL; |
| 91 | } |
| 92 | |
| 93 | return (PyObject *) self; |
| 94 | } |
| 95 | |
| 96 | /* On Unix, open will succeed for directories. |
| 97 | In Python, there should be no file objects referring to |
| 98 | directories, so we need a check. */ |
| 99 | |
| 100 | static int |
| 101 | dircheck(PyFileIOObject* self) |
| 102 | { |
| 103 | #if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR) |
| 104 | struct stat buf; |
| 105 | if (self->fd < 0) |
| 106 | return 0; |
| 107 | if (fstat(self->fd, &buf) == 0 && S_ISDIR(buf.st_mode)) { |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 108 | char *msg = strerror(EISDIR); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 109 | PyObject *exc; |
| 110 | internal_close(self); |
| 111 | |
| 112 | exc = PyObject_CallFunction(PyExc_IOError, "(is)", |
| 113 | EISDIR, msg); |
| 114 | PyErr_SetObject(PyExc_IOError, exc); |
| 115 | Py_XDECREF(exc); |
| 116 | return -1; |
| 117 | } |
| 118 | #endif |
| 119 | return 0; |
| 120 | } |
| 121 | |
| 122 | |
| 123 | static int |
| 124 | fileio_init(PyObject *oself, PyObject *args, PyObject *kwds) |
| 125 | { |
| 126 | PyFileIOObject *self = (PyFileIOObject *) oself; |
| 127 | static char *kwlist[] = {"file", "mode", "closefd", NULL}; |
| 128 | char *name = NULL; |
| 129 | char *mode = "r"; |
| 130 | char *s; |
| 131 | #ifdef MS_WINDOWS |
| 132 | Py_UNICODE *widename = NULL; |
| 133 | #endif |
| 134 | int ret = 0; |
| 135 | int rwa = 0, plus = 0, append = 0; |
| 136 | int flags = 0; |
| 137 | int fd = -1; |
| 138 | int closefd = 1; |
| 139 | |
| 140 | assert(PyFileIO_Check(oself)); |
| 141 | if (self->fd >= 0) { |
| 142 | /* Have to close the existing file first. */ |
| 143 | if (internal_close(self) < 0) |
| 144 | return -1; |
| 145 | } |
| 146 | |
| 147 | if (PyArg_ParseTupleAndKeywords(args, kwds, "i|si:fileio", |
| 148 | kwlist, &fd, &mode, &closefd)) { |
| 149 | if (fd < 0) { |
| 150 | PyErr_SetString(PyExc_ValueError, |
| 151 | "Negative filedescriptor"); |
| 152 | return -1; |
| 153 | } |
| 154 | } |
| 155 | else { |
| 156 | PyErr_Clear(); |
| 157 | |
| 158 | #ifdef Py_WIN_WIDE_FILENAMES |
| 159 | if (GetVersion() < 0x80000000) { |
| 160 | /* On NT, so wide API available */ |
| 161 | PyObject *po; |
| 162 | if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:fileio", |
| 163 | kwlist, &po, &mode, &closefd) |
| 164 | ) { |
| 165 | widename = PyUnicode_AS_UNICODE(po); |
| 166 | } else { |
| 167 | /* Drop the argument parsing error as narrow |
| 168 | strings are also valid. */ |
| 169 | PyErr_Clear(); |
| 170 | } |
| 171 | } |
| 172 | if (widename == NULL) |
| 173 | #endif |
| 174 | { |
| 175 | if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:fileio", |
| 176 | kwlist, |
| 177 | Py_FileSystemDefaultEncoding, |
| 178 | &name, &mode, &closefd)) |
Neal Norwitz | 901e471 | 2008-08-24 22:03:05 +0000 | [diff] [blame] | 179 | return -1; |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 180 | } |
| 181 | } |
| 182 | |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 183 | s = mode; |
| 184 | while (*s) { |
| 185 | switch (*s++) { |
| 186 | case 'r': |
| 187 | if (rwa) { |
| 188 | bad_mode: |
| 189 | PyErr_SetString(PyExc_ValueError, |
| 190 | "Must have exactly one of read/write/append mode"); |
| 191 | goto error; |
| 192 | } |
| 193 | rwa = 1; |
| 194 | self->readable = 1; |
| 195 | break; |
| 196 | case 'w': |
| 197 | if (rwa) |
| 198 | goto bad_mode; |
| 199 | rwa = 1; |
| 200 | self->writable = 1; |
| 201 | flags |= O_CREAT | O_TRUNC; |
| 202 | break; |
| 203 | case 'a': |
| 204 | if (rwa) |
| 205 | goto bad_mode; |
| 206 | rwa = 1; |
| 207 | self->writable = 1; |
| 208 | flags |= O_CREAT; |
| 209 | append = 1; |
| 210 | break; |
| 211 | case '+': |
| 212 | if (plus) |
| 213 | goto bad_mode; |
| 214 | self->readable = self->writable = 1; |
| 215 | plus = 1; |
| 216 | break; |
| 217 | default: |
| 218 | PyErr_Format(PyExc_ValueError, |
| 219 | "invalid mode: %.200s", mode); |
| 220 | goto error; |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | if (!rwa) |
| 225 | goto bad_mode; |
| 226 | |
| 227 | if (self->readable && self->writable) |
| 228 | flags |= O_RDWR; |
| 229 | else if (self->readable) |
| 230 | flags |= O_RDONLY; |
| 231 | else |
| 232 | flags |= O_WRONLY; |
| 233 | |
| 234 | #ifdef O_BINARY |
| 235 | flags |= O_BINARY; |
| 236 | #endif |
| 237 | |
| 238 | #ifdef O_APPEND |
| 239 | if (append) |
| 240 | flags |= O_APPEND; |
| 241 | #endif |
| 242 | |
| 243 | if (fd >= 0) { |
| 244 | self->fd = fd; |
| 245 | self->closefd = closefd; |
| 246 | } |
| 247 | else { |
| 248 | self->closefd = 1; |
| 249 | if (!closefd) { |
| 250 | PyErr_SetString(PyExc_ValueError, |
Amaury Forgeot d'Arc | 9f616f4 | 2008-10-29 23:15:57 +0000 | [diff] [blame] | 251 | "Cannot use closefd=False with file name"); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 252 | goto error; |
| 253 | } |
| 254 | |
| 255 | Py_BEGIN_ALLOW_THREADS |
| 256 | errno = 0; |
| 257 | #ifdef MS_WINDOWS |
| 258 | if (widename != NULL) |
| 259 | self->fd = _wopen(widename, flags, 0666); |
| 260 | else |
| 261 | #endif |
| 262 | self->fd = open(name, flags, 0666); |
| 263 | Py_END_ALLOW_THREADS |
Benjamin Peterson | f22c26e | 2008-09-01 14:13:43 +0000 | [diff] [blame] | 264 | if (self->fd < 0) { |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 265 | #ifdef MS_WINDOWS |
| 266 | PyErr_SetFromErrnoWithUnicodeFilename(PyExc_IOError, widename); |
| 267 | #else |
| 268 | PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); |
| 269 | #endif |
| 270 | goto error; |
| 271 | } |
Benjamin Peterson | f22c26e | 2008-09-01 14:13:43 +0000 | [diff] [blame] | 272 | if(dircheck(self) < 0) |
| 273 | goto error; |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 274 | } |
| 275 | |
| 276 | goto done; |
| 277 | |
| 278 | error: |
| 279 | ret = -1; |
| 280 | |
| 281 | done: |
Neal Norwitz | 18aa388 | 2008-08-24 05:04:52 +0000 | [diff] [blame] | 282 | PyMem_Free(name); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 283 | return ret; |
| 284 | } |
| 285 | |
| 286 | static void |
| 287 | fileio_dealloc(PyFileIOObject *self) |
| 288 | { |
| 289 | if (self->weakreflist != NULL) |
| 290 | PyObject_ClearWeakRefs((PyObject *) self); |
| 291 | |
| 292 | if (self->fd >= 0 && self->closefd) { |
| 293 | errno = internal_close(self); |
| 294 | if (errno < 0) { |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 295 | PySys_WriteStderr("close failed: [Errno %d] %s\n", |
| 296 | errno, strerror(errno)); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 297 | } |
| 298 | } |
| 299 | |
| 300 | Py_TYPE(self)->tp_free((PyObject *)self); |
| 301 | } |
| 302 | |
| 303 | static PyObject * |
| 304 | err_closed(void) |
| 305 | { |
| 306 | PyErr_SetString(PyExc_ValueError, "I/O operation on closed file"); |
| 307 | return NULL; |
| 308 | } |
| 309 | |
| 310 | static PyObject * |
| 311 | err_mode(char *action) |
| 312 | { |
| 313 | PyErr_Format(PyExc_ValueError, "File not open for %s", action); |
| 314 | return NULL; |
| 315 | } |
| 316 | |
| 317 | static PyObject * |
| 318 | fileio_fileno(PyFileIOObject *self) |
| 319 | { |
| 320 | if (self->fd < 0) |
| 321 | return err_closed(); |
| 322 | return PyInt_FromLong((long) self->fd); |
| 323 | } |
| 324 | |
| 325 | static PyObject * |
| 326 | fileio_readable(PyFileIOObject *self) |
| 327 | { |
| 328 | if (self->fd < 0) |
| 329 | return err_closed(); |
| 330 | return PyBool_FromLong((long) self->readable); |
| 331 | } |
| 332 | |
| 333 | static PyObject * |
| 334 | fileio_writable(PyFileIOObject *self) |
| 335 | { |
| 336 | if (self->fd < 0) |
| 337 | return err_closed(); |
| 338 | return PyBool_FromLong((long) self->writable); |
| 339 | } |
| 340 | |
| 341 | static PyObject * |
| 342 | fileio_seekable(PyFileIOObject *self) |
| 343 | { |
| 344 | if (self->fd < 0) |
| 345 | return err_closed(); |
| 346 | if (self->seekable < 0) { |
| 347 | int ret; |
| 348 | Py_BEGIN_ALLOW_THREADS |
| 349 | ret = lseek(self->fd, 0, SEEK_CUR); |
| 350 | Py_END_ALLOW_THREADS |
| 351 | if (ret < 0) |
| 352 | self->seekable = 0; |
| 353 | else |
| 354 | self->seekable = 1; |
| 355 | } |
| 356 | return PyBool_FromLong((long) self->seekable); |
| 357 | } |
| 358 | |
| 359 | static PyObject * |
| 360 | fileio_readinto(PyFileIOObject *self, PyObject *args) |
| 361 | { |
Martin v. Löwis | f91d46a | 2008-08-12 14:49:50 +0000 | [diff] [blame] | 362 | Py_buffer pbuf; |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 363 | Py_ssize_t n; |
| 364 | |
| 365 | if (self->fd < 0) |
| 366 | return err_closed(); |
| 367 | if (!self->readable) |
| 368 | return err_mode("reading"); |
| 369 | |
Martin v. Löwis | f91d46a | 2008-08-12 14:49:50 +0000 | [diff] [blame] | 370 | if (!PyArg_ParseTuple(args, "w*", &pbuf)) |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 371 | return NULL; |
| 372 | |
| 373 | Py_BEGIN_ALLOW_THREADS |
| 374 | errno = 0; |
Martin v. Löwis | f91d46a | 2008-08-12 14:49:50 +0000 | [diff] [blame] | 375 | n = read(self->fd, pbuf.buf, pbuf.len); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 376 | Py_END_ALLOW_THREADS |
Martin v. Löwis | f91d46a | 2008-08-12 14:49:50 +0000 | [diff] [blame] | 377 | PyBuffer_Release(&pbuf); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 378 | if (n < 0) { |
| 379 | if (errno == EAGAIN) |
| 380 | Py_RETURN_NONE; |
| 381 | PyErr_SetFromErrno(PyExc_IOError); |
| 382 | return NULL; |
| 383 | } |
| 384 | |
| 385 | return PyLong_FromSsize_t(n); |
| 386 | } |
| 387 | |
| 388 | #define DEFAULT_BUFFER_SIZE (8*1024) |
| 389 | |
| 390 | static PyObject * |
| 391 | fileio_readall(PyFileIOObject *self) |
| 392 | { |
| 393 | PyObject *result; |
| 394 | Py_ssize_t total = 0; |
| 395 | int n; |
| 396 | |
Gregory P. Smith | dd96db6 | 2008-06-09 04:58:54 +0000 | [diff] [blame] | 397 | result = PyString_FromStringAndSize(NULL, DEFAULT_BUFFER_SIZE); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 398 | if (result == NULL) |
| 399 | return NULL; |
| 400 | |
| 401 | while (1) { |
| 402 | Py_ssize_t newsize = total + DEFAULT_BUFFER_SIZE; |
Gregory P. Smith | dd96db6 | 2008-06-09 04:58:54 +0000 | [diff] [blame] | 403 | if (PyString_GET_SIZE(result) < newsize) { |
| 404 | if (_PyString_Resize(&result, newsize) < 0) { |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 405 | if (total == 0) { |
| 406 | Py_DECREF(result); |
| 407 | return NULL; |
| 408 | } |
| 409 | PyErr_Clear(); |
| 410 | break; |
| 411 | } |
| 412 | } |
| 413 | Py_BEGIN_ALLOW_THREADS |
| 414 | errno = 0; |
| 415 | n = read(self->fd, |
Gregory P. Smith | dd96db6 | 2008-06-09 04:58:54 +0000 | [diff] [blame] | 416 | PyString_AS_STRING(result) + total, |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 417 | newsize - total); |
| 418 | Py_END_ALLOW_THREADS |
| 419 | if (n == 0) |
| 420 | break; |
| 421 | if (n < 0) { |
| 422 | if (total > 0) |
| 423 | break; |
| 424 | if (errno == EAGAIN) { |
| 425 | Py_DECREF(result); |
| 426 | Py_RETURN_NONE; |
| 427 | } |
| 428 | Py_DECREF(result); |
| 429 | PyErr_SetFromErrno(PyExc_IOError); |
| 430 | return NULL; |
| 431 | } |
| 432 | total += n; |
| 433 | } |
| 434 | |
Gregory P. Smith | dd96db6 | 2008-06-09 04:58:54 +0000 | [diff] [blame] | 435 | if (PyString_GET_SIZE(result) > total) { |
| 436 | if (_PyString_Resize(&result, total) < 0) { |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 437 | /* This should never happen, but just in case */ |
| 438 | Py_DECREF(result); |
| 439 | return NULL; |
| 440 | } |
| 441 | } |
| 442 | return result; |
| 443 | } |
| 444 | |
| 445 | static PyObject * |
| 446 | fileio_read(PyFileIOObject *self, PyObject *args) |
| 447 | { |
| 448 | char *ptr; |
| 449 | Py_ssize_t n; |
| 450 | Py_ssize_t size = -1; |
| 451 | PyObject *bytes; |
| 452 | |
| 453 | if (self->fd < 0) |
| 454 | return err_closed(); |
| 455 | if (!self->readable) |
| 456 | return err_mode("reading"); |
| 457 | |
| 458 | if (!PyArg_ParseTuple(args, "|n", &size)) |
| 459 | return NULL; |
| 460 | |
| 461 | if (size < 0) { |
| 462 | return fileio_readall(self); |
| 463 | } |
| 464 | |
Gregory P. Smith | dd96db6 | 2008-06-09 04:58:54 +0000 | [diff] [blame] | 465 | bytes = PyString_FromStringAndSize(NULL, size); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 466 | if (bytes == NULL) |
| 467 | return NULL; |
Gregory P. Smith | dd96db6 | 2008-06-09 04:58:54 +0000 | [diff] [blame] | 468 | ptr = PyString_AS_STRING(bytes); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 469 | |
| 470 | Py_BEGIN_ALLOW_THREADS |
| 471 | errno = 0; |
| 472 | n = read(self->fd, ptr, size); |
| 473 | Py_END_ALLOW_THREADS |
| 474 | |
| 475 | if (n < 0) { |
| 476 | if (errno == EAGAIN) |
| 477 | Py_RETURN_NONE; |
| 478 | PyErr_SetFromErrno(PyExc_IOError); |
| 479 | return NULL; |
| 480 | } |
| 481 | |
| 482 | if (n != size) { |
Gregory P. Smith | dd96db6 | 2008-06-09 04:58:54 +0000 | [diff] [blame] | 483 | if (_PyString_Resize(&bytes, n) < 0) { |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 484 | Py_DECREF(bytes); |
| 485 | return NULL; |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | return (PyObject *) bytes; |
| 490 | } |
| 491 | |
| 492 | static PyObject * |
| 493 | fileio_write(PyFileIOObject *self, PyObject *args) |
| 494 | { |
Martin v. Löwis | f91d46a | 2008-08-12 14:49:50 +0000 | [diff] [blame] | 495 | Py_buffer pbuf; |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 496 | Py_ssize_t n; |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 497 | |
| 498 | if (self->fd < 0) |
| 499 | return err_closed(); |
| 500 | if (!self->writable) |
| 501 | return err_mode("writing"); |
| 502 | |
Martin v. Löwis | f91d46a | 2008-08-12 14:49:50 +0000 | [diff] [blame] | 503 | if (!PyArg_ParseTuple(args, "s*", &pbuf)) |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 504 | return NULL; |
| 505 | |
| 506 | Py_BEGIN_ALLOW_THREADS |
| 507 | errno = 0; |
Martin v. Löwis | f91d46a | 2008-08-12 14:49:50 +0000 | [diff] [blame] | 508 | n = write(self->fd, pbuf.buf, pbuf.len); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 509 | Py_END_ALLOW_THREADS |
| 510 | |
Martin v. Löwis | f91d46a | 2008-08-12 14:49:50 +0000 | [diff] [blame] | 511 | PyBuffer_Release(&pbuf); |
| 512 | |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 513 | if (n < 0) { |
| 514 | if (errno == EAGAIN) |
| 515 | Py_RETURN_NONE; |
| 516 | PyErr_SetFromErrno(PyExc_IOError); |
| 517 | return NULL; |
| 518 | } |
| 519 | |
| 520 | return PyLong_FromSsize_t(n); |
| 521 | } |
| 522 | |
| 523 | /* XXX Windows support below is likely incomplete */ |
| 524 | |
| 525 | #if defined(MS_WIN64) || defined(MS_WINDOWS) |
| 526 | typedef PY_LONG_LONG Py_off_t; |
| 527 | #else |
| 528 | typedef off_t Py_off_t; |
| 529 | #endif |
| 530 | |
| 531 | /* Cribbed from posix_lseek() */ |
| 532 | static PyObject * |
| 533 | portable_lseek(int fd, PyObject *posobj, int whence) |
| 534 | { |
| 535 | Py_off_t pos, res; |
| 536 | |
| 537 | #ifdef SEEK_SET |
| 538 | /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */ |
| 539 | switch (whence) { |
| 540 | #if SEEK_SET != 0 |
| 541 | case 0: whence = SEEK_SET; break; |
| 542 | #endif |
| 543 | #if SEEK_CUR != 1 |
| 544 | case 1: whence = SEEK_CUR; break; |
| 545 | #endif |
| 546 | #if SEEL_END != 2 |
| 547 | case 2: whence = SEEK_END; break; |
| 548 | #endif |
| 549 | } |
| 550 | #endif /* SEEK_SET */ |
| 551 | |
| 552 | if (posobj == NULL) |
| 553 | pos = 0; |
| 554 | else { |
| 555 | if(PyFloat_Check(posobj)) { |
| 556 | PyErr_SetString(PyExc_TypeError, "an integer is required"); |
| 557 | return NULL; |
| 558 | } |
Alexandre Vassalotti | 1aed624 | 2008-05-09 21:49:43 +0000 | [diff] [blame] | 559 | #if defined(HAVE_LARGEFILE_SUPPORT) |
| 560 | pos = PyLong_AsLongLong(posobj); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 561 | #else |
Alexandre Vassalotti | 1aed624 | 2008-05-09 21:49:43 +0000 | [diff] [blame] | 562 | pos = PyLong_AsLong(posobj); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 563 | #endif |
| 564 | if (PyErr_Occurred()) |
| 565 | return NULL; |
| 566 | } |
| 567 | |
| 568 | Py_BEGIN_ALLOW_THREADS |
| 569 | #if defined(MS_WIN64) || defined(MS_WINDOWS) |
| 570 | res = _lseeki64(fd, pos, whence); |
| 571 | #else |
| 572 | res = lseek(fd, pos, whence); |
| 573 | #endif |
| 574 | Py_END_ALLOW_THREADS |
| 575 | if (res < 0) |
| 576 | return PyErr_SetFromErrno(PyExc_IOError); |
| 577 | |
Alexandre Vassalotti | 1aed624 | 2008-05-09 21:49:43 +0000 | [diff] [blame] | 578 | #if defined(HAVE_LARGEFILE_SUPPORT) |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 579 | return PyLong_FromLongLong(res); |
Alexandre Vassalotti | 1aed624 | 2008-05-09 21:49:43 +0000 | [diff] [blame] | 580 | #else |
| 581 | return PyLong_FromLong(res); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 582 | #endif |
| 583 | } |
| 584 | |
| 585 | static PyObject * |
| 586 | fileio_seek(PyFileIOObject *self, PyObject *args) |
| 587 | { |
| 588 | PyObject *posobj; |
| 589 | int whence = 0; |
| 590 | |
| 591 | if (self->fd < 0) |
| 592 | return err_closed(); |
| 593 | |
| 594 | if (!PyArg_ParseTuple(args, "O|i", &posobj, &whence)) |
| 595 | return NULL; |
| 596 | |
| 597 | return portable_lseek(self->fd, posobj, whence); |
| 598 | } |
| 599 | |
| 600 | static PyObject * |
| 601 | fileio_tell(PyFileIOObject *self, PyObject *args) |
| 602 | { |
| 603 | if (self->fd < 0) |
| 604 | return err_closed(); |
| 605 | |
| 606 | return portable_lseek(self->fd, NULL, 1); |
| 607 | } |
| 608 | |
| 609 | #ifdef HAVE_FTRUNCATE |
| 610 | static PyObject * |
| 611 | fileio_truncate(PyFileIOObject *self, PyObject *args) |
| 612 | { |
| 613 | PyObject *posobj = NULL; |
| 614 | Py_off_t pos; |
| 615 | int ret; |
| 616 | int fd; |
| 617 | |
| 618 | fd = self->fd; |
| 619 | if (fd < 0) |
| 620 | return err_closed(); |
| 621 | if (!self->writable) |
| 622 | return err_mode("writing"); |
| 623 | |
| 624 | if (!PyArg_ParseTuple(args, "|O", &posobj)) |
| 625 | return NULL; |
| 626 | |
| 627 | if (posobj == Py_None || posobj == NULL) { |
Alexandre Vassalotti | 1aed624 | 2008-05-09 21:49:43 +0000 | [diff] [blame] | 628 | /* Get the current position. */ |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 629 | posobj = portable_lseek(fd, NULL, 1); |
| 630 | if (posobj == NULL) |
Alexandre Vassalotti | 1aed624 | 2008-05-09 21:49:43 +0000 | [diff] [blame] | 631 | return NULL; |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 632 | } |
| 633 | else { |
Alexandre Vassalotti | 1aed624 | 2008-05-09 21:49:43 +0000 | [diff] [blame] | 634 | /* Move to the position to be truncated. */ |
| 635 | posobj = portable_lseek(fd, posobj, 0); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 636 | } |
| 637 | |
Alexandre Vassalotti | 1aed624 | 2008-05-09 21:49:43 +0000 | [diff] [blame] | 638 | #if defined(HAVE_LARGEFILE_SUPPORT) |
| 639 | pos = PyLong_AsLongLong(posobj); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 640 | #else |
Alexandre Vassalotti | 1aed624 | 2008-05-09 21:49:43 +0000 | [diff] [blame] | 641 | pos = PyLong_AsLong(posobj); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 642 | #endif |
Alexandre Vassalotti | 1aed624 | 2008-05-09 21:49:43 +0000 | [diff] [blame] | 643 | if (PyErr_Occurred()) |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 644 | return NULL; |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 645 | |
| 646 | #ifdef MS_WINDOWS |
| 647 | /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, |
| 648 | so don't even try using it. */ |
| 649 | { |
| 650 | HANDLE hFile; |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 651 | |
| 652 | /* Truncate. Note that this may grow the file! */ |
| 653 | Py_BEGIN_ALLOW_THREADS |
| 654 | errno = 0; |
| 655 | hFile = (HANDLE)_get_osfhandle(fd); |
| 656 | ret = hFile == (HANDLE)-1; |
| 657 | if (ret == 0) { |
| 658 | ret = SetEndOfFile(hFile) == 0; |
| 659 | if (ret) |
| 660 | errno = EACCES; |
| 661 | } |
| 662 | Py_END_ALLOW_THREADS |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 663 | } |
| 664 | #else |
| 665 | Py_BEGIN_ALLOW_THREADS |
| 666 | errno = 0; |
| 667 | ret = ftruncate(fd, pos); |
| 668 | Py_END_ALLOW_THREADS |
| 669 | #endif /* !MS_WINDOWS */ |
| 670 | |
| 671 | if (ret != 0) { |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 672 | PyErr_SetFromErrno(PyExc_IOError); |
| 673 | return NULL; |
| 674 | } |
| 675 | |
| 676 | return posobj; |
| 677 | } |
| 678 | #endif |
| 679 | |
| 680 | static char * |
| 681 | mode_string(PyFileIOObject *self) |
| 682 | { |
| 683 | if (self->readable) { |
| 684 | if (self->writable) |
| 685 | return "r+"; |
| 686 | else |
| 687 | return "r"; |
| 688 | } |
| 689 | else |
| 690 | return "w"; |
| 691 | } |
| 692 | |
| 693 | static PyObject * |
| 694 | fileio_repr(PyFileIOObject *self) |
| 695 | { |
| 696 | if (self->fd < 0) |
Gregory P. Smith | dd96db6 | 2008-06-09 04:58:54 +0000 | [diff] [blame] | 697 | return PyString_FromFormat("_fileio._FileIO(-1)"); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 698 | |
Gregory P. Smith | dd96db6 | 2008-06-09 04:58:54 +0000 | [diff] [blame] | 699 | return PyString_FromFormat("_fileio._FileIO(%d, '%s')", |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 700 | self->fd, mode_string(self)); |
| 701 | } |
| 702 | |
| 703 | static PyObject * |
| 704 | fileio_isatty(PyFileIOObject *self) |
| 705 | { |
| 706 | long res; |
| 707 | |
| 708 | if (self->fd < 0) |
| 709 | return err_closed(); |
| 710 | Py_BEGIN_ALLOW_THREADS |
| 711 | res = isatty(self->fd); |
| 712 | Py_END_ALLOW_THREADS |
| 713 | return PyBool_FromLong(res); |
| 714 | } |
| 715 | |
| 716 | |
| 717 | PyDoc_STRVAR(fileio_doc, |
| 718 | "file(name: str[, mode: str]) -> file IO object\n" |
| 719 | "\n" |
| 720 | "Open a file. The mode can be 'r', 'w' or 'a' for reading (default),\n" |
| 721 | "writing or appending. The file will be created if it doesn't exist\n" |
| 722 | "when opened for writing or appending; it will be truncated when\n" |
| 723 | "opened for writing. Add a '+' to the mode to allow simultaneous\n" |
| 724 | "reading and writing."); |
| 725 | |
| 726 | PyDoc_STRVAR(read_doc, |
| 727 | "read(size: int) -> bytes. read at most size bytes, returned as bytes.\n" |
| 728 | "\n" |
| 729 | "Only makes one system call, so less data may be returned than requested\n" |
| 730 | "In non-blocking mode, returns None if no data is available.\n" |
| 731 | "On end-of-file, returns ''."); |
| 732 | |
| 733 | PyDoc_STRVAR(readall_doc, |
| 734 | "readall() -> bytes. read all data from the file, returned as bytes.\n" |
| 735 | "\n" |
| 736 | "In non-blocking mode, returns as much as is immediately available,\n" |
| 737 | "or None if no data is available. On end-of-file, returns ''."); |
| 738 | |
| 739 | PyDoc_STRVAR(write_doc, |
| 740 | "write(b: bytes) -> int. Write bytes b to file, return number written.\n" |
| 741 | "\n" |
| 742 | "Only makes one system call, so not all of the data may be written.\n" |
| 743 | "The number of bytes actually written is returned."); |
| 744 | |
| 745 | PyDoc_STRVAR(fileno_doc, |
| 746 | "fileno() -> int. \"file descriptor\".\n" |
| 747 | "\n" |
| 748 | "This is needed for lower-level file interfaces, such the fcntl module."); |
| 749 | |
| 750 | PyDoc_STRVAR(seek_doc, |
| 751 | "seek(offset: int[, whence: int]) -> None. Move to new file position.\n" |
| 752 | "\n" |
| 753 | "Argument offset is a byte count. Optional argument whence defaults to\n" |
| 754 | "0 (offset from start of file, offset should be >= 0); other values are 1\n" |
| 755 | "(move relative to current position, positive or negative), and 2 (move\n" |
| 756 | "relative to end of file, usually negative, although many platforms allow\n" |
| 757 | "seeking beyond the end of a file)." |
| 758 | "\n" |
| 759 | "Note that not all file objects are seekable."); |
| 760 | |
| 761 | #ifdef HAVE_FTRUNCATE |
| 762 | PyDoc_STRVAR(truncate_doc, |
| 763 | "truncate([size: int]) -> None. Truncate the file to at most size bytes.\n" |
| 764 | "\n" |
Alexandre Vassalotti | 1aed624 | 2008-05-09 21:49:43 +0000 | [diff] [blame] | 765 | "Size defaults to the current file position, as returned by tell()." |
| 766 | "The current file position is changed to the value of size."); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 767 | #endif |
| 768 | |
| 769 | PyDoc_STRVAR(tell_doc, |
| 770 | "tell() -> int. Current file position"); |
| 771 | |
| 772 | PyDoc_STRVAR(readinto_doc, |
| 773 | "readinto() -> Undocumented. Don't use this; it may go away."); |
| 774 | |
| 775 | PyDoc_STRVAR(close_doc, |
| 776 | "close() -> None. Close the file.\n" |
| 777 | "\n" |
| 778 | "A closed file cannot be used for further I/O operations. close() may be\n" |
| 779 | "called more than once without error. Changes the fileno to -1."); |
| 780 | |
| 781 | PyDoc_STRVAR(isatty_doc, |
| 782 | "isatty() -> bool. True if the file is connected to a tty device."); |
| 783 | |
| 784 | PyDoc_STRVAR(seekable_doc, |
| 785 | "seekable() -> bool. True if file supports random-access."); |
| 786 | |
| 787 | PyDoc_STRVAR(readable_doc, |
| 788 | "readable() -> bool. True if file was opened in a read mode."); |
| 789 | |
| 790 | PyDoc_STRVAR(writable_doc, |
| 791 | "writable() -> bool. True if file was opened in a write mode."); |
| 792 | |
| 793 | static PyMethodDef fileio_methods[] = { |
| 794 | {"read", (PyCFunction)fileio_read, METH_VARARGS, read_doc}, |
| 795 | {"readall", (PyCFunction)fileio_readall, METH_NOARGS, readall_doc}, |
| 796 | {"readinto", (PyCFunction)fileio_readinto, METH_VARARGS, readinto_doc}, |
| 797 | {"write", (PyCFunction)fileio_write, METH_VARARGS, write_doc}, |
| 798 | {"seek", (PyCFunction)fileio_seek, METH_VARARGS, seek_doc}, |
| 799 | {"tell", (PyCFunction)fileio_tell, METH_VARARGS, tell_doc}, |
| 800 | #ifdef HAVE_FTRUNCATE |
| 801 | {"truncate", (PyCFunction)fileio_truncate, METH_VARARGS, truncate_doc}, |
| 802 | #endif |
| 803 | {"close", (PyCFunction)fileio_close, METH_NOARGS, close_doc}, |
| 804 | {"seekable", (PyCFunction)fileio_seekable, METH_NOARGS, seekable_doc}, |
| 805 | {"readable", (PyCFunction)fileio_readable, METH_NOARGS, readable_doc}, |
| 806 | {"writable", (PyCFunction)fileio_writable, METH_NOARGS, writable_doc}, |
| 807 | {"fileno", (PyCFunction)fileio_fileno, METH_NOARGS, fileno_doc}, |
| 808 | {"isatty", (PyCFunction)fileio_isatty, METH_NOARGS, isatty_doc}, |
| 809 | {NULL, NULL} /* sentinel */ |
| 810 | }; |
| 811 | |
| 812 | /* 'closed' and 'mode' are attributes for backwards compatibility reasons. */ |
| 813 | |
| 814 | static PyObject * |
| 815 | get_closed(PyFileIOObject *self, void *closure) |
| 816 | { |
| 817 | return PyBool_FromLong((long)(self->fd < 0)); |
| 818 | } |
| 819 | |
| 820 | static PyObject * |
Amaury Forgeot d'Arc | 3226565 | 2008-11-20 23:34:31 +0000 | [diff] [blame^] | 821 | get_closefd(PyFileIOObject *self, void *closure) |
| 822 | { |
| 823 | return PyBool_FromLong((long)(self->closefd)); |
| 824 | } |
| 825 | |
| 826 | static PyObject * |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 827 | get_mode(PyFileIOObject *self, void *closure) |
| 828 | { |
Gregory P. Smith | dd96db6 | 2008-06-09 04:58:54 +0000 | [diff] [blame] | 829 | return PyString_FromString(mode_string(self)); |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 830 | } |
| 831 | |
| 832 | static PyGetSetDef fileio_getsetlist[] = { |
| 833 | {"closed", (getter)get_closed, NULL, "True if the file is closed"}, |
Amaury Forgeot d'Arc | 3226565 | 2008-11-20 23:34:31 +0000 | [diff] [blame^] | 834 | {"closefd", (getter)get_closefd, NULL, |
| 835 | "True if the file descriptor will be closed"}, |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 836 | {"mode", (getter)get_mode, NULL, "String giving the file mode"}, |
| 837 | {0}, |
| 838 | }; |
| 839 | |
| 840 | PyTypeObject PyFileIO_Type = { |
Hirokazu Yamamoto | 09979a1 | 2008-09-23 16:11:09 +0000 | [diff] [blame] | 841 | PyVarObject_HEAD_INIT(NULL, 0) |
Christian Heimes | 7f39c9f | 2008-01-25 12:18:43 +0000 | [diff] [blame] | 842 | "_FileIO", |
| 843 | sizeof(PyFileIOObject), |
| 844 | 0, |
| 845 | (destructor)fileio_dealloc, /* tp_dealloc */ |
| 846 | 0, /* tp_print */ |
| 847 | 0, /* tp_getattr */ |
| 848 | 0, /* tp_setattr */ |
| 849 | 0, /* tp_compare */ |
| 850 | (reprfunc)fileio_repr, /* tp_repr */ |
| 851 | 0, /* tp_as_number */ |
| 852 | 0, /* tp_as_sequence */ |
| 853 | 0, /* tp_as_mapping */ |
| 854 | 0, /* tp_hash */ |
| 855 | 0, /* tp_call */ |
| 856 | 0, /* tp_str */ |
| 857 | PyObject_GenericGetAttr, /* tp_getattro */ |
| 858 | 0, /* tp_setattro */ |
| 859 | 0, /* tp_as_buffer */ |
| 860 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ |
| 861 | fileio_doc, /* tp_doc */ |
| 862 | 0, /* tp_traverse */ |
| 863 | 0, /* tp_clear */ |
| 864 | 0, /* tp_richcompare */ |
| 865 | offsetof(PyFileIOObject, weakreflist), /* tp_weaklistoffset */ |
| 866 | 0, /* tp_iter */ |
| 867 | 0, /* tp_iternext */ |
| 868 | fileio_methods, /* tp_methods */ |
| 869 | 0, /* tp_members */ |
| 870 | fileio_getsetlist, /* tp_getset */ |
| 871 | 0, /* tp_base */ |
| 872 | 0, /* tp_dict */ |
| 873 | 0, /* tp_descr_get */ |
| 874 | 0, /* tp_descr_set */ |
| 875 | 0, /* tp_dictoffset */ |
| 876 | fileio_init, /* tp_init */ |
| 877 | PyType_GenericAlloc, /* tp_alloc */ |
| 878 | fileio_new, /* tp_new */ |
| 879 | PyObject_Del, /* tp_free */ |
| 880 | }; |
| 881 | |
| 882 | static PyMethodDef module_methods[] = { |
| 883 | {NULL, NULL} |
| 884 | }; |
| 885 | |
| 886 | PyMODINIT_FUNC |
| 887 | init_fileio(void) |
| 888 | { |
| 889 | PyObject *m; /* a module object */ |
| 890 | |
| 891 | m = Py_InitModule3("_fileio", module_methods, |
| 892 | "Fast implementation of io.FileIO."); |
| 893 | if (m == NULL) |
| 894 | return; |
| 895 | if (PyType_Ready(&PyFileIO_Type) < 0) |
| 896 | return; |
| 897 | Py_INCREF(&PyFileIO_Type); |
| 898 | PyModule_AddObject(m, "_FileIO", (PyObject *) &PyFileIO_Type); |
| 899 | } |