]> git.saurik.com Git - apple/security.git/blobdiff - cdsa/cdsa_utilities/devrandom.cpp
Security-54.1.5.tar.gz
[apple/security.git] / cdsa / cdsa_utilities / devrandom.cpp
index 574a7142b8ad22f67a4faa99fc6fe4515642808f..835b8defa1de17f8a4632a4602944c002bda23c9 100644 (file)
 //
 #include <Security/devrandom.h>
 
+using namespace UnixPlusPlus;
+
 
 namespace Security {
 
 
+//
+// The common (shared) open file descriptor to /dev/random
+//
+ModuleNexus<FileDesc> DevRandomGenerator::mDevRandom;
+
+
 //
 // DevRandomGenerator objects immediately open their file descriptors
 //
 DevRandomGenerator::DevRandomGenerator(bool writable)
 {
-    mDevRandom.open("/dev/random", writable ? O_RDWR : O_RDONLY);
+    FileDesc &fd = mDevRandom();
+    if (!fd) {
+        fd.open("/dev/random", writable ? O_RDWR : O_RDONLY);
+    } else if (writable && !fd.isWritable()) {
+        FileDesc newFd("/dev/random", O_RDWR);
+        fd.close();
+        fd = newFd;
+    }
 }
 
 
@@ -39,7 +54,7 @@ DevRandomGenerator::DevRandomGenerator(bool writable)
 //
 void DevRandomGenerator::random(void *data, size_t length)
 {
-    mDevRandom.read(data, length);
+    mDevRandom().read(data, length);
 }
 
 
@@ -48,7 +63,7 @@ void DevRandomGenerator::random(void *data, size_t length)
 //
 void DevRandomGenerator::addEntropy(const void *data, size_t length)
 {
-    mDevRandom.write(data, length);
+    mDevRandom().write(data, length);
 }