]> granicus.if.org Git - python/commitdiff
Issue #18756: Improve error reporting in os.urandom() when the failure is due to...
authorAntoine Pitrou <solipsis@pitrou.net>
Fri, 16 Aug 2013 18:44:38 +0000 (20:44 +0200)
committerAntoine Pitrou <solipsis@pitrou.net>
Fri, 16 Aug 2013 18:44:38 +0000 (20:44 +0200)
Lib/test/test_os.py
Misc/NEWS
Python/random.c

index bdbeb0107bba1b1b4f04cd32950498a6675d0a6f..ccc58d4fbb72e74ef5dc45a463bfeaa5f96dfcfa 100644 (file)
@@ -10,6 +10,10 @@ import sys
 import signal
 import subprocess
 import time
+try:
+    import resource
+except ImportError:
+    resource = None
 
 from test import test_support
 import mmap
@@ -563,6 +567,20 @@ class URandomTests (unittest.TestCase):
         data2 = self.get_urandom_subprocess(16)
         self.assertNotEqual(data1, data2)
 
+    @unittest.skipUnless(resource, "test requires the resource module")
+    def test_urandom_failure(self):
+        soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
+        resource.setrlimit(resource.RLIMIT_NOFILE, (1, hard_limit))
+        try:
+            with self.assertRaises(OSError) as cm:
+                os.urandom(16)
+            self.assertEqual(cm.exception.errno, errno.EMFILE)
+        finally:
+            # We restore the old limit as soon as possible.  If doing it
+            # using addCleanup(), code running in between would fail
+            # creating any file descriptor.
+            resource.setrlimit(resource.RLIMIT_NOFILE, (soft_limit, hard_limit))
+
     def test_execvpe_with_bad_arglist(self):
         self.assertRaises(ValueError, os.execvpe, 'notepad', [], None)
 
index 2aad9bbd066ae423479575b67cf70524896809f0..e5101f5fb0c865eeac75e8842cc2489ddfaca7bf 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -29,6 +29,10 @@ Core and Builtins
 Library
 -------
 
+- Issue #18756: Improve error reporting in os.urandom() when the failure
+  is due to something else than /dev/urandom not existing (for example,
+  exhausting the file descriptor limit).
+
 - Fix tkinter regression introduced by the security fix in issue #16248.
 
 - Issue #18676: Change 'positive' to 'non-negative' in queue.py put and get
index 825260f36b2ad80aa1998125f8dd41da711e4c34..73e3cc3551f7a099f3b507d45189d28ab36b718b 100644 (file)
@@ -165,8 +165,12 @@ dev_urandom_python(char *buffer, Py_ssize_t size)
     Py_END_ALLOW_THREADS
     if (fd < 0)
     {
-        PyErr_SetString(PyExc_NotImplementedError,
-                        "/dev/urandom (or equivalent) not found");
+        if (errno == ENOENT || errno == ENXIO ||
+            errno == ENODEV || errno == EACCES)
+            PyErr_SetString(PyExc_NotImplementedError,
+                            "/dev/urandom (or equivalent) not found");
+        else
+            PyErr_SetFromErrno(PyExc_OSError);
         return -1;
     }