Reduce probability of startup port collisions (#1273)

This commit is contained in:
Justin Kotalik 2018-08-28 09:34:10 -07:00 committed by GitHub
parent f86fabe9d2
commit 338af6f07d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 5 deletions

View File

@ -3,6 +3,8 @@
#pragma once
#include <random>
#define MIN_PORT 1025
#define MAX_PORT 48000
#define MAX_RETRY 10
@ -294,6 +296,8 @@ private:
volatile BOOL m_fReady;
mutable LONG m_cRefs;
std::mt19937 m_randomGenerator;
DWORD m_dwPort;
DWORD m_dwStartupTimeLimitInMS;
DWORD m_dwShutdownTimeLimitInMS;
@ -322,4 +326,4 @@ private:
PROCESS_MANAGER *m_pProcessManager;
ENVIRONMENT_VAR_HASH *m_pEnvironmentVarTable ;
};
};

View File

@ -88,13 +88,15 @@ SERVER_PROCESS::GetRandomPort
BOOL fPortInUse = FALSE;
DWORD dwActualProcessId = 0;
std::uniform_int_distribution<> dist(MIN_PORT, MAX_PORT);
if (g_fNsiApiNotSupported)
{
//
// the default value for optional parameter dwExcludedPort is 0 which is reserved
// a random number between MIN_PORT and MAX_PORT
//
while ((*pdwPickedPort = (rand() % (MAX_PORT - MIN_PORT)) + MIN_PORT + 1) == dwExcludedPort);
while ((*pdwPickedPort = dist(m_randomGenerator)) == dwExcludedPort);
}
else
{
@ -106,7 +108,7 @@ SERVER_PROCESS::GetRandomPort
// determing whether the randomly generated port is
// in use by any other process.
//
while ((*pdwPickedPort = (rand() % (MAX_PORT - MIN_PORT)) + MIN_PORT + 1) == dwExcludedPort);
while ((*pdwPickedPort = dist(m_randomGenerator)) == dwExcludedPort);
hr = CheckIfServerIsUp(*pdwPickedPort, &dwActualProcessId, &fPortInUse);
} while (fPortInUse && ++cRetry < MAX_RETRY);
@ -1901,10 +1903,10 @@ SERVER_PROCESS::SERVER_PROCESS() :
m_pForwarderConnection( NULL ),
m_dwListeningProcessId( 0 ),
m_hListeningProcessHandle( NULL ),
m_hShutdownHandle( NULL )
m_hShutdownHandle( NULL ),
m_randomGenerator( std::random_device()() )
{
InterlockedIncrement(&g_dwActiveServerProcesses);
srand(GetTickCount());
for(INT i=0;i<MAX_ACTIVE_CHILD_PROCESSES; ++i)
{