diff options
author | Jonathan Reams <jbreams@mongodb.com> | 2015-11-10 16:01:32 -0500 |
---|---|---|
committer | Jonathan Reams <jbreams@mongodb.com> | 2015-11-12 12:03:30 -0500 |
commit | 8eeed6d77edaf0b0f2b9834d60e5ea0d3aa8e050 (patch) | |
tree | 2705147d6edf74e88fac0860189584fe5e163c2c | |
parent | 884644ac56de2edc2223b75ceabe9e1a6fef6dab (diff) | |
download | mongo-8eeed6d77edaf0b0f2b9834d60e5ea0d3aa8e050.tar.gz |
SERVER-20727 Seed shell random numbers from SecureRandom
-rw-r--r-- | src/mongo/shell/shell_utils.cpp | 20 | ||||
-rw-r--r-- | src/mongo/shell/utils.js | 7 |
2 files changed, 16 insertions, 11 deletions
diff --git a/src/mongo/shell/shell_utils.cpp b/src/mongo/shell/shell_utils.cpp index 84b83844d0b..bae9cce9081 100644 --- a/src/mongo/shell/shell_utils.cpp +++ b/src/mongo/shell/shell_utils.cpp @@ -35,6 +35,7 @@ #include "mongo/client/dbclientinterface.h" #include "mongo/db/catalog/index_key_validate.h" #include "mongo/db/index/external_key_generator.h" +#include "mongo/platform/random.h" #include "mongo/shell/bench.h" #include "mongo/scripting/engine.h" #include "mongo/shell/shell_options.h" @@ -113,16 +114,21 @@ ThreadLocalValue<unsigned int> _randomSeed; #endif BSONObj JSSrand(const BSONObj& a, void* data) { - uassert(12518, - "srand requires a single numeric argument", - a.nFields() == 1 && a.firstElement().isNumber()); + unsigned int seed; + // grab the least significant bits of either the supplied argument or + // a random number from SecureRandom. + if (a.nFields() == 1 && a.firstElement().isNumber()) + seed = static_cast<unsigned int>(a.firstElement().numberLong()); + else { + std::unique_ptr<SecureRandom> rand(SecureRandom::create()); + seed = static_cast<unsigned int>(rand->nextInt64()); + } #if !defined(_WIN32) - _randomSeed.set( - static_cast<unsigned int>(a.firstElement().numberLong())); // grab least significant digits + _randomSeed.set(seed); #else - srand(static_cast<unsigned int>(a.firstElement().numberLong())); + srand(seed); #endif - return undefinedReturn; + return BSON("" << static_cast<double>(seed)); } BSONObj JSRand(const BSONObj& a, void* data) { diff --git a/src/mongo/shell/utils.js b/src/mongo/shell/utils.js index 227f5e509b5..1a3d8ea365c 100644 --- a/src/mongo/shell/utils.js +++ b/src/mongo/shell/utils.js @@ -812,7 +812,7 @@ Math.sigFig = function( x , N ){ Random = function() {} // set random seed -Random.srand = function( s ) { _srand( s ); } +Random.srand = function( s ) { return _srand( s ); } // random number 0 <= r < 1 Random.rand = function() { return _rand(); } @@ -821,9 +821,8 @@ Random.rand = function() { return _rand(); } Random.randInt = function( n ) { return Math.floor( Random.rand() * n ); } Random.setRandomSeed = function( s ) { - s = s || new Date().getTime(); - print( "setting random seed: " + s ); - Random.srand( s ); + var seed = Random.srand( s ); + print("setting random seed: " + seed); } // generate a random value from the exponential distribution with the specified mean |