diff -r f4271cc2dfb5 -r 00df7fc6d2ef Doc/library/functions.rst --- a/Doc/library/functions.rst Mon Aug 19 23:19:49 2013 +0300 +++ b/Doc/library/functions.rst Mon Aug 19 23:06:45 2013 +0200 @@ -996,6 +996,9 @@ The *opener* parameter was added. The ``'x'`` mode was added. + .. versionchanged:: 3.4 + The new file descriptor is now non-inheritable. + The type of :term:`file object` returned by the :func:`open` function depends on the mode. When :func:`open` is used to open a file in a text mode (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of diff -r f4271cc2dfb5 -r 00df7fc6d2ef Doc/library/io.rst --- a/Doc/library/io.rst Mon Aug 19 23:19:49 2013 +0300 +++ b/Doc/library/io.rst Mon Aug 19 23:06:45 2013 +0200 @@ -522,6 +522,8 @@ :mod:`os.open` as *opener* results in functionality similar to passing ``None``). + The newly created file is :ref:`non-inheritable `. + See the :func:`open` built-in function for examples on using the *opener* parameter. @@ -529,6 +531,9 @@ The *opener* parameter was added. The ``'x'`` mode was added. + .. versionchanged:: 3.4 + The file is now non-inheritable. + In addition to the attributes and methods from :class:`IOBase` and :class:`RawIOBase`, :class:`FileIO` provides the following data attributes: diff -r f4271cc2dfb5 -r 00df7fc6d2ef Doc/library/os.rst --- a/Doc/library/os.rst Mon Aug 19 23:19:49 2013 +0300 +++ b/Doc/library/os.rst Mon Aug 19 23:06:45 2013 +0200 @@ -685,17 +685,29 @@ .. function:: dup(fd) - Return a duplicate of file descriptor *fd*. + Return a duplicate of file descriptor *fd*. The new file descriptor is + :ref:`non-inheritable `. + + On Windows, when duplicating a standard stream (0: stdin, 1: stdout, + 2: stderr), the new file descriptor is :ref:`inheritable + `. Availability: Unix, Windows. + .. versionchanged:: 3.4 + The new file descriptor is now non-inheritable. + .. function:: dup2(fd, fd2) Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary. + The file descriptor *fd2* is set to :ref:`non-inheritable `. Availability: Unix, Windows. + .. versionchanged:: 3.4 + *fd2* is now set to non-inheritable. + .. function:: fchmod(fd, mode) @@ -848,6 +860,7 @@ Open the file *file* and set various flags according to *flags* and possibly its mode according to *mode*. When computing *mode*, the current umask value is first masked out. Return the file descriptor for the newly opened file. + The new file descriptor is :ref:`non-inheritable `. For a description of the flag and mode values, see the C run-time documentation; flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in @@ -859,6 +872,9 @@ Availability: Unix, Windows. + .. versionchanged:: 3.4 + The new file descriptor is now non-inheritable. + .. note:: This function is intended for low-level I/O. For normal usage, use the @@ -933,20 +949,28 @@ .. index:: module: pty - Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master, - slave)`` for the pty and the tty, respectively. For a (slightly) more portable - approach, use the :mod:`pty` module. + Open a new pseudo-terminal pair. Return a pair of file descriptors + ``(master, slave)`` for the pty and the tty, respectively. The new file + descriptors are :ref:`non-inheritable `. For a (slightly) more + portable approach, use the :mod:`pty` module. Availability: some flavors of Unix. + .. versionchanged:: 3.4 + The new file descriptors are now non-inheritable. + .. function:: pipe() - Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading - and writing, respectively. + Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for + reading and writing, respectively. The new file descriptor are + :ref:`non-inheritable `. Availability: Unix, Windows. + .. versionchanged:: 3.4 + The new file descriptors are now non-inheritable. + .. function:: pipe2(flags) @@ -1178,6 +1202,42 @@ Height of the terminal window in characters. +.. _fd_inheritance: + +Inheritance of File Descriptors +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A file descriptor has a inheritable flag which indicates if the file descriptor +will be inherited or not in child processes. Since Python 3.4, file descriptors +created by Python are non-inheritable by default. + +On UNIX, file descriptors with the inheritable flag unset are be closed in +child processes at the execution (not at fork), other file descriptors are +inherited. + +On Windows, handles and file descriptors with the inheritable flag unset are +closed in child processes. There are 3 exceptions: file descriptors 0 (stdin), +1 (stdout) and 2 (stderr) are inherited. Handles with the inheritable flag set +are only inherited by child processes if the :mod:`subprocess` module is used +with *close_fds* parameter set to ``False``. All file descriptors (except 0, 1 +and 2) are always closed when using the :mod:`subprocess` module, *close_fds* +only concern handles. For :func:`os.spawn\*p\*` functions, handles and file +descriptors with the inheritable flag set are all inherited. + +.. function:: get_inheritable(fd) + + Get the inheritable flag of the specified file descriptor. Return a + :class:`bool`. + + .. versionadded:: 3.4 + +.. function:: set_inheritable(fd, inheritable) + + Set or clear the inheritable flag on the specified file descriptor. + + .. versionadded:: 3.4 + + .. _os-file-dir: Files and Directories diff -r f4271cc2dfb5 -r 00df7fc6d2ef Doc/library/select.rst --- a/Doc/library/select.rst Mon Aug 19 23:19:49 2013 +0300 +++ b/Doc/library/select.rst Mon Aug 19 23:06:45 2013 +0200 @@ -37,8 +37,13 @@ increases this value, :c:func:`devpoll` may return an incomplete list of active file descriptors. + The new file descriptor is :ref:`non-inheritable `. + .. versionadded:: 3.3 + .. versionchanged:: 3.4 + The new file descriptor is now non-inheritable. + .. function:: epoll(sizehint=-1, flags=0) (Only supported on Linux 2.5.44 and newer.) Return an edge polling object, @@ -49,11 +54,14 @@ :ref:`epoll-objects` below for the methods supported by epolling objects. They also support the :keyword:`with` statement. + The new file descriptor is :ref:`non-inheritable `. + .. versionchanged:: 3.3 Added the *flags* parameter. .. versionchanged:: 3.4 Support for the :keyword:`with` statement was added. + The new file descriptor is now non-inheritable. .. function:: poll() @@ -69,6 +77,11 @@ (Only supported on BSD.) Returns a kernel queue object; see section :ref:`kqueue-objects` below for the methods supported by kqueue objects. + The new file descriptor is :ref:`non-inheritable `. + + .. versionchanged:: 3.4 + The new file descriptor is now non-inheritable. + .. function:: kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0) @@ -199,6 +212,13 @@ block until there is an event for this poll object. +.. method:: devpoll.fileno() + + Return the file descriptor number. + + .. versionadded:: 3.4 + + .. _epoll-objects: Edge and Level Trigger Polling (epoll) Objects diff -r f4271cc2dfb5 -r 00df7fc6d2ef Doc/library/socket.rst --- a/Doc/library/socket.rst Mon Aug 19 23:19:49 2013 +0300 +++ b/Doc/library/socket.rst Mon Aug 19 23:06:45 2013 +0200 @@ -460,7 +460,7 @@ ``'udp'``, otherwise any protocol will match. -.. function:: socket([family[, type[, proto]]]) +.. function:: socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None) Create a new socket using the given address family, socket type and protocol number. The address family should be :const:`AF_INET` (the default), @@ -471,14 +471,20 @@ case where the address family is :const:`AF_CAN` the protocol should be one of :const:`CAN_RAW` or :const:`CAN_BCM`. + The newly created socket is :ref:`non-inheritable `. + .. versionchanged:: 3.3 The AF_CAN family was added. The AF_RDS family was added. - .. versionchanged:: 3.4 - The CAN_BCM protocol was added. + .. versionchanged:: 3.4 + The CAN_BCM protocol was added. -.. function:: socketpair([family[, type[, proto]]]) + .. versionchanged:: 3.4 + The socket is now non-inheritable. + + +.. function:: socketpair(family=AF_INET, type=SOCK_STREAM, proto=0) Build a pair of connected socket objects using the given address family, socket type, and protocol number. Address family, socket type, and protocol number are @@ -486,12 +492,17 @@ if defined on the platform; otherwise, the default is :const:`AF_INET`. Availability: Unix. + The newly created sockets are :ref:`non-inheritable `. + .. versionchanged:: 3.2 The returned socket objects now support the whole socket API, rather than a subset. + .. versionchanged:: 3.4 + The sockets are now non-inheritable. -.. function:: fromfd(fd, family, type[, proto]) + +.. function:: fromfd(fd, family, type, proto=0) Duplicate the file descriptor *fd* (an integer as returned by a file object's :meth:`fileno` method) and build a socket object from the result. Address @@ -730,6 +741,11 @@ *new* socket object usable to send and receive data on the connection, and *address* is the address bound to the socket on the other end of the connection. + The newly created socket is :ref:`non-inheritable `. + + .. versionchanged:: 3.4 + The socket is now non-inheritable. + .. method:: socket.bind(address) @@ -775,6 +791,16 @@ .. versionadded:: 3.2 +.. method:: socket.dup() + + Duplicate the socket. + + The newly created socket is :ref:`non-inheritable `. + + .. versionchanged:: 3.4 + The socket is now non-inheritable. + + .. method:: socket.fileno() Return the socket's file descriptor (a small integer). This is useful with diff -r f4271cc2dfb5 -r 00df7fc6d2ef Include/fileutils.h --- a/Include/fileutils.h Mon Aug 19 23:19:49 2013 +0300 +++ b/Include/fileutils.h Mon Aug 19 23:06:45 2013 +0200 @@ -27,11 +27,19 @@ struct stat *statbuf); #endif +PyAPI_FUNC(int) _Py_open( + const char *pathname, + int flags); + PyAPI_FUNC(FILE *) _Py_wfopen( const wchar_t *path, const wchar_t *mode); PyAPI_FUNC(FILE*) _Py_fopen( + const char *pathname, + const char *mode); + +PyAPI_FUNC(FILE*) _Py_fopen_obj( PyObject *path, const char *mode); @@ -53,6 +61,12 @@ wchar_t *buf, size_t size); +PyAPI_FUNC(int) _Py_get_inheritable(int fd); + +PyAPI_FUNC(int) _Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works); + +PyAPI_FUNC(void) _Py_try_set_inheritable(int fd, int inheritable); + #ifdef __cplusplus } #endif diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/http/server.py --- a/Lib/http/server.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/http/server.py Mon Aug 19 23:06:45 2013 +0200 @@ -1132,7 +1132,9 @@ except OSError: pass os.dup2(self.rfile.fileno(), 0) + os.set_inheritable(0, True) os.dup2(self.wfile.fileno(), 1) + os.set_inheritable(1, True) os.execve(scriptfile, args, env) except: self.server.handle_error(self.request, self.client_address) diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/multiprocessing/connection.py --- a/Lib/multiprocessing/connection.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/multiprocessing/connection.py Mon Aug 19 23:06:45 2013 +0200 @@ -536,7 +536,9 @@ _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE, _winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE | _winapi.PIPE_WAIT, - 1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL + 1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, + # default security descriptor: the handle cannot be inherited + _winapi.NULL ) h2 = _winapi.CreateFile( address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING, diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/pty.py --- a/Lib/pty.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/pty.py Mon Aug 19 23:06:45 2013 +0200 @@ -105,7 +105,9 @@ os.dup2(slave_fd, STDOUT_FILENO) os.dup2(slave_fd, STDERR_FILENO) if (slave_fd > STDERR_FILENO): - os.close (slave_fd) + os.close(slave_fd) + for fd in (STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO): + os.set_inheritable(fd, True) # Explicitly open the tty to make it become a controlling tty. tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR) diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/socket.py --- a/Lib/socket.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/socket.py Mon Aug 19 23:06:45 2013 +0200 @@ -137,7 +137,8 @@ def dup(self): """dup() -> socket object - Return a new socket object connected to the same system resource. + Duplicate the socket. Return a new socket object connected to the same + system resource. The new socket is non-inheritable. """ fd = dup(self.fileno()) sock = self.__class__(self.family, self.type, self.proto, fileno=fd) diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/subprocess.py --- a/Lib/subprocess.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/subprocess.py Mon Aug 19 23:06:45 2013 +0200 @@ -405,7 +405,6 @@ import select _has_poll = hasattr(select, 'poll') import _posixsubprocess - _create_pipe = _posixsubprocess.cloexec_pipe # When select or poll has indicated that the file is writable, # we can write up to _PIPE_BUF bytes without risk of blocking. @@ -1258,7 +1257,7 @@ if stdin is None: pass elif stdin == PIPE: - p2cread, p2cwrite = _create_pipe() + p2cread, p2cwrite = os.pipe() elif stdin == DEVNULL: p2cread = self._get_devnull() elif isinstance(stdin, int): @@ -1270,7 +1269,7 @@ if stdout is None: pass elif stdout == PIPE: - c2pread, c2pwrite = _create_pipe() + c2pread, c2pwrite = os.pipe() elif stdout == DEVNULL: c2pwrite = self._get_devnull() elif isinstance(stdout, int): @@ -1282,7 +1281,7 @@ if stderr is None: pass elif stderr == PIPE: - errread, errwrite = _create_pipe() + errread, errwrite = os.pipe() elif stderr == STDOUT: errwrite = c2pwrite elif stderr == DEVNULL: @@ -1334,7 +1333,7 @@ # For transferring possible exec failure from child to parent. # Data format: "exception name:hex errno:description" # Pickle is not used; it is complex and involves memory allocation. - errpipe_read, errpipe_write = _create_pipe() + errpipe_read, errpipe_write = os.pipe() try: try: # We must avoid complex work that could involve diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/tempfile.py --- a/Lib/tempfile.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/tempfile.py Mon Aug 19 23:06:45 2013 +0200 @@ -35,33 +35,12 @@ from random import Random as _Random try: - import fcntl as _fcntl -except ImportError: - def _set_cloexec(fd): - pass -else: - def _set_cloexec(fd): - try: - flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0) - except OSError: - pass - else: - # flags read successfully, modify - flags |= _fcntl.FD_CLOEXEC - _fcntl.fcntl(fd, _fcntl.F_SETFD, flags) - - -try: import _thread except ImportError: import _dummy_thread as _thread _allocate_lock = _thread.allocate_lock _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL -if hasattr(_os, 'O_CLOEXEC'): - _text_openflags |= _os.O_CLOEXEC -if hasattr(_os, 'O_NOINHERIT'): - _text_openflags |= _os.O_NOINHERIT if hasattr(_os, 'O_NOFOLLOW'): _text_openflags |= _os.O_NOFOLLOW @@ -90,8 +69,8 @@ # Fallback. All we need is something that raises OSError if the # file doesn't exist. def _stat(fn): - f = open(fn) - f.close() + fd = _os.open(fn, _os.O_RDONLY) + os.close(fd) def _exists(fn): try: @@ -217,7 +196,6 @@ file = _os.path.join(dir, pre + name + suf) try: fd = _os.open(file, flags, 0o600) - _set_cloexec(fd) return (fd, _os.path.abspath(file)) except FileExistsError: continue # try again diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/test/subprocessdata/fd_status.py --- a/Lib/test/subprocessdata/fd_status.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/test/subprocessdata/fd_status.py Mon Aug 19 23:06:45 2013 +0200 @@ -3,6 +3,7 @@ import errno import os +import stat try: _MAXFD = os.sysconf("SC_OPEN_MAX") @@ -19,6 +20,6 @@ continue raise # Ignore Solaris door files - if st.st_mode & 0xF000 != 0xd000: + if not stat.S_ISDOOR(st.st_mode): fds.append(fd) print(','.join(map(str, fds))) diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/test/subprocessdata/inherited.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Lib/test/subprocessdata/inherited.py Mon Aug 19 23:06:45 2013 +0200 @@ -0,0 +1,22 @@ +"""Similar to fd_status.py, but only checks file descriptors passed on the +command line.""" + +import errno +import os +import sys +import stat + +if __name__ == "__main__": + fds = map(int, sys.argv[1:]) + inherited = [] + for fd in fds: + try: + st = os.fstat(fd) + except OSError as e: + if e.errno == errno.EBADF: + continue + raise + # Ignore Solaris door files + if not stat.S_ISDOOR(st.st_mode): + inherited.append(fd) + print(','.join(map(str, inherited))) diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/test/test_asyncore.py --- a/Lib/test/test_asyncore.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/test/test_asyncore.py Mon Aug 19 23:06:45 2013 +0200 @@ -745,7 +745,12 @@ s.create_socket(self.family) self.assertEqual(s.socket.family, self.family) SOCK_NONBLOCK = getattr(socket, 'SOCK_NONBLOCK', 0) - self.assertEqual(s.socket.type, socket.SOCK_STREAM | SOCK_NONBLOCK) + sock_type = socket.SOCK_STREAM | SOCK_NONBLOCK + if hasattr(socket, 'SOCK_CLOEXEC'): + self.assertIn(s.socket.type, + (sock_type | socket.SOCK_CLOEXEC, sock_type)) + else: + self.assertEqual(s.socket.type, sock_type) def test_bind(self): if HAS_UNIX_SOCKETS and self.family == socket.AF_UNIX: diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/test/test_builtin.py --- a/Lib/test/test_builtin.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/test/test_builtin.py Mon Aug 19 23:06:45 2013 +0200 @@ -976,29 +976,24 @@ def write_testfile(self): # NB the first 4 lines are also used to test input, below fp = open(TESTFN, 'w') - try: + self.addCleanup(unlink, TESTFN) + with fp: fp.write('1+1\n') fp.write('The quick brown fox jumps over the lazy dog') fp.write('.\n') fp.write('Dear John\n') fp.write('XXX'*100) fp.write('YYY'*100) - finally: - fp.close() def test_open(self): self.write_testfile() - fp = open(TESTFN, 'r') - try: + with open(TESTFN, 'r') as fp: self.assertEqual(fp.readline(4), '1+1\n') self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n') self.assertEqual(fp.readline(4), 'Dear') self.assertEqual(fp.readline(100), ' John\n') self.assertEqual(fp.read(300), 'XXX'*100) self.assertEqual(fp.read(1000), 'YYY'*100) - finally: - fp.close() - unlink(TESTFN) def test_open_default_encoding(self): old_environ = dict(os.environ) @@ -1012,16 +1007,20 @@ self.write_testfile() current_locale_encoding = locale.getpreferredencoding(False) - fp = open(TESTFN, 'w') - try: + with open(TESTFN, 'w') as fp: self.assertEqual(fp.encoding, current_locale_encoding) - finally: - fp.close() - unlink(TESTFN) finally: os.environ.clear() os.environ.update(old_environ) + @unittest.skipUnless(hasattr(os, "get_inheritable"), + "need os.get_inheritable()") + def test_open_cloexec(self): + self.write_testfile() + fileobj = open(TESTFN) + with fileobj: + self.assertEqual(os.get_inheritable(fileobj.fileno()), False) + def test_ord(self): self.assertEqual(ord(' '), 32) self.assertEqual(ord('A'), 65) diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/test/test_os.py --- a/Lib/test/test_os.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/test/test_os.py Mon Aug 19 23:06:45 2013 +0200 @@ -2286,6 +2286,136 @@ else: self.skipTest("Could not determine the number of CPUs") + +@unittest.skipUnless(hasattr(os, 'get_inheritable'), "need os.get_inheritable()") +class FDInheritanceTests(unittest.TestCase): + def create_testfile(self): + fileobj = open(support.TESTFN, 'xb') + self.addCleanup(support.unlink, support.TESTFN) + fileobj.close() + + def test_get_inheritable(self): + self.create_testfile() + + fd = os.open(support.TESTFN, os.O_RDONLY) + self.addCleanup(os.close, fd) + for inheritable in (False, True): + os.set_inheritable(fd, inheritable) + self.assertEqual(os.get_inheritable(fd), inheritable) + + def test_set_inheritable(self): + self.create_testfile() + + fd = os.open(support.TESTFN, os.O_RDONLY) + self.addCleanup(os.close, fd) + os.set_inheritable(fd, True) + self.assertEqual(os.get_inheritable(fd), True) + + def test_open(self): + self.create_testfile() + + fd = os.open(support.TESTFN, os.O_RDONLY) + self.addCleanup(os.close, fd) + self.assertEqual(os.get_inheritable(fd), False) + + @unittest.skipUnless(hasattr(os, 'pipe'), "need os.pipe()") + def test_pipe_inheritable(self): + rfd, wfd = os.pipe() + self.addCleanup(os.close, rfd) + self.addCleanup(os.close, wfd) + self.assertEqual(os.get_inheritable(rfd), False) + self.assertEqual(os.get_inheritable(wfd), False) + + @unittest.skipUnless(hasattr(os, 'dup'), "need os.dup()") + def test_dup_inheritable(self): + self.create_testfile() + + for inheritable in (False, True): + fd1 = os.open(support.TESTFN, os.O_RDONLY) + try: + os.set_inheritable(fd1, not inheritable) + fd2 = os.dup(fd1) + try: + self.assertEqual(os.get_inheritable(fd2), False) + finally: + os.close(fd2) + finally: + os.close(fd1) + + @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()") + def test_dup2_inheritable(self): + self.create_testfile() + + for inheritable in (False, True): + fd1 = os.open(support.TESTFN, os.O_RDONLY) + try: + os.set_inheritable(fd1, not inheritable) + fd2 = os.open(support.TESTFN, os.O_RDONLY) + try: + os.set_inheritable(fd2, not inheritable) + os.dup2(fd1, fd2) + self.assertEqual(os.get_inheritable(fd2), False) + finally: + os.close(fd2) + finally: + os.close(fd1) + + @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()") + def test_dup2_std_inheritable(self): + new_fd = os.open(__file__, os.O_RDONLY) + self.addCleanup(os.close, new_fd) + self.assertGreater(new_fd, 2) + + for fd in (0, 1, 2): + with self.subTest("fd %s" % fd): + saved = os.dup(fd) + # On Windows, os.set_inheritable() fails with OSError(87, + # "invalid argument") on Windows console handles + if os.name != 'nt': + was_inheritable = os.get_inheritable(fd) + try: + os.dup2(new_fd, fd) + self.assertEqual(os.get_inheritable(fd), False) + finally: + os.dup2(saved, fd) + if os.name != 'nt': + os.set_inheritable(fd, was_inheritable) + os.close(saved) + + @unittest.skipUnless(hasattr(os, 'dup2'), "need os.dup2()") + def test_dup2_non_inheritable(self): + old_fd = os.open(__file__, os.O_RDONLY) + self.addCleanup(os.close, old_fd) + self.assertGreater(old_fd, 2) + + new_fd = os.open(__file__, os.O_RDONLY) + self.addCleanup(os.close, new_fd) + self.assertGreater(new_fd, 2) + self.assertNotEqual(old_fd, new_fd) + + for old_inheritable in (False, True): + # os.dup2(fd, fd) must make fd non-inheritable + os.set_inheritable(old_fd, old_inheritable) + os.dup2(old_fd, old_fd) + self.assertEqual(os.get_inheritable(old_fd), False) + + for new_inheritable in (False, True): + os.set_inheritable(old_fd, old_inheritable) + os.set_inheritable(new_fd, new_inheritable) + + # os.dup2(fd, fd2) must make fd2 non-inheritable + os.dup2(old_fd, new_fd) + self.assertEqual(os.get_inheritable(new_fd), False) + + @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()") + def test_openpty_inheritable(self): + master_fd, slave_fd = os.openpty() + self.addCleanup(os.close, master_fd) + self.addCleanup(os.close, slave_fd) + self.assertEqual(os.get_inheritable(master_fd), False) + self.assertEqual(os.get_inheritable(slave_fd), False) + + @support.reap_threads def test_main(): support.run_unittest( @@ -2318,6 +2448,7 @@ OSErrorTests, RemoveDirsTests, CPUCountTests, + FDInheritanceTests, ) if __name__ == "__main__": diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/test/test_select.py --- a/Lib/test/test_select.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/test/test_select.py Mon Aug 19 23:06:45 2013 +0200 @@ -75,8 +75,30 @@ a[:] = [F()] * 10 self.assertEqual(select.select([], a, []), ([], a[:5], [])) + +@unittest.skipUnless(hasattr(os, 'get_inheritable'), + "need os.get_inheritable()") +class FDInheritanceTests(unittest.TestCase): + @unittest.skipUnless(hasattr(select, 'devpoll'), "need select.devpoll()") + def test_devpoll_inheritance(self): + devpoll = select.devpoll() + self.assertEqual(os.get_inheritable(devpoll.fileno()), False) + devpoll = None + + @unittest.skipUnless(hasattr(select, 'epoll'), "need select.epoll()") + def test_epoll_inheritance(self): + epoll = select.epoll() + with epoll: + self.assertEqual(os.get_inheritable(epoll.fileno()), False) + + @unittest.skipUnless(hasattr(select, 'kqueue'), "need select.kqueue()") + def test_kqueue_inheritance(self): + kqueue = select.kqueue() + self.assertEqual(os.get_inheritable(kqueue.fileno()), False) + + def test_main(): - support.run_unittest(SelectTestCase) + support.run_unittest(SelectTestCase, FDInheritanceTests) support.reap_children() if __name__ == "__main__": diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/test/test_socket.py --- a/Lib/test/test_socket.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/test/test_socket.py Mon Aug 19 23:06:45 2013 +0200 @@ -23,10 +23,6 @@ import pickle import struct try: - import fcntl -except ImportError: - fcntl = False -try: import multiprocessing except ImportError: multiprocessing = False @@ -1108,9 +1104,15 @@ def testNewAttributes(self): # testing .family, .type and .protocol + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.assertEqual(sock.family, socket.AF_INET) - self.assertEqual(sock.type, socket.SOCK_STREAM) + if hasattr(socket, 'SOCK_CLOEXEC'): + self.assertIn(sock.type, + (socket.SOCK_STREAM | socket.SOCK_CLOEXEC, + socket.SOCK_STREAM)) + else: + self.assertEqual(sock.type, socket.SOCK_STREAM) self.assertEqual(sock.proto, 0) sock.close() @@ -4748,16 +4750,52 @@ self.assertRaises(OSError, sock.sendall, b'foo') -@unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"), - "SOCK_CLOEXEC not defined") -@unittest.skipUnless(fcntl, "module fcntl not available") -class CloexecConstantTest(unittest.TestCase): +@unittest.skipUnless(hasattr(os, 'get_inheritable'), + "need os.get_inheritable()") +class InheritanceTest(unittest.TestCase): + @unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"), + "SOCK_CLOEXEC not defined") @support.requires_linux_version(2, 6, 28) def test_SOCK_CLOEXEC(self): with socket.socket(socket.AF_INET, socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s: self.assertTrue(s.type & socket.SOCK_CLOEXEC) - self.assertTrue(fcntl.fcntl(s, fcntl.F_GETFD) & fcntl.FD_CLOEXEC) + self.assertTrue(os.get_inheritable(sock.fileno())) + + def test_socket_inheritance(self): + sock = socket.socket() + with sock: + self.assertEqual(os.get_inheritable(sock.fileno()), False) + + def test_dup_inheritance(self): + for inheritable in (False, True): + sock = socket.socket() + with sock: + os.set_inheritable(sock.fileno(), inheritable) + newsock = sock.dup() + sock.close() + self.assertEqual(os.get_inheritable(newsock.fileno()), False) + newsock.close() + + def test_socket_set_inheritable(self): + sock = socket.socket() + with sock: + # On Windows, fileno() returns an handle, not a file descriptor. + # Check if it is accepted. + os.set_inheritable(sock.fileno(), False) + self.assertEqual(os.get_inheritable(sock.fileno()), False) + + os.set_inheritable(sock.fileno(), True) + self.assertEqual(os.get_inheritable(sock.fileno()), True) + + @unittest.skipUnless(hasattr(socket, "socketpair"), + "need socket.socketpair()") + def test_socketpair_inheritance(self): + s1, s2 = socket.socketpair() + self.assertEqual(os.get_inheritable(s1.fileno()), False) + self.assertEqual(os.get_inheritable(s2.fileno()), False) + s1.close() + s2.close() @unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"), @@ -4926,7 +4964,7 @@ NetworkConnectionAttributesTest, NetworkConnectionBehaviourTest, ContextManagersTest, - CloexecConstantTest, + InheritanceTest, NonblockConstantTest ]) if hasattr(socket, "socketpair"): diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/test/test_subprocess.py --- a/Lib/test/test_subprocess.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/test/test_subprocess.py Mon Aug 19 23:06:45 2013 +0200 @@ -1501,16 +1501,29 @@ # Terminating a dead process self._kill_dead_process('terminate') + def _save_fds(self, save_fds): + fds = [] + for fd in save_fds: + inheritable = os.get_inheritable(fd) + saved = os.dup(fd) + fds.append((fd, saved, inheritable)) + return fds + + def _restore_fds(self, fds): + for fd, saved, inheritable in fds: + os.dup2(saved, fd) + os.set_inheritable(fd, inheritable) + os.close(saved) + def check_close_std_fds(self, fds): # Issue #9905: test that subprocess pipes still work properly with # some standard fds closed stdin = 0 - newfds = [] - for a in fds: - b = os.dup(a) - newfds.append(b) - if a == 0: - stdin = b + saved_fds = self._save_fds(fds) + for fd, saved, inheritable in saved_fds: + if fd == 0: + stdin = saved + break try: for fd in fds: os.close(fd) @@ -1525,10 +1538,7 @@ err = support.strip_python_stderr(err) self.assertEqual((out, err), (b'apple', b'orange')) finally: - for b, a in zip(newfds, fds): - os.dup2(b, a) - for b in newfds: - os.close(b) + self._restore_fds(saved_fds) def test_close_fd_0(self): self.check_close_std_fds([0]) @@ -1568,7 +1578,7 @@ os.lseek(temp_fds[1], 0, 0) # move the standard file descriptors out of the way - saved_fds = [os.dup(fd) for fd in range(3)] + saved_fds = self._save_fds(range(3)) try: # duplicate the file objects over the standard fd's for fd, temp_fd in enumerate(temp_fds): @@ -1584,10 +1594,7 @@ stderr=temp_fds[0]) p.wait() finally: - # restore the original fd's underneath sys.stdin, etc. - for std, saved in enumerate(saved_fds): - os.dup2(saved, std) - os.close(saved) + self._restore_fds(saved_fds) for fd in temp_fds: os.lseek(fd, 0, 0) @@ -1611,7 +1618,7 @@ os.unlink(fname) # save a copy of the standard file descriptors - saved_fds = [os.dup(fd) for fd in range(3)] + saved_fds = self._save_fds(range(3)) try: # duplicate the temp files over the standard fd's 0, 1, 2 for fd, temp_fd in enumerate(temp_fds): @@ -1637,9 +1644,7 @@ out = os.read(stdout_no, 1024) err = support.strip_python_stderr(os.read(stderr_no, 1024)) finally: - for std, saved in enumerate(saved_fds): - os.dup2(saved, std) - os.close(saved) + self._restore_fds(saved_fds) self.assertEqual(out, b"got STDIN") self.assertEqual(err, b"err") @@ -1810,6 +1815,9 @@ self.addCleanup(os.close, fd) open_fds.add(fd) + for fd in open_fds: + os.set_inheritable(fd, True) + p = subprocess.Popen([sys.executable, fd_status], stdout=subprocess.PIPE, close_fds=False) output, ignored = p.communicate() @@ -1854,6 +1862,8 @@ fds = os.pipe() self.addCleanup(os.close, fds[0]) self.addCleanup(os.close, fds[1]) + os.set_inheritable(fds[0], True) + os.set_inheritable(fds[1], True) open_fds.update(fds) for fd in open_fds: @@ -1876,6 +1886,32 @@ close_fds=False, pass_fds=(fd, ))) self.assertIn('overriding close_fds', str(context.warning)) + def test_pass_fds_inheritable(self): + script = support.findfile("inherited.py", subdir="subprocessdata") + + inheritable, non_inheritable = os.pipe() + self.addCleanup(os.close, inheritable) + self.addCleanup(os.close, non_inheritable) + os.set_inheritable(inheritable, True) + os.set_inheritable(non_inheritable, False) + pass_fds = (inheritable, non_inheritable) + args = [sys.executable, script] + args += list(map(str, pass_fds)) + + p = subprocess.Popen(args, + stdout=subprocess.PIPE, close_fds=True, + pass_fds=pass_fds) + output, ignored = p.communicate() + fds = set(map(int, output.split(b','))) + + # the inheritable file descriptor must be inherited, so its inheritable + # flag must be set in the child process after fork() and before exec() + self.assertEqual(fds, set(pass_fds)) + + # inheritable flag must not be changed in the parent process + self.assertEqual(os.get_inheritable(inheritable), True) + self.assertEqual(os.get_inheritable(non_inheritable), False) + def test_stdout_stdin_are_single_inout_fd(self): with io.open(os.devnull, "r+") as inout: p = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"], diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/test/test_tempfile.py --- a/Lib/test/test_tempfile.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/test/test_tempfile.py Mon Aug 19 23:06:45 2013 +0200 @@ -333,6 +333,8 @@ v="q" file = self.do_create() + if hasattr(os, 'get_inheritable'): + self.assertEqual(os.get_inheritable(file.fd), False) fd = "%d" % file.fd try: diff -r f4271cc2dfb5 -r 00df7fc6d2ef Lib/xmlrpc/server.py --- a/Lib/xmlrpc/server.py Mon Aug 19 23:19:49 2013 +0300 +++ b/Lib/xmlrpc/server.py Mon Aug 19 23:06:45 2013 +0200 @@ -584,13 +584,6 @@ SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types) socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate) - # [Bug #1222790] If possible, set close-on-exec flag; if a - # method spawns a subprocess, the subprocess shouldn't have - # the listening socket open. - if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'): - flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD) - flags |= fcntl.FD_CLOEXEC - fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags) class MultiPathXMLRPCServer(SimpleXMLRPCServer): """Multipath XML-RPC Server diff -r f4271cc2dfb5 -r 00df7fc6d2ef Modules/_cursesmodule.c --- a/Modules/_cursesmodule.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Modules/_cursesmodule.c Mon Aug 19 23:06:45 2013 +0200 @@ -1702,6 +1702,7 @@ fd = mkstemp(fn); if (fd < 0) return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + _Py_try_set_inheritable(fd, 0); fp = fdopen(fd, "wb+"); if (fp == NULL) { close(fd); @@ -2265,6 +2266,7 @@ fd = mkstemp(fn); if (fd < 0) return PyErr_SetFromErrnoWithFilename(PyExc_IOError, fn); + _Py_try_set_inheritable(fd, 0); fp = fdopen(fd, "wb+"); if (fp == NULL) { close(fd); diff -r f4271cc2dfb5 -r 00df7fc6d2ef Modules/_io/fileio.c --- a/Modules/_io/fileio.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Modules/_io/fileio.c Mon Aug 19 23:06:45 2013 +0200 @@ -202,6 +202,9 @@ return 0; } +#ifdef O_CLOEXEC +extern int _Py_open_cloexec_works; +#endif static int fileio_init(PyObject *oself, PyObject *args, PyObject *kwds) @@ -221,6 +224,11 @@ int fd = -1; int closefd = 1; int fd_is_own = 0; +#ifdef O_CLOEXEC + int *atomic_flag_works = &_Py_open_cloexec_works; +#else + int *atomic_flag_works = NULL; +#endif assert(PyFileIO_Check(oself)); if (self->fd >= 0) { @@ -345,6 +353,11 @@ if (append) flags |= O_APPEND; #endif +#ifdef MS_WINDOWS + flags |= O_NOINHERIT; +#elif defined(O_CLOEXEC) + flags |= O_CLOEXEC; +#endif if (fd >= 0) { if (check_fd(fd)) @@ -369,10 +382,16 @@ else #endif self->fd = open(name, flags, 0666); + Py_END_ALLOW_THREADS - } else { - PyObject *fdobj = PyObject_CallFunction( - opener, "Oi", nameobj, flags); + } + else { + PyObject *fdobj; + + /* the opener may clear the atomic flag */ + atomic_flag_works = NULL; + + fdobj = PyObject_CallFunction(opener, "Oi", nameobj, flags); if (fdobj == NULL) goto error; if (!PyLong_Check(fdobj)) { @@ -394,6 +413,11 @@ PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, nameobj); goto error; } + +#ifndef MS_WINDOWS + if (_Py_set_inheritable(self->fd, 0, atomic_flag_works) < 0) + goto error; +#endif } if (dircheck(self, nameobj) < 0) goto error; diff -r f4271cc2dfb5 -r 00df7fc6d2ef Modules/_posixsubprocess.c --- a/Modules/_posixsubprocess.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Modules/_posixsubprocess.c Mon Aug 19 23:06:45 2013 +0200 @@ -35,7 +35,7 @@ # define FD_DIR "/proc/self/fd" #endif -#define POSIX_CALL(call) if ((call) == -1) goto error +#define POSIX_CALL(call) do { if ((call) == -1) goto error; } while (0) /* Maximum file descriptor, initialized on module load. */ @@ -87,7 +87,7 @@ if (stat("/dev", &dev_stat) != 0) return 0; if (stat(FD_DIR, &dev_fd_stat) != 0) - return 0; + return 0; if (dev_stat.st_dev == dev_fd_stat.st_dev) return 0; /* / == /dev == /dev/fd means it is static. #fail */ return 1; @@ -136,6 +136,29 @@ return 0; } +static int +make_inheritable(PyObject *py_fds_to_keep, int errpipe_write) +{ + Py_ssize_t i, len; + + len = PySequence_Length(py_fds_to_keep); + for (i = 0; i < len; ++i) { + PyObject* fdobj = PySequence_Fast_GET_ITEM(py_fds_to_keep, i); + long fd = PyLong_AsLong(fdobj); + assert(!PyErr_Occurred()); + assert(0 <= fd && fd <= INT_MAX); + if (fd == errpipe_write) { + /* errpipe_write is part of py_fds_to_keep. It must be closed at + exec(), but kept open in the child process until exec() is + called. */ + continue; + } + if (_Py_set_inheritable((int)fd, 1, NULL) < 0) + return -1; + } + return 0; +} + /* Close all file descriptors in the range start_fd inclusive to * end_fd exclusive except for those in py_fds_to_keep. If the @@ -205,18 +228,8 @@ int fd_dir_fd; if (start_fd >= end_fd) return; -#ifdef O_CLOEXEC - fd_dir_fd = open(FD_DIR, O_RDONLY | O_CLOEXEC, 0); -#else - fd_dir_fd = open(FD_DIR, O_RDONLY, 0); -#ifdef FD_CLOEXEC - { - int old = fcntl(fd_dir_fd, F_GETFD); - if (old != -1) - fcntl(fd_dir_fd, F_SETFD, old | FD_CLOEXEC); - } -#endif -#endif + + fd_dir_fd = _Py_open(FD_DIR, O_RDONLY); if (fd_dir_fd == -1) { /* No way to get a list of open fds. */ _close_fds_by_brute_force(start_fd, end_fd, py_fds_to_keep); @@ -356,16 +369,16 @@ /* Buffer large enough to hold a hex integer. We can't malloc. */ char hex_errno[sizeof(saved_errno)*2+1]; + if (make_inheritable(py_fds_to_keep, errpipe_write) < 0) + goto error; + /* Close parent's pipe ends. */ - if (p2cwrite != -1) { + if (p2cwrite != -1) POSIX_CALL(close(p2cwrite)); - } - if (c2pread != -1) { + if (c2pread != -1) POSIX_CALL(close(c2pread)); - } - if (errread != -1) { + if (errread != -1) POSIX_CALL(close(errread)); - } POSIX_CALL(close(errpipe_read)); /* When duping fds, if there arises a situation where one of the fds is @@ -378,39 +391,27 @@ /* Dup fds for child. dup2() removes the CLOEXEC flag but we must do it ourselves if dup2() would be a no-op (issue #10806). */ - if (p2cread == 0) { - int old = fcntl(p2cread, F_GETFD); - if (old != -1) - fcntl(p2cread, F_SETFD, old & ~FD_CLOEXEC); - } else if (p2cread != -1) { + if (p2cread == 0) + _Py_try_set_inheritable(p2cread, 1); + else if (p2cread != -1) POSIX_CALL(dup2(p2cread, 0)); /* stdin */ - } - if (c2pwrite == 1) { - int old = fcntl(c2pwrite, F_GETFD); - if (old != -1) - fcntl(c2pwrite, F_SETFD, old & ~FD_CLOEXEC); - } else if (c2pwrite != -1) { + if (c2pwrite == 1) + _Py_try_set_inheritable(c2pwrite, 1); + else if (c2pwrite != -1) POSIX_CALL(dup2(c2pwrite, 1)); /* stdout */ - } - if (errwrite == 2) { - int old = fcntl(errwrite, F_GETFD); - if (old != -1) - fcntl(errwrite, F_SETFD, old & ~FD_CLOEXEC); - } else if (errwrite != -1) { + if (errwrite == 2) + _Py_try_set_inheritable(errwrite, 1); + else if (errwrite != -1) POSIX_CALL(dup2(errwrite, 2)); /* stderr */ - } /* Close pipe fds. Make sure we don't close the same fd more than */ /* once, or standard fds. */ - if (p2cread > 2) { + if (p2cread > 2) POSIX_CALL(close(p2cread)); - } - if (c2pwrite > 2 && c2pwrite != p2cread) { + if (c2pwrite > 2 && c2pwrite != p2cread) POSIX_CALL(close(c2pwrite)); - } - if (errwrite != c2pwrite && errwrite != p2cread && errwrite > 2) { + if (errwrite != c2pwrite && errwrite != p2cread && errwrite > 2) POSIX_CALL(close(errwrite)); - } if (close_fds) { int local_max_fd = max_fd; @@ -543,7 +544,7 @@ PyObject *result; _Py_IDENTIFIER(isenabled); _Py_IDENTIFIER(disable); - + gc_module = PyImport_ImportModule("gc"); if (gc_module == NULL) return NULL; @@ -720,52 +721,6 @@ Raises: Only on an error in the parent process.\n\ "); -PyDoc_STRVAR(subprocess_cloexec_pipe_doc, -"cloexec_pipe() -> (read_end, write_end)\n\n\ -Create a pipe whose ends have the cloexec flag set."); - -static PyObject * -subprocess_cloexec_pipe(PyObject *self, PyObject *noargs) -{ - int fds[2]; - int res; -#ifdef HAVE_PIPE2 - Py_BEGIN_ALLOW_THREADS - res = pipe2(fds, O_CLOEXEC); - Py_END_ALLOW_THREADS - if (res != 0 && errno == ENOSYS) - { - { -#endif - /* We hold the GIL which offers some protection from other code calling - * fork() before the CLOEXEC flags have been set but we can't guarantee - * anything without pipe2(). */ - long oldflags; - - res = pipe(fds); - - if (res == 0) { - oldflags = fcntl(fds[0], F_GETFD, 0); - if (oldflags < 0) res = oldflags; - } - if (res == 0) - res = fcntl(fds[0], F_SETFD, oldflags | FD_CLOEXEC); - - if (res == 0) { - oldflags = fcntl(fds[1], F_GETFD, 0); - if (oldflags < 0) res = oldflags; - } - if (res == 0) - res = fcntl(fds[1], F_SETFD, oldflags | FD_CLOEXEC); -#ifdef HAVE_PIPE2 - } - } -#endif - if (res != 0) - return PyErr_SetFromErrno(PyExc_OSError); - return Py_BuildValue("(ii)", fds[0], fds[1]); -} - /* module level code ********************************************************/ PyDoc_STRVAR(module_doc, @@ -774,7 +729,6 @@ static PyMethodDef module_methods[] = { {"fork_exec", subprocess_fork_exec, METH_VARARGS, subprocess_fork_exec_doc}, - {"cloexec_pipe", subprocess_cloexec_pipe, METH_NOARGS, subprocess_cloexec_pipe_doc}, {NULL, NULL} /* sentinel */ }; diff -r f4271cc2dfb5 -r 00df7fc6d2ef Modules/_ssl.c --- a/Modules/_ssl.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Modules/_ssl.c Mon Aug 19 23:06:45 2013 +0200 @@ -2345,7 +2345,7 @@ FILE *f; DH *dh; - f = _Py_fopen(filepath, "rb"); + f = _Py_fopen_obj(filepath, "rb"); if (f == NULL) { if (!PyErr_Occurred()) PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath); diff -r f4271cc2dfb5 -r 00df7fc6d2ef Modules/main.c --- a/Modules/main.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Modules/main.c Mon Aug 19 23:06:45 2013 +0200 @@ -22,6 +22,10 @@ #include #endif +#ifdef HAVE_FCNTL_H +#include +#endif /* HAVE_FCNTL_H */ + #if defined(MS_WINDOWS) #define PYTHONHOMEHELP "\\lib" #else @@ -143,7 +147,7 @@ { char *startup = Py_GETENV("PYTHONSTARTUP"); if (startup != NULL && startup[0] != '\0') { - FILE *fp = fopen(startup, "r"); + FILE *fp = _Py_fopen(startup, "r"); if (fp != NULL) { (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf); PyErr_Clear(); diff -r f4271cc2dfb5 -r 00df7fc6d2ef Modules/mmapmodule.c --- a/Modules/mmapmodule.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Modules/mmapmodule.c Mon Aug 19 23:06:45 2013 +0200 @@ -1208,7 +1208,7 @@ flags |= MAP_ANONYMOUS; #else /* SVR4 method to map anonymous memory is to open /dev/zero */ - fd = devzero = open("/dev/zero", O_RDWR); + fd = devzero = _Py_open("/dev/zero", O_RDWR); if (devzero == -1) { Py_DECREF(m_obj); PyErr_SetFromErrno(PyExc_OSError); @@ -1222,6 +1222,7 @@ PyErr_SetFromErrno(PyExc_OSError); return NULL; } + _Py_try_set_inheritable(m_obj->fd, 0); } m_obj->data = mmap(NULL, map_size, diff -r f4271cc2dfb5 -r 00df7fc6d2ef Modules/ossaudiodev.c --- a/Modules/ossaudiodev.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Modules/ossaudiodev.c Mon Aug 19 23:06:45 2013 +0200 @@ -115,7 +115,9 @@ one open at a time. This does *not* affect later I/O; OSS provides a special ioctl() for non-blocking read/write, which is exposed via oss_nonblock() below. */ - if ((fd = open(devicename, imode|O_NONBLOCK)) == -1) { + fd = _Py_open(devicename, imode|O_NONBLOCK); + + if (fd == -1) { PyErr_SetFromErrnoWithFilename(PyExc_IOError, devicename); return NULL; } @@ -177,7 +179,8 @@ devicename = "/dev/mixer"; } - if ((fd = open(devicename, O_RDWR)) == -1) { + fd = _Py_open(devicename, O_RDWR); + if (fd == -1) { PyErr_SetFromErrnoWithFilename(PyExc_IOError, devicename); return NULL; } diff -r f4271cc2dfb5 -r 00df7fc6d2ef Modules/posixmodule.c --- a/Modules/posixmodule.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Modules/posixmodule.c Mon Aug 19 23:06:45 2013 +0200 @@ -3543,6 +3543,8 @@ /* closedir() closes the FD, so we duplicate it */ Py_BEGIN_ALLOW_THREADS fd = dup(path->fd); + if (fd != -1) + _Py_try_set_inheritable(fd, 0); Py_END_ALLOW_THREADS if (fd == -1) { @@ -5774,8 +5776,9 @@ static PyObject * posix_openpty(PyObject *self, PyObject *noargs) { - int master_fd, slave_fd; + int master_fd = -1, slave_fd = -1; #ifndef HAVE_OPENPTY + int flags; char * slave_name; #endif #if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY) @@ -5788,18 +5791,40 @@ #ifdef HAVE_OPENPTY if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0) return posix_error(); + + if (_Py_set_inheritable(master_fd, 0, NULL) < 0) + goto error; + if (_Py_set_inheritable(slave_fd, 0, NULL) < 0) + goto error; + #elif defined(HAVE__GETPTY) slave_name = _getpty(&master_fd, O_RDWR, 0666, 0); if (slave_name == NULL) return posix_error(); - - slave_fd = open(slave_name, O_RDWR); + if (_Py_set_inheritable(master_fd, 0, NULL) < 0) + goto error; + + flags = O_RDWR; +#ifdef O_CLOEXEC + flags |= O_CLOEXEC; +#endif + slave_fd = open(slave_name, flags); if (slave_fd < 0) return posix_error(); -#else - master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */ + if (_Py_set_inheritable(slave_fd, 0, NULL) < 0) + goto error; + +#else + flags = O_RDWR | O_NOCTTY; +#ifdef O_CLOEXEC + flags |= O_CLOEXEC; +#endif + master_fd = open(DEV_PTY_FILE, flags); /* open master */ if (master_fd < 0) return posix_error(); + if (_Py_set_inheritable(master_fd, 0, NULL) < 0) + goto error; + sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL); /* change permission of slave */ if (grantpt(master_fd) < 0) { @@ -5815,9 +5840,15 @@ slave_name = ptsname(master_fd); /* get name of slave */ if (slave_name == NULL) return posix_error(); - slave_fd = open(slave_name, O_RDWR | O_NOCTTY); /* open slave */ + flags = O_RDWR | O_NOCTTY; +#ifdef O_CLOEXEC + flags |= O_CLOEXEC; +#endif + slave_fd = open(slave_name, flags); /* open slave */ if (slave_fd < 0) return posix_error(); + if (_Py_set_inheritable(slave_fd, 0, NULL) < 0) + goto error; #if !defined(__CYGWIN__) && !defined(HAVE_DEV_PTC) ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */ ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */ @@ -5829,6 +5860,12 @@ return Py_BuildValue("(ii)", master_fd, slave_fd); +error: + if (master_fd != -1) + close(master_fd); + if (slave_fd != -1) + close(slave_fd); + return NULL; } #endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */ @@ -7438,6 +7475,10 @@ /* Functions acting on file descriptors */ +#ifdef O_CLOEXEC +extern int _Py_open_cloexec_works; +#endif + PyDoc_STRVAR(posix_open__doc__, "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\ Open a file for low level IO. Returns a file handle (integer).\n\ @@ -7457,6 +7498,13 @@ int fd; PyObject *return_value = NULL; static char *keywords[] = {"path", "flags", "mode", "dir_fd", NULL}; +#ifndef MS_WINDOWS +#ifdef O_CLOEXEC + int *atomic_flag_works = &_Py_open_cloexec_works; +#else + int *atomic_flag_works = NULL; +#endif +#endif memset(&path, 0, sizeof(path)); path.function_name = "open"; @@ -7471,6 +7519,12 @@ )) return NULL; +#ifdef MS_WINDOWS + flags |= O_NOINHERIT; +#elif defined(O_CLOEXEC) + flags |= O_CLOEXEC; +#endif + Py_BEGIN_ALLOW_THREADS #ifdef MS_WINDOWS if (path.wide) @@ -7490,6 +7544,13 @@ goto exit; } +#ifndef MS_WINDOWS + if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) { + close(fd); + goto exit; + } +#endif + return_value = PyLong_FromLong((long)fd); exit: @@ -7546,13 +7607,58 @@ posix_dup(PyObject *self, PyObject *args) { int fd; +#ifdef MS_WINDOWS + HANDLE handle; + DWORD ftype; +#endif + if (!PyArg_ParseTuple(args, "i:dup", &fd)) return NULL; + if (!_PyVerify_fd(fd)) return posix_error(); + +#ifdef MS_WINDOWS + handle = (HANDLE)_get_osfhandle(fd); + if (handle == INVALID_HANDLE_VALUE) { + PyErr_SetFromWindowsErr(0); + return NULL; + } + + /* get the file type, ignore error */ + ftype = GetFileType(handle); + + Py_BEGIN_ALLOW_THREADS fd = dup(fd); + Py_END_ALLOW_THREADS if (fd < 0) return posix_error(); + + /* Character files like console cannot be make non-inheritable */ + if (ftype != FILE_TYPE_CHAR) { + if (_Py_set_inheritable(fd, 0, NULL) < 0) { + close(fd); + return NULL; + } + } +#elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC) + Py_BEGIN_ALLOW_THREADS + fd = fcntl(fd, F_DUPFD_CLOEXEC, 0); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error(); + +#else + Py_BEGIN_ALLOW_THREADS + fd = dup(fd); + Py_END_ALLOW_THREADS + if (fd < 0) + return posix_error(); + if (_Py_set_inheritable(fd, 0, NULL) < 0) { + close(fd); + return NULL; + } +#endif return PyLong_FromLong((long)fd); } @@ -7565,13 +7671,75 @@ posix_dup2(PyObject *self, PyObject *args) { int fd, fd2, res; +#ifdef MS_WINDOWS + HANDLE handle; + DWORD ftype; +#elif defined(HAVE_DUP3) + /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */ + int dup3_works = -1; +#endif + if (!PyArg_ParseTuple(args, "ii:dup2", &fd, &fd2)) return NULL; if (!_PyVerify_fd_dup2(fd, fd2)) return posix_error(); + +#ifdef MS_WINDOWS + handle = (HANDLE)_get_osfhandle(fd); + if (handle == INVALID_HANDLE_VALUE) { + PyErr_SetFromWindowsErr(0); + return NULL; + } + + /* get the file type, ignore error */ + ftype = GetFileType(handle); + + Py_BEGIN_ALLOW_THREADS res = dup2(fd, fd2); + Py_END_ALLOW_THREADS if (res < 0) return posix_error(); + + /* Character files like console cannot be make non-inheritable */ + if (ftype != FILE_TYPE_CHAR) { + if (_Py_set_inheritable(fd2, 0, NULL) < 0) { + close(fd2); + return NULL; + } + } +#else + +#ifdef HAVE_DUP3 + if (dup3_works != 0) { + Py_BEGIN_ALLOW_THREADS + res = dup3(fd, fd2, O_CLOEXEC); + Py_END_ALLOW_THREADS + if (res < 0) { + if (dup3_works == -1) + dup3_works = (errno != ENOSYS); + if (dup3_works) + return posix_error(); + } + } + + if (dup3_works == 0) + { +#endif + Py_BEGIN_ALLOW_THREADS + res = dup2(fd, fd2); + Py_END_ALLOW_THREADS + if (res < 0) + return posix_error(); + if (_Py_set_inheritable(fd2, 0, NULL) < 0) { + close(fd2); + return NULL; + } +#ifdef HAVE_DUP3 + } +#endif + +#endif + Py_INCREF(Py_None); return Py_None; } @@ -8052,30 +8220,75 @@ #ifdef HAVE_PIPE PyDoc_STRVAR(posix_pipe__doc__, -"pipe() -> (read_end, write_end)\n\n\ -Create a pipe."); +"pipe() -> (read_end, write_end)\n\n" +"Create a pipe. If cloexec is True, set the close-on-exec flag."); static PyObject * posix_pipe(PyObject *self, PyObject *noargs) { -#if !defined(MS_WINDOWS) int fds[2]; +#ifdef MS_WINDOWS + HANDLE read, write; + SECURITY_ATTRIBUTES attr; + BOOL ok; +#else int res; - res = pipe(fds); - if (res != 0) - return posix_error(); - return Py_BuildValue("(ii)", fds[0], fds[1]); -#else /* MS_WINDOWS */ - HANDLE read, write; - int read_fd, write_fd; - BOOL ok; - ok = CreatePipe(&read, &write, NULL, 0); +#endif + +#ifdef MS_WINDOWS + attr.nLength = sizeof(attr); + attr.lpSecurityDescriptor = NULL; + attr.bInheritHandle = FALSE; + + Py_BEGIN_ALLOW_THREADS + ok = CreatePipe(&read, &write, &attr, 0); + if (ok) { + fds[0] = _open_osfhandle((Py_intptr_t)read, _O_RDONLY); + fds[1] = _open_osfhandle((Py_intptr_t)write, _O_WRONLY); + if (fds[0] == -1 || fds[1] == -1) { + CloseHandle(read); + CloseHandle(write); + ok = 0; + } + } + Py_END_ALLOW_THREADS + if (!ok) return PyErr_SetFromWindowsErr(0); - read_fd = _open_osfhandle((Py_intptr_t)read, 0); - write_fd = _open_osfhandle((Py_intptr_t)write, 1); - return Py_BuildValue("(ii)", read_fd, write_fd); -#endif /* MS_WINDOWS */ +#else + +#ifdef HAVE_PIPE2 + Py_BEGIN_ALLOW_THREADS + res = pipe2(fds, O_CLOEXEC); + Py_END_ALLOW_THREADS + + if (res != 0 && errno == ENOSYS) + { +#endif + Py_BEGIN_ALLOW_THREADS + res = pipe(fds); + Py_END_ALLOW_THREADS + + if (res == 0) { + if (_Py_set_inheritable(fds[0], 0, NULL) < 0) { + close(fds[0]); + close(fds[1]); + return NULL; + } + if (_Py_set_inheritable(fds[1], 0, NULL) < 0) { + close(fds[0]); + close(fds[1]); + return NULL; + } + } +#ifdef HAVE_PIPE2 + } +#endif + + if (res != 0) + return PyErr_SetFromErrno(PyExc_OSError); +#endif /* !MS_WINDOWS */ + return Py_BuildValue("(ii)", fds[0], fds[1]); } #endif /* HAVE_PIPE */ @@ -10665,6 +10878,103 @@ Py_RETURN_NONE; } +PyDoc_STRVAR(get_inheritable__doc__, + "get_inheritable(fd) -> bool\n" \ + "\n" \ + "Get the close-on-exe flag of the specified file descriptor."); + +static PyObject* +posix_get_inheritable(PyObject *self, PyObject *args) +{ +#ifdef MS_WINDOWS + Py_intptr_t handle; + BOOL success; + DWORD flags; + + if (!PyArg_ParseTuple(args, _Py_PARSE_INTPTR ":get_inheritable", &handle)) + return NULL; + + if (_PyVerify_fd(handle)) { + /* handle looks to be a file descriptor */ + handle = _get_osfhandle((int)handle); + if ((HANDLE)handle == INVALID_HANDLE_VALUE) { + PyErr_SetFromWindowsErr(0); + return NULL; + } + } + + success = GetHandleInformation((HANDLE)handle, &flags); + if (!success) { + PyErr_SetFromWindowsErr(0); + return NULL; + } + + return PyBool_FromLong(flags & HANDLE_FLAG_INHERIT); +#else + int fd; + int inheritable; + + if (!PyArg_ParseTuple(args, "i:get_inheritable", &fd)) + return NULL; + + inheritable = _Py_get_inheritable(fd); + if (inheritable < 0) + return NULL; + return PyBool_FromLong(inheritable); +#endif +} + +PyDoc_STRVAR(set_inheritable__doc__, + "set_inheritable(fd, inheritable)\n" \ + "\n" \ + "Set or clear inheritable flag on the specified file descriptor."); + +static PyObject* +posix_set_inheritable(PyObject *self, PyObject *args) +{ + int inheritable = 1; +#ifdef MS_WINDOWS + Py_intptr_t handle; + DWORD flags; + BOOL success; + + if (!PyArg_ParseTuple(args, _Py_PARSE_INTPTR "i:set_inheritable", + &handle, &inheritable)) + return NULL; + + if (_PyVerify_fd(handle)) { + /* handle looks to be a file descriptor */ + handle = _get_osfhandle((int)handle); + if ((HANDLE)handle == INVALID_HANDLE_VALUE) { + PyErr_SetFromWindowsErr(0); + return NULL; + } + } + + /* fd may be an handle, ex: a Windows socket */ + if (inheritable) + flags = HANDLE_FLAG_INHERIT; + else + flags = 0; + success = SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags); + if (!success) { + PyErr_SetFromWindowsErr(0); + return NULL; + } + Py_RETURN_NONE; +#else + int fd; + + + if (!PyArg_ParseTuple(args, "ii:set_inheritable", &fd, &inheritable)) + return NULL; + + if (_Py_set_inheritable(fd, inheritable, NULL) < 0) + return NULL; + Py_RETURN_NONE; +#endif +} + static PyMethodDef posix_methods[] = { {"access", (PyCFunction)posix_access, @@ -11113,6 +11423,8 @@ #endif {"cpu_count", (PyCFunction)posix_cpu_count, METH_NOARGS, posix_cpu_count__doc__}, + {"get_inheritable", posix_get_inheritable, METH_VARARGS, get_inheritable__doc__}, + {"set_inheritable", posix_set_inheritable, METH_VARARGS, set_inheritable__doc__}, {NULL, NULL} /* Sentinel */ }; diff -r f4271cc2dfb5 -r 00df7fc6d2ef Modules/selectmodule.c --- a/Modules/selectmodule.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Modules/selectmodule.c Mon Aug 19 23:06:45 2013 +0200 @@ -882,6 +882,17 @@ return NULL; } +static PyObject* +devpoll_fileno(devpollObject *self) +{ + return PyLong_FromLong(self->fd_devpoll); +} + +PyDoc_STRVAR(devpoll_fileno_doc, +"fileno() -> int\n\ +\n\ +Return the file descriptor."); + static PyMethodDef devpoll_methods[] = { {"register", (PyCFunction)devpoll_register, METH_VARARGS, devpoll_register_doc}, @@ -891,11 +902,13 @@ METH_O, devpoll_unregister_doc}, {"poll", (PyCFunction)devpoll_poll, METH_VARARGS, devpoll_poll_doc}, + {"fileno", (PyCFunction)devpoll_fileno, METH_NOARGS, + devpoll_fileno_doc}, {NULL, NULL} /* sentinel */ }; static devpollObject * -newDevPollObject(void) +newDevPollObject() { devpollObject *self; int fd_devpoll, limit_result; @@ -923,6 +936,11 @@ return NULL; } + if (_Py_set_inheritable(fd_devpoll, 0, NULL) < 0) { + close(fd_devpoll); + return NULL; + } + fds = PyMem_NEW(struct pollfd, limit.rlim_cur); if (fds == NULL) { close(fd_devpoll); @@ -1103,6 +1121,7 @@ if (fd == -1) { Py_BEGIN_ALLOW_THREADS #ifdef HAVE_EPOLL_CREATE1 + flags |= EPOLL_CLOEXEC; if (flags) self->epfd = epoll_create1(flags); else @@ -1118,6 +1137,14 @@ PyErr_SetFromErrno(PyExc_OSError); return NULL; } + +#ifndef HAVE_EPOLL_CREATE1 + if (_Py_set_inheritable(self->epfd, 0, NULL) < 0) { + Py_DECREF(self); + return NULL; + } +#endif + return (PyObject *)self; } @@ -1805,13 +1832,19 @@ PyErr_SetFromErrno(PyExc_OSError); return NULL; } + + if (fd == -1) { + if (_Py_set_inheritable(self->kqfd, 0, NULL) < 0) { + Py_DECREF(self); + return NULL; + } + } return (PyObject *)self; } static PyObject * kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { - if ((args != NULL && PyObject_Size(args)) || (kwds != NULL && PyObject_Size(kwds))) { PyErr_SetString(PyExc_ValueError, @@ -1822,6 +1855,7 @@ return newKqueue_Object(type, -1); } + static void kqueue_queue_dealloc(kqueue_queue_Object *self) { diff -r f4271cc2dfb5 -r 00df7fc6d2ef Modules/socketmodule.c --- a/Modules/socketmodule.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Modules/socketmodule.c Mon Aug 19 23:06:45 2013 +0200 @@ -97,13 +97,14 @@ /* Socket object documentation */ PyDoc_STRVAR(sock_doc, -"socket([family[, type[, proto]]]) -> socket object\n\ +"socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, cloexec=None) -> socket object\n\ \n\ Open a socket of the given type. The family argument specifies the\n\ address family; it defaults to AF_INET. The type argument specifies\n\ whether this is a stream (SOCK_STREAM, this is the default)\n\ or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\ specifying the default protocol. Keyword arguments are accepted.\n\ +If cloexec is True, set close-on-exec flag.\n\ \n\ A socket object represents one endpoint of a network connection.\n\ \n\ @@ -114,7 +115,7 @@ close() -- close the socket\n\ connect(addr) -- connect the socket to a remote address\n\ connect_ex(addr) -- connect, return an error code instead of an exception\n\ -_dup() -- return a new socket fd duplicated from fileno()\n\ +dup(cloexec=None) -- return a new socket fd duplicated from fileno()\n\ fileno() -- return underlying file descriptor\n\ getpeername() -- return remote address [*]\n\ getsockname() -- return local address\n\ @@ -356,22 +357,7 @@ #endif #ifdef MS_WINDOWS -/* On Windows a socket is really a handle not an fd */ -static SOCKET -dup_socket(SOCKET handle) -{ - WSAPROTOCOL_INFO info; - - if (WSADuplicateSocket(handle, GetCurrentProcessId(), &info)) - return INVALID_SOCKET; - - return WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, - FROM_PROTOCOL_INFO, &info, 0, WSA_FLAG_OVERLAPPED); -} #define SOCKETCLOSE closesocket -#else -/* On Unix we can use dup to duplicate the file descriptor of a socket*/ -#define dup_socket(fd) dup(fd) #endif #ifdef MS_WIN32 @@ -499,6 +485,11 @@ (errno == expected) #endif +#ifdef MS_WINDOWS +/* Does WSASocket() support the WSA_FLAG_NO_HANDLE_INHERIT flag? */ +static int support_wsa_no_inherit = -1; +#endif + /* Convenience function to raise an error according to errno and return a NULL pointer from a function. */ @@ -1955,6 +1946,11 @@ PyObject *addr = NULL; PyObject *res = NULL; int timeout; +#if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) + /* accept4() is available on Linux 2.6.28+ and glibc 2.10 */ + static int accept4_works = -1; +#endif + if (!getsockaddrlen(s, &addrlen)) return NULL; memset(&addrbuf, 0, addrlen); @@ -1963,10 +1959,22 @@ return select_error(); BEGIN_SELECT_LOOP(s) + Py_BEGIN_ALLOW_THREADS timeout = internal_select_ex(s, 0, interval); if (!timeout) { +#if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) + if (accept4_works != 0) { + newfd = accept4(s->sock_fd, SAS2SA(&addrbuf), &addrlen, + SOCK_CLOEXEC); + if (newfd == INVALID_SOCKET && accept4_works == -1) + accept4_works = (errno != ENOSYS); + } + if (accept4_works == 0) + newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen); +#else newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen); +#endif } Py_END_ALLOW_THREADS @@ -1979,6 +1987,27 @@ if (newfd == INVALID_SOCKET) return s->errorhandler(); +#if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) + if (!accept4_works) +#endif + { + int os_fd; +#ifdef MS_WINDOWS + os_fd = _open_osfhandle((Py_intptr_t)newfd, O_RDWR); + if (os_fd == -1) { + PyErr_SetFromWindowsErr(0); + SOCKETCLOSE(newfd); + goto finally; + } +#else + os_fd = newfd; +#endif + if (_Py_set_inheritable(os_fd, 0, NULL) < 0) { + SOCKETCLOSE(newfd); + goto finally; + } + } + sock = PyLong_FromSocket_t(newfd); if (sock == NULL) { SOCKETCLOSE(newfd); @@ -3909,6 +3938,12 @@ /* Initialize a new socket object. */ +#ifdef SOCK_CLOEXEC +/* socket() and socketpair() fail with EINVAL on Linux kernel older + * than 2.6.27 if SOCK_CLOEXEC flag is set in the socket type. */ +static int sock_cloexec_works = -1; +#endif + /*ARGSUSED*/ static int sock_initobj(PyObject *self, PyObject *args, PyObject *kwds) @@ -3918,6 +3953,13 @@ SOCKET_T fd = INVALID_SOCKET; int family = AF_INET, type = SOCK_STREAM, proto = 0; static char *keywords[] = {"family", "type", "proto", "fileno", 0}; +#ifndef MS_WINDOWS +#ifdef SOCK_CLOEXEC + int *atomic_flag_works = &sock_cloexec_works; +#else + int *atomic_flag_works = NULL; +#endif +#endif if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iiiO:socket", keywords, @@ -3962,15 +4004,78 @@ } } else { +#ifdef MS_WINDOWS + /* Windows implementation */ +#ifndef WSA_FLAG_NO_HANDLE_INHERIT +#define WSA_FLAG_NO_HANDLE_INHERIT 0x80 +#endif + Py_BEGIN_ALLOW_THREADS - fd = socket(family, type, proto); + if (support_wsa_no_inherit) { + fd = WSASocket(family, type, proto, + NULL, 0, + WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT); + if (fd == INVALID_SOCKET) { + /* Windows 7 or Windows 2008 R2 without SP1 or the hotfix */ + support_wsa_no_inherit = 0; + fd = socket(family, type, proto); + } + } + else { + fd = socket(family, type, proto); + } Py_END_ALLOW_THREADS if (fd == INVALID_SOCKET) { set_error(); return -1; } - } + + if (!support_wsa_no_inherit) { + BOOL success = SetHandleInformation((HANDLE)fd, + HANDLE_FLAG_INHERIT, 0); + if (!success) { + closesocket(fd); + PyErr_SetFromWindowsErr(0); + return -1; + } + } +#else + /* UNIX */ + Py_BEGIN_ALLOW_THREADS +#ifdef SOCK_CLOEXEC + if (sock_cloexec_works != 0) { + fd = socket(family, type | SOCK_CLOEXEC, proto); + if (sock_cloexec_works == -1) { + if (fd >= 0) { + sock_cloexec_works = 1; + } + else if (errno == EINVAL) { + /* Linux older than 2.6.27 does not support SOCK_CLOEXEC */ + sock_cloexec_works = 0; + fd = socket(family, type, proto); + } + } + } + else +#endif + { + fd = socket(family, type, proto); + } + Py_END_ALLOW_THREADS + + if (fd == INVALID_SOCKET) { + set_error(); + return -1; + } + + if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) { + SOCKETCLOSE(fd); + return -1; + } +#endif + } + init_sockobject(s, fd, family, type, proto); return 0; @@ -4535,16 +4640,63 @@ { SOCKET_T fd, newfd; PyObject *newfdobj; - +#ifdef MS_WINDOWS + WSAPROTOCOL_INFO info; +#endif fd = PyLong_AsSocket_t(fdobj); if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) return NULL; - newfd = dup_socket(fd); +#ifdef MS_WINDOWS + if (WSADuplicateSocket(fd, GetCurrentProcessId(), &info)) + return set_error(); + + if (support_wsa_no_inherit) { + newfd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, + FROM_PROTOCOL_INFO, + &info, 0, + WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT); + if (newfd == INVALID_SOCKET) { + /* Windows 7 or Windows 2008 R2 without SP1 or the hotfix */ + support_wsa_no_inherit = 0; + newfd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, + FROM_PROTOCOL_INFO, + &info, 0, WSA_FLAG_OVERLAPPED); + } + } + else { + newfd = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, + FROM_PROTOCOL_INFO, + &info, 0, WSA_FLAG_OVERLAPPED); + } if (newfd == INVALID_SOCKET) return set_error(); + if (!SetHandleInformation((HANDLE)newfd, HANDLE_FLAG_INHERIT, 0)) { + closesocket(newfd); + PyErr_SetFromWindowsErr(0); + return NULL; + } + +#elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC) + newfd = fcntl(fd, F_DUPFD_CLOEXEC, 0); + if (newfd == INVALID_SOCKET) + return set_error(); + +#else + /* On UNIX, dup can be used to duplicate the file descriptor of a socket */ + newfd = dup(fd); + + if (newfd == INVALID_SOCKET) + return set_error(); + + if (_Py_set_inheritable(newfd, 0, NULL) < 0) { + close(newfd); + return -1; + } +#endif + newfdobj = PyLong_FromSocket_t(newfd); if (newfdobj == NULL) SOCKETCLOSE(newfd); @@ -4570,8 +4722,14 @@ { PySocketSockObject *s0 = NULL, *s1 = NULL; SOCKET_T sv[2]; - int family, type = SOCK_STREAM, proto = 0; + int family = AF_INET, type = SOCK_STREAM, proto = 0; PyObject *res = NULL; +#ifdef SOCK_CLOEXEC + int *atomic_flag_works = &sock_cloexec_works; +#else + int *atomic_flag_works = NULL; +#endif + int ret; #if defined(AF_UNIX) family = AF_UNIX; @@ -4581,9 +4739,38 @@ if (!PyArg_ParseTuple(args, "|iii:socketpair", &family, &type, &proto)) return NULL; + /* Create a pair of socket fds */ - if (socketpair(family, type, proto, sv) < 0) + Py_BEGIN_ALLOW_THREADS +#ifdef SOCK_CLOEXEC + if (sock_cloexec_works != 0) { + ret = socketpair(family, type | SOCK_CLOEXEC, proto, sv); + if (sock_cloexec_works == -1) { + if (ret >= 0) { + sock_cloexec_works = 1; + } + else if (errno == EINVAL) { + /* Linux older than 2.6.27 does not support SOCK_CLOEXEC */ + sock_cloexec_works = 0; + ret = socketpair(family, type, proto, sv); + } + } + } + else +#endif + { + ret = socketpair(family, type, proto, sv); + } + Py_END_ALLOW_THREADS + + if (ret < 0) return set_error(); + + if (_Py_set_inheritable(sv[0], 0, atomic_flag_works) < 0) + goto finally; + if (_Py_set_inheritable(sv[1], 0, atomic_flag_works) < 0) + goto finally; + s0 = new_sockobject(sv[0], family, type, proto); if (s0 == NULL) goto finally; @@ -4605,7 +4792,7 @@ } PyDoc_STRVAR(socketpair_doc, -"socketpair([family[, type[, proto]]]) -> (socket object, socket object)\n\ +"socketpair(family=AF_INET, type=SOCK_STREAM, proto=0) -> (socket object, socket object)\n\ \n\ Create a pair of socket objects from the sockets returned by the platform\n\ socketpair() function.\n\ @@ -5539,6 +5726,16 @@ if (!os_init()) return NULL; +#ifdef MS_WINDOWS + if (support_wsa_no_inherit == -1) { + DWORD version = GetVersion(); + DWORD major = (DWORD)LOBYTE(LOWORD(version)); + DWORD minor = (DWORD)HIBYTE(LOWORD(version)); + /* need Windows 7 SP1, 2008 R2 SP1 or later */ + support_wsa_no_inherit = (major >= 6 && minor >= 1); + } +#endif + Py_TYPE(&sock_type) = &PyType_Type; m = PyModule_Create(&socketmodule); if (m == NULL) diff -r f4271cc2dfb5 -r 00df7fc6d2ef Modules/zipimport.c --- a/Modules/zipimport.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Modules/zipimport.c Mon Aug 19 23:06:45 2013 +0200 @@ -870,7 +870,7 @@ const char *charset; int bootstrap; - fp = _Py_fopen(archive, "rb"); + fp = _Py_fopen_obj(archive, "rb"); if (fp == NULL) { if (!PyErr_Occurred()) PyErr_Format(ZipImportError, "can't open Zip file: %R", archive); @@ -1064,7 +1064,7 @@ return NULL; } - fp = _Py_fopen(archive, "rb"); + fp = _Py_fopen_obj(archive, "rb"); if (!fp) { if (!PyErr_Occurred()) PyErr_Format(PyExc_IOError, diff -r f4271cc2dfb5 -r 00df7fc6d2ef Parser/tokenizer.c --- a/Parser/tokenizer.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Parser/tokenizer.c Mon Aug 19 23:06:45 2013 +0200 @@ -1734,6 +1734,10 @@ if (fd < 0) { return NULL; } +#ifndef PGEN + _Py_try_set_inheritable(fd, 0); +#endif + fp = fdopen(fd, "r"); if (fp == NULL) { return NULL; diff -r f4271cc2dfb5 -r 00df7fc6d2ef Python/errors.c --- a/Python/errors.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Python/errors.c Mon Aug 19 23:06:45 2013 +0200 @@ -2,6 +2,7 @@ /* Error handling */ #include "Python.h" +#include #ifndef __STDC__ #ifndef MS_WINDOWS @@ -977,7 +978,7 @@ if (filename == NULL || *filename == '\0' || lineno <= 0) return NULL; - fp = fopen(filename, "r" PY_STDIOTEXTMODE); + fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE); if (fp == NULL) return NULL; for (i = 0; i < lineno; i++) { diff -r f4271cc2dfb5 -r 00df7fc6d2ef Python/fileutils.c --- a/Python/fileutils.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Python/fileutils.c Mon Aug 19 23:06:45 2013 +0200 @@ -9,10 +9,29 @@ #include #endif +#if defined(HAVE_SYS_IOCTL_H) +# include +#endif + +#ifdef HAVE_FCNTL_H +#include +#endif /* HAVE_FCNTL_H */ + #ifdef __APPLE__ extern wchar_t* _Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size); #endif +#ifdef O_CLOEXEC +/* Does open() supports the O_CLOEXEC flag? Possible values: + + -1: unknown + 0: open() ignores O_CLOEXEC flag, ex: Linux kernel older than 2.6.23 + 1: open() supports O_CLOEXEC flag, close-on-exec is set + + The flag is used by open_cloexec(), io.FileIO and os.open() */ +int _Py_open_cloexec_works = -1; +#endif + PyObject * _Py_device_encoding(int fd) { @@ -547,14 +566,211 @@ #endif +/* Get the inheritable flag of the specified file descriptor. + Return 1 if it the file descriptor is inheritable, 0 if it is not, + raise an exception and return -1 on error. */ +int +_Py_get_inheritable(int fd) +{ +#ifdef MS_WINDOWS + HANDLE handle; + BOOL success; + DWORD flags; + + if (!_PyVerify_fd(fd)) { + PyErr_SetFromWindowsErr(ERROR_INVALID_HANDLE); + return -1; + } + + handle = (HANDLE)_get_osfhandle(fd); + if (handle == INVALID_HANDLE_VALUE) { + PyErr_SetFromWindowsErr(0); + return -1; + } + + success = GetHandleInformation(handle, &flags); + if (!success) { + PyErr_SetFromWindowsErr(0); + return -1; + } + + return (flags & HANDLE_FLAG_INHERIT); +#else + int flags; + + flags = fcntl(fd, F_GETFD, 0); + if (flags == -1) { + PyErr_SetFromErrno(PyExc_OSError); + return -1; + } + return !(flags & FD_CLOEXEC); +#endif +} + +static int +set_inheritable(int fd, int inheritable, int raise) +{ +#ifdef MS_WINDOWS + HANDLE handle; + DWORD flags; + BOOL success; +#elif defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX) + int request; + int err; +#elif defined(HAVE_FCNTL_H) + int flags; + int res; +#endif + +#ifdef MS_WINDOWS + if (!_PyVerify_fd(fd)) { + if (raise) + PyErr_SetFromWindowsErr(ERROR_INVALID_HANDLE); + return -1; + } + + handle = (HANDLE)_get_osfhandle(fd); + if (handle == INVALID_HANDLE_VALUE) { + if (raise) + PyErr_SetFromWindowsErr(0); + return -1; + } + + if (inheritable) + flags = HANDLE_FLAG_INHERIT; + else + flags = 0; + success = SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags); + if (!success) { + if (raise) + PyErr_SetFromWindowsErr(0); + return -1; + } + return 0; +#elif defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX) + if (inheritable) + request = FIONCLEX; + else + request = FIOCLEX; + err = ioctl(fd, request); + if (err) { + if (raise) + PyErr_SetFromErrno(PyExc_OSError); + return -1; + } + return 0; +#elif defined(HAVE_FCNTL_H) + flags = fcntl(fd, F_GETFD); + if (flags < 0) { + if (raise) + PyErr_SetFromErrno(PyExc_OSError); + return -1; + } + + if (inheritable) + flags &= ~FD_CLOEXEC; + else + flags |= FD_CLOEXEC; + res = fcntl(fd, F_SETFD, flags); + if (res < 0) { + if (raise) + PyErr_SetFromErrno(PyExc_OSError); + return -1; + } + return 0; +#else + if (raise) + PyErr_SetString(PyExc_NotImplementedError, + "close-on-exec flag is not supported on your platform"); + return -1; +#endif +} + +/* Set or clear inheritable flag of the specified file descriptor. + On success: return 0, on error: raise an exception if raise is nonzero + and return -1. */ +int +_Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works) +{ + if (atomic_flag_works != NULL) { + if (*atomic_flag_works == -1) { + int inheritable = _Py_get_inheritable(fd); + if (inheritable == -1) + return -1; + *atomic_flag_works = !inheritable; + } + + if (*atomic_flag_works) + return 0; + } + + return set_inheritable(fd, inheritable, 1); +} + +/* Try to set or clear the inheritable flag of the specified file descriptor. + If setting the close-on-exec flag failed, ignore the error. */ +void +_Py_try_set_inheritable(int fd, int inheritable) +{ + (void)set_inheritable(fd, inheritable, 0); +} + +static int +open_cloexec(const char *pathname, int flags, int cloexec) +{ + int fd; + + if (!cloexec) + return open(pathname, flags); + +#ifdef MS_WINDOWS + flags |= O_NOINHERIT; +#elif defined(O_CLOEXEC) + flags |= O_CLOEXEC; +#endif + fd = open(pathname, flags); + if (fd < 0) + return fd; + +#if defined(O_CLOEXEC) && !defined(MS_WINDOWS) + if (_Py_open_cloexec_works == -1) { + int flags = fcntl(fd, F_GETFD, 0); + if (flags != -1) + _Py_open_cloexec_works = (flags & FD_CLOEXEC); + else + _Py_open_cloexec_works = 0; + } + + if (!_Py_open_cloexec_works) { + /* Linux kernel older than 2.6.23 ignores O_CLOEXEC flag */ + (void)set_inheritable(fd, 0, 0); + } +#elif !defined(MS_WINDOWS) + (void)set_inheritable(fd, 0, 0); +#endif + return fd; +} + +/* Open a file with the specified flags (wrapper to open() function). + + Try to set the file descriptor non-inheritable. If clearing the inheritable + flag failed, ignore the error. */ +int +_Py_open(const char *pathname, int flags) +{ + return open_cloexec(pathname, flags, 1); +} + /* Open a file. Use _wfopen() on Windows, encode the path to the locale - encoding and use fopen() otherwise. */ + encoding and use fopen() otherwise. + Try to clear the inheritable flag on the newly created file descriptor. If + clearing the inheritable flag failed, ignore the error. */ FILE * _Py_wfopen(const wchar_t *path, const wchar_t *mode) { + FILE *f; #ifndef MS_WINDOWS - FILE *f; char *cpath; char cmode[10]; size_t r; @@ -570,19 +786,38 @@ PyMem_Free(cpath); return f; #else - return _wfopen(path, mode); + f = _wfopen(path, mode); #endif + if (f == NULL) + return NULL; + (void)set_inheritable(fileno(f), 0, 0); + return f; } -/* Call _wfopen() on Windows, or encode the path to the filesystem encoding and - call fopen() otherwise. +/* Wrapper to fopen(). + Try to make the file non-inheritable, ignore the error if it failed. */ +FILE* +_Py_fopen(const char *pathname, const char *mode) +{ + FILE *f = fopen(pathname, mode); + if (f == NULL) + return NULL; + (void)set_inheritable(fileno(f), 0, 0); + return f; +} + +/* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem + encoding and call fopen() otherwise. + + Try to clear the inheritable flag on the newly created file descriptor. If + clearing the inheritable flag failed, ignore the error. Return the new file object on success, or NULL if the file cannot be open or - (if PyErr_Occurred()) on unicode error */ - + (if PyErr_Occurred()) on unicode error. */ FILE* -_Py_fopen(PyObject *path, const char *mode) +_Py_fopen_obj(PyObject *path, const char *mode) { + FILE *f; #ifdef MS_WINDOWS wchar_t *wpath; wchar_t wmode[10]; @@ -602,16 +837,18 @@ if (usize == 0) return NULL; - return _wfopen(wpath, wmode); + f = _wfopen(wpath, wmode); #else - FILE *f; PyObject *bytes; if (!PyUnicode_FSConverter(path, &bytes)) return NULL; f = fopen(PyBytes_AS_STRING(bytes), mode); Py_DECREF(bytes); +#endif + if (f == NULL) + return NULL; + (void)set_inheritable(fileno(f), 0, 0); return f; -#endif } #ifdef HAVE_READLINK diff -r f4271cc2dfb5 -r 00df7fc6d2ef Python/import.c --- a/Python/import.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Python/import.c Mon Aug 19 23:06:45 2013 +0200 @@ -1800,7 +1800,7 @@ &name, PyUnicode_FSDecoder, &pathname, &fob)) return NULL; if (fob != NULL) { - fp = _Py_fopen(pathname, "r"); + fp = _Py_fopen_obj(pathname, "r"); if (fp == NULL) { Py_DECREF(pathname); if (!PyErr_Occurred()) diff -r f4271cc2dfb5 -r 00df7fc6d2ef Python/pythonrun.c --- a/Python/pythonrun.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Python/pythonrun.c Mon Aug 19 23:06:45 2013 +0200 @@ -29,6 +29,10 @@ #include #endif +#ifdef HAVE_FCNTL_H +#include +#endif /* HAVE_FCNTL_H */ + #ifdef MS_WINDOWS #undef BYTE #include "windows.h" @@ -1451,7 +1455,7 @@ /* Try to run a pyc file. First, re-open in binary */ if (closeit) fclose(fp); - if ((pyc_fp = fopen(filename, "rb")) == NULL) { + if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) { fprintf(stderr, "python: Can't reopen .pyc file\n"); goto done; } diff -r f4271cc2dfb5 -r 00df7fc6d2ef Python/random.c --- a/Python/random.c Mon Aug 19 23:19:49 2013 +0300 +++ b/Python/random.c Mon Aug 19 23:06:45 2013 +0200 @@ -101,7 +101,7 @@ assert (0 < size); - fd = open("/dev/urandom", O_RDONLY); + fd = _Py_open("/dev/urandom", O_RDONLY); if (fd < 0) Py_FatalError("Failed to open /dev/urandom"); @@ -134,7 +134,7 @@ return 0; Py_BEGIN_ALLOW_THREADS - fd = open("/dev/urandom", O_RDONLY); + fd = _Py_open("/dev/urandom", O_RDONLY); Py_END_ALLOW_THREADS if (fd < 0) { diff -r f4271cc2dfb5 -r 00df7fc6d2ef configure.ac --- a/configure.ac Mon Aug 19 23:19:49 2013 +0300 +++ b/configure.ac Mon Aug 19 23:06:45 2013 +0200 @@ -2806,7 +2806,7 @@ # checks for library functions AC_CHECK_FUNCS(alarm accept4 setitimer getitimer bind_textdomain_codeset chown \ - clock confstr ctermid execv faccessat fchmod fchmodat fchown fchownat \ + clock confstr ctermid dup3 execv faccessat fchmod fchmodat fchown fchownat \ fexecve fdopendir fork fpathconf fstatat ftime ftruncate futimesat \ futimens futimes gai_strerror \ getgrouplist getgroups getlogin getloadavg getpeername getpgid getpid \