(original) (raw)

changeset: 73743:3c9ddd93c983 branch: 3.2 parent: 73735:2d6f0e2fe034 user: Antoine Pitrou solipsis@pitrou.net date: Fri Nov 25 21:28:15 2011 +0100 files: Lib/tempfile.py Lib/test/test_tempfile.py Misc/NEWS description: Issue #12856: Ensure child processes do not inherit the parent's random seed for filename generation in the tempfile module. Patch by Brian Harring. diff -r 2d6f0e2fe034 -r 3c9ddd93c983 Lib/tempfile.py --- a/Lib/tempfile.py Fri Nov 25 16:33:53 2011 +0100 +++ b/Lib/tempfile.py Fri Nov 25 21:28:15 2011 +0100 @@ -112,8 +112,13 @@ characters = "abcdefghijklmnopqrstuvwxyz0123456789_" - def __init__(self): - self.rng = _Random() + @property + def rng(self): + cur_pid = _os.getpid() + if cur_pid != getattr(self, '_rng_pid', None): + self._rng = _Random() + self._rng_pid = cur_pid + return self._rng def __iter__(self): return self diff -r 2d6f0e2fe034 -r 3c9ddd93c983 Lib/test/test_tempfile.py --- a/Lib/test/test_tempfile.py Fri Nov 25 16:33:53 2011 +0100 +++ b/Lib/test/test_tempfile.py Fri Nov 25 21:28:15 2011 +0100 @@ -1,6 +1,7 @@ # tempfile.py unit tests. import tempfile import os +import signal import sys import re import warnings @@ -135,6 +136,37 @@ except: self.failOnException("iteration") + @unittest.skipUnless(hasattr(os, 'fork'), + "os.fork is required for this test") + def test_process_awareness(self): + # ensure that the random source differs between + # child and parent. + read_fd, write_fd = os.pipe() + pid = None + try: + pid = os.fork() + if not pid: + os.close(read_fd) + os.write(write_fd, next(self.r).encode("ascii")) + os.close(write_fd) + # bypass the normal exit handlers- leave those to + # the parent. + os._exit(0) + parent_value = next(self.r) + child_value = os.read(read_fd, len(parent_value)).decode("ascii") + finally: + if pid: + # best effort to ensure the process can't bleed out + # via any bugs above + try: + os.kill(pid, signal.SIGKILL) + except EnvironmentError: + pass + os.close(read_fd) + os.close(write_fd) + self.assertNotEqual(child_value, parent_value) + + test_classes.append(test__RandomNameSequence) diff -r 2d6f0e2fe034 -r 3c9ddd93c983 Misc/NEWS --- a/Misc/NEWS Fri Nov 25 16:33:53 2011 +0100 +++ b/Misc/NEWS Fri Nov 25 21:28:15 2011 +0100 @@ -83,6 +83,10 @@ Library ------- +- Issue #12856: Ensure child processes do not inherit the parent's random + seed for filename generation in the tempfile module. Patch by Brian + Harring. + - Issue #13458: Fix a memory leak in the ssl module when decoding a certificate with a subjectAltName. Patch by Robert Xiao. /solipsis@pitrou.net