From 338af6f07d29d9e34ae1eb8b901632cad6edb06f Mon Sep 17 00:00:00 2001 From: Justin Kotalik Date: Tue, 28 Aug 2018 09:34:10 -0700 Subject: [PATCH] Reduce probability of startup port collisions (#1273) --- src/AspNetCoreModuleV1/AspNetCore/Inc/serverprocess.h | 6 +++++- .../AspNetCore/src/serverprocess.cxx | 10 ++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/AspNetCoreModuleV1/AspNetCore/Inc/serverprocess.h b/src/AspNetCoreModuleV1/AspNetCore/Inc/serverprocess.h index 4d6bf6c145..0eebdb9d69 100644 --- a/src/AspNetCoreModuleV1/AspNetCore/Inc/serverprocess.h +++ b/src/AspNetCoreModuleV1/AspNetCore/Inc/serverprocess.h @@ -3,6 +3,8 @@ #pragma once +#include + #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 ; -}; \ No newline at end of file +}; diff --git a/src/AspNetCoreModuleV1/AspNetCore/src/serverprocess.cxx b/src/AspNetCoreModuleV1/AspNetCore/src/serverprocess.cxx index a64b6cae28..f7fc15e3e9 100644 --- a/src/AspNetCoreModuleV1/AspNetCore/src/serverprocess.cxx +++ b/src/AspNetCoreModuleV1/AspNetCore/src/serverprocess.cxx @@ -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