This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: os: Users of path_converter don't handle fd == -1 properly
Type: behavior Stage:
Components: Versions: Python 3.7, Python 3.6
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: izbyshev, larry
Priority: normal Keywords:

Created on 2018-02-20 16:24 by izbyshev, last changed 2022-04-11 14:58 by admin.

Messages (1)
msg312421 - (view) Author: Alexey Izbyshev (izbyshev) * (Python triager) Date: 2018-02-20 16:24
Demo:
>>> import os
>>> os.chdir(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 14] Bad address: -1
>>> os.chdir(-2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 9] Bad file descriptor: -2

Functions in os supporting either path or file descriptor argument (os.supports_fd) usually use the following code pattern to distinguish between those cases:

    if (path->fd != -1)
        result = fchdir(path->fd);
    else
        result = chdir(path->narrow);

However, _fd_converter used by path_converter internally doesn't give any special meaning to -1 and allows any negative file descriptors. Therefore, if a user passes -1 to such function, path->narrow, which is NULL, will be used.

I see two ways to fix this.
1) Make some flag in path_t indicating that it should be treated as fd and make all users check that flag.
2) Make _fd_converter raise an exception for negative descriptors.

Also, I have to mention an inconsistency in reporting of bad descriptors. A handful of os functions uses fildes_converter for descriptors, which uses PyObject_AsFileDescriptor, which in turn is used in other places in Python as well (e.g. in fcntl module). PyObject_AsFileDescriptor raises a ValueError for negative descriptors instead of OSError raised by most os functions in this case.

>>> os.fchdir(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: file descriptor cannot be a negative integer (-1)
History
Date User Action Args
2022-04-11 14:58:58adminsetgithub: 77068
2018-02-20 16:28:20izbyshevsetnosy: + larry
2018-02-20 16:24:10izbyshevcreate