Change SSLContext to use a ThreadLocalPRNG
authorNeel Goyal <ngoyal@fb.com>
Tue, 29 Mar 2016 17:47:14 +0000 (10:47 -0700)
committerFacebook Github Bot 2 <facebook-github-bot-2-bot@fb.com>
Tue, 29 Mar 2016 17:50:22 +0000 (10:50 -0700)
Summary:Use a ThreadLocalPRNG insteaad of a per context RNG.  This avoids
calls to Random::seed on context creation which can get expensive
when many are created in an application.

Reviewed By: siyengar

Differential Revision: D3105501

fb-gh-sync-id: 92d987c27a1f190a98035ca25c23b994ca915007
fbshipit-source-id: 92d987c27a1f190a98035ca25c23b994ca915007

folly/io/async/SSLContext.cpp
folly/io/async/SSLContext.h

index eb9920a73c33569b3e84df90c1d4dfa09cb8f0f0..ac032da294158c5125164062e034b39c03bf3c31 100644 (file)
@@ -23,6 +23,7 @@
 
 #include <folly/Format.h>
 #include <folly/Memory.h>
+#include <folly/Random.h>
 #include <folly/SpinLock.h>
 
 // ---------------------------------------------------------------------
@@ -85,8 +86,6 @@ SSLContext::SSLContext(SSLVersion version) {
   SSL_CTX_set_tlsext_servername_callback(ctx_, baseServerNameOpenSSLCallback);
   SSL_CTX_set_tlsext_servername_arg(ctx_, this);
 #endif
-
-  Random::seed(randomGenerator_);
 }
 
 SSLContext::~SSLContext() {
@@ -359,7 +358,8 @@ void SSLContext::switchCiphersIfTLS11(
       cipherListPicker_.reset(
           new std::discrete_distribution<int>(weights.begin(), weights.end()));
     }
-    auto index = (*cipherListPicker_)(randomGenerator_);
+    auto rng = ThreadLocalPRNG();
+    auto index = (*cipherListPicker_)(rng);
     if ((size_t)index >= tls11AltCipherlist.size()) {
       LOG(ERROR) << "Trying to pick alt TLS11 cipher index " << index
                  << ", but tls11AltCipherlist is of length "
@@ -499,7 +499,8 @@ void SSLContext::unsetNextProtocols() {
 
 size_t SSLContext::pickNextProtocols() {
   CHECK(!advertisedNextProtocols_.empty()) << "Failed to pickNextProtocols";
-  return nextProtocolDistribution_(randomGenerator_);
+  auto rng = ThreadLocalPRNG();
+  return nextProtocolDistribution_(rng);
 }
 
 int SSLContext::advertisedNextProtocolCallback(SSL* ssl,
index 7b1df4ad513d8a51054c9e05c9b04b8c416ee734..e3ebaf5f7e8bc2486f8fbf90b3291d808e369403 100644 (file)
@@ -36,7 +36,6 @@
 #include <folly/folly-config.h>
 #endif
 
-#include <folly/Random.h>
 #include <folly/Range.h>
 #include <folly/io/async/ssl/OpenSSLPtrTypes.h>
 #include <folly/io/async/ssl/OpenSSLUtils.h>
@@ -494,8 +493,6 @@ class SSLContext {
 
   static bool initialized_;
 
-  // Used in randomized next-proto pick / randomized cipherlist
-  Random::DefaultGenerator randomGenerator_;
   // To provide control over choice of server ciphersuites
   std::unique_ptr<std::discrete_distribution<int>> cipherListPicker_;