python / python/cpython

os.forkpty() and pty.fork() return FD with O_CLOEXEC

Offen
#139,184 6 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

3.15 stdlib type-bug
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
36k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug report

Bug description:
(pid, fd) = pty.fork() # os.forkpty()
print('os.get_inheritable(fd))

https://docs.python.org/3/library/os.html#os.forkpty
https://docs.python.org/3/library/pty.html#pty.fork

Say nothing about that.

Lib/pty.py:

def fork():
    """fork() -> (pid, master_fd)
    Fork and make the child a session leader with a controlling terminal."""

    try:
        pid, fd = os.forkpty()
    except (AttributeError, OSError):
        pass
    else:
        if pid == CHILD:
            try:
                os.setsid()
            except OSError:
                # os.forkpty() already set us session leader
                pass
        return pid, fd

    master_fd, slave_fd = openpty()
    pid = os.fork()
    if pid == CHILD:
        os.close(master_fd)
        os.login_tty(slave_fd)
    else:
        os.close(slave_fd)

    # Parent and child process.
    return pid, master_fd

Also uses openpty() which also does not set O_CLOEXEC

Meanwhile, there is a C function posix_openpt(int flags); which allows setting O_CLOEXEC.

Seems, fd-leak safe solution is to boilerplate all the actions by hand. i.e. same way as pty.fork() does, but also implement openpty() using posix_openpt() + ptsname() / ptsname_r().

Just setting O_CLOEXEC after openpty() or after calling C forkpty() is not enough because of race-condition and possible file descriptor leak.

So, CLOEXEC behavior should be documented and race-condition prevented

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-139408

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit Lib/pty.py und den dokumentierten Einstiegspunkten os.forkpty() und pty.fork(), und vergleiche anschließend deren openpty()-Pfade mit der im Report erwähnten posix_openpt(int flags)-Schnittstelle. Die Arbeit ist abgeschlossen, wenn das CLOEXEC-Verhalten dokumentiert ist und die fork/openpty-Pfade das beschriebene Race-Condition-Leak von Dateideskriptoren verhindern.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
operating-systems
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.