serverprocess.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the MIT License. See License.txt in the project root for license information.
  3. #include "serverprocess.h"
  4. #include <IPHlpApi.h>
  5. #include "EventLog.h"
  6. #include "file_utility.h"
  7. #include "exceptions.h"
  8. #define STARTUP_TIME_LIMIT_INCREMENT_IN_MILLISECONDS 5000
  9. HRESULT
  10. SERVER_PROCESS::Initialize(
  11. PROCESS_MANAGER *pProcessManager,
  12. STRU *pszProcessExePath,
  13. STRU *pszArguments,
  14. DWORD dwStartupTimeLimitInMS,
  15. DWORD dwShtudownTimeLimitInMS,
  16. BOOL fWindowsAuthEnabled,
  17. BOOL fBasicAuthEnabled,
  18. BOOL fAnonymousAuthEnabled,
  19. std::map<std::wstring, std::wstring, ignore_case_comparer>& pEnvironmentVariables,
  20. BOOL fStdoutLogEnabled,
  21. BOOL fEnableOutOfProcessConsoleRedirection,
  22. BOOL fWebSocketSupported,
  23. STRU *pstruStdoutLogFile,
  24. STRU *pszAppPhysicalPath,
  25. STRU *pszAppPath,
  26. STRU *pszAppVirtualPath,
  27. STRU *pszHttpsPort
  28. )
  29. {
  30. HRESULT hr = S_OK;
  31. m_pProcessManager = pProcessManager;
  32. m_dwStartupTimeLimitInMS = dwStartupTimeLimitInMS;
  33. m_dwShutdownTimeLimitInMS = dwShtudownTimeLimitInMS;
  34. m_fStdoutLogEnabled = fStdoutLogEnabled;
  35. m_fWebSocketSupported = fWebSocketSupported;
  36. m_fWindowsAuthEnabled = fWindowsAuthEnabled;
  37. m_fBasicAuthEnabled = fBasicAuthEnabled;
  38. m_fAnonymousAuthEnabled = fAnonymousAuthEnabled;
  39. m_fEnableOutOfProcessConsoleRedirection = fEnableOutOfProcessConsoleRedirection;
  40. m_pProcessManager->ReferenceProcessManager();
  41. m_fDebuggerAttached = FALSE;
  42. if (FAILED_LOG(hr = m_ProcessPath.Copy(*pszProcessExePath)) ||
  43. FAILED_LOG(hr = m_struLogFile.Copy(*pstruStdoutLogFile))||
  44. FAILED_LOG(hr = m_struPhysicalPath.Copy(*pszAppPhysicalPath))||
  45. FAILED_LOG(hr = m_struAppFullPath.Copy(*pszAppPath))||
  46. FAILED_LOG(hr = m_struAppVirtualPath.Copy(*pszAppVirtualPath))||
  47. FAILED_LOG(hr = m_Arguments.Copy(*pszArguments)) ||
  48. FAILED_LOG(hr = m_struHttpsPort.Copy(*pszHttpsPort)) ||
  49. FAILED_LOG(hr = SetupJobObject()))
  50. {
  51. goto Finished;
  52. }
  53. m_pEnvironmentVarTable = pEnvironmentVariables;
  54. Finished:
  55. return hr;
  56. }
  57. HRESULT
  58. SERVER_PROCESS::SetupJobObject(VOID)
  59. {
  60. HRESULT hr = S_OK;
  61. JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobInfo = { 0 };
  62. if (m_hJobObject == NULL)
  63. {
  64. m_hJobObject = CreateJobObject(NULL, // LPSECURITY_ATTRIBUTES
  65. NULL); // LPCTSTR lpName
  66. #pragma warning( disable : 4312)
  67. // 0xdeadbeef is used by Antares
  68. if (m_hJobObject == NULL || m_hJobObject == (HANDLE)0xdeadbeef)
  69. {
  70. m_hJobObject = NULL;
  71. // ignore job object creation error.
  72. }
  73. #pragma warning( error : 4312)
  74. if (m_hJobObject != NULL)
  75. {
  76. jobInfo.BasicLimitInformation.LimitFlags =
  77. JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
  78. if (!SetInformationJobObject(m_hJobObject,
  79. JobObjectExtendedLimitInformation,
  80. &jobInfo,
  81. sizeof jobInfo))
  82. {
  83. hr = HRESULT_FROM_WIN32(GetLastError());
  84. }
  85. }
  86. }
  87. return hr;
  88. }
  89. HRESULT
  90. SERVER_PROCESS::GetRandomPort
  91. (
  92. DWORD* pdwPickedPort,
  93. DWORD dwExcludedPort = 0
  94. )
  95. {
  96. HRESULT hr = S_OK;
  97. BOOL fPortInUse = FALSE;
  98. DWORD dwActualProcessId = 0;
  99. std::uniform_int_distribution<> dist(MIN_PORT_RANDOM, MAX_PORT);
  100. DWORD cRetry = 0;
  101. do
  102. {
  103. //
  104. // ignore dwActualProcessId because here we are
  105. // determing whether the randomly generated port is
  106. // in use by any other process.
  107. //
  108. while ((*pdwPickedPort = dist(m_randomGenerator)) == dwExcludedPort);
  109. hr = CheckIfServerIsUp(*pdwPickedPort, &dwActualProcessId, &fPortInUse);
  110. } while (fPortInUse && ++cRetry < MAX_RETRY);
  111. if (cRetry >= MAX_RETRY)
  112. {
  113. hr = HRESULT_FROM_WIN32(ERROR_PORT_NOT_SET);
  114. }
  115. return hr;
  116. }
  117. HRESULT
  118. SERVER_PROCESS::SetupListenPort(
  119. ENVIRONMENT_VAR_HASH *pEnvironmentVarTable,
  120. BOOL* pfCriticalError
  121. )
  122. {
  123. HRESULT hr = S_OK;
  124. ENVIRONMENT_VAR_ENTRY *pEntry = NULL;
  125. *pfCriticalError = FALSE;
  126. pEnvironmentVarTable->FindKey(ASPNETCORE_PORT_ENV_STR, &pEntry);
  127. if (pEntry != NULL)
  128. {
  129. if (pEntry->QueryValue() != NULL && pEntry->QueryValue()[0] != L'\0')
  130. {
  131. m_dwPort = (DWORD)_wtoi(pEntry->QueryValue());
  132. if (m_dwPort >MAX_PORT || m_dwPort < MIN_PORT)
  133. {
  134. hr = E_INVALIDARG;
  135. *pfCriticalError = TRUE;
  136. goto Finished;
  137. // need add log for this one
  138. }
  139. hr = m_struPort.Copy(pEntry->QueryValue());
  140. goto Finished;
  141. }
  142. else
  143. {
  144. //
  145. // user set the env variable but did not give value, let's set it up
  146. //
  147. pEnvironmentVarTable->DeleteKey(ASPNETCORE_PORT_ENV_STR);
  148. pEntry->Dereference();
  149. pEntry = NULL;
  150. }
  151. }
  152. WCHAR buffer[15];
  153. if (FAILED_LOG(hr = GetRandomPort(&m_dwPort)))
  154. {
  155. goto Finished;
  156. }
  157. if (swprintf_s(buffer, 15, L"%d", m_dwPort) <= 0)
  158. {
  159. hr = E_INVALIDARG;
  160. goto Finished;
  161. }
  162. pEntry = new ENVIRONMENT_VAR_ENTRY();
  163. if (pEntry == NULL)
  164. {
  165. hr = E_OUTOFMEMORY;
  166. goto Finished;
  167. }
  168. if (FAILED_LOG(hr = pEntry->Initialize(ASPNETCORE_PORT_ENV_STR, buffer)) ||
  169. FAILED_LOG(hr = pEnvironmentVarTable->InsertRecord(pEntry)) ||
  170. FAILED_LOG(hr = m_struPort.Copy(buffer)))
  171. {
  172. goto Finished;
  173. }
  174. Finished:
  175. if (pEntry != NULL)
  176. {
  177. pEntry->Dereference();
  178. pEntry = NULL;
  179. }
  180. if (FAILED_LOG(hr))
  181. {
  182. EventLog::Error(
  183. ASPNETCORE_EVENT_PROCESS_START_SUCCESS,
  184. ASPNETCORE_EVENT_PROCESS_START_PORTSETUP_ERROR_MSG,
  185. m_struAppFullPath.QueryStr(),
  186. m_struPhysicalPath.QueryStr(),
  187. m_dwPort,
  188. MIN_PORT_RANDOM,
  189. MAX_PORT,
  190. hr);
  191. }
  192. return hr;
  193. }
  194. HRESULT
  195. SERVER_PROCESS::SetupAppPath(
  196. ENVIRONMENT_VAR_HASH* pEnvironmentVarTable
  197. )
  198. {
  199. HRESULT hr = S_OK;
  200. ENVIRONMENT_VAR_ENTRY* pEntry = NULL;
  201. pEnvironmentVarTable->FindKey(ASPNETCORE_APP_PATH_ENV_STR, &pEntry);
  202. if (pEntry != NULL)
  203. {
  204. // user should not set this environment variable in configuration
  205. pEnvironmentVarTable->DeleteKey(ASPNETCORE_APP_PATH_ENV_STR);
  206. pEntry->Dereference();
  207. pEntry = NULL;
  208. }
  209. pEntry = new ENVIRONMENT_VAR_ENTRY();
  210. if (pEntry == NULL)
  211. {
  212. hr = E_OUTOFMEMORY;
  213. goto Finished;
  214. }
  215. if (FAILED_LOG(hr = pEntry->Initialize(ASPNETCORE_APP_PATH_ENV_STR, m_struAppVirtualPath.QueryStr())) ||
  216. FAILED_LOG(hr = pEnvironmentVarTable->InsertRecord(pEntry)))
  217. {
  218. goto Finished;
  219. }
  220. Finished:
  221. if (pEntry != NULL)
  222. {
  223. pEntry->Dereference();
  224. pEntry = NULL;
  225. }
  226. return hr;
  227. }
  228. HRESULT
  229. SERVER_PROCESS::SetupAppToken(
  230. ENVIRONMENT_VAR_HASH *pEnvironmentVarTable
  231. )
  232. {
  233. HRESULT hr = S_OK;
  234. UUID logUuid;
  235. PSTR pszLogUuid = NULL;
  236. BOOL fRpcStringAllocd = FALSE;
  237. RPC_STATUS rpcStatus;
  238. STRU strAppToken;
  239. ENVIRONMENT_VAR_ENTRY* pEntry = NULL;
  240. pEnvironmentVarTable->FindKey(ASPNETCORE_APP_TOKEN_ENV_STR, &pEntry);
  241. if (pEntry != NULL)
  242. {
  243. // user sets the environment variable
  244. m_straGuid.Reset();
  245. hr = m_straGuid.CopyW(pEntry->QueryValue());
  246. pEntry->Dereference();
  247. pEntry = NULL;
  248. goto Finished;
  249. }
  250. else
  251. {
  252. if (m_straGuid.IsEmpty())
  253. {
  254. // the GUID has not been set yet
  255. rpcStatus = UuidCreate(&logUuid);
  256. if (rpcStatus != RPC_S_OK)
  257. {
  258. hr = rpcStatus;
  259. goto Finished;
  260. }
  261. rpcStatus = UuidToStringA(&logUuid, (BYTE **)&pszLogUuid);
  262. if (rpcStatus != RPC_S_OK)
  263. {
  264. hr = rpcStatus;
  265. goto Finished;
  266. }
  267. fRpcStringAllocd = TRUE;
  268. if (FAILED_LOG(hr = m_straGuid.Copy(pszLogUuid)))
  269. {
  270. goto Finished;
  271. }
  272. }
  273. pEntry = new ENVIRONMENT_VAR_ENTRY();
  274. if (pEntry == NULL)
  275. {
  276. hr = E_OUTOFMEMORY;
  277. goto Finished;
  278. }
  279. if (FAILED_LOG(strAppToken.CopyA(m_straGuid.QueryStr())) ||
  280. FAILED_LOG(hr = pEntry->Initialize(ASPNETCORE_APP_TOKEN_ENV_STR, strAppToken.QueryStr())) ||
  281. FAILED_LOG(hr = pEnvironmentVarTable->InsertRecord(pEntry)))
  282. {
  283. goto Finished;
  284. }
  285. }
  286. Finished:
  287. if (fRpcStringAllocd)
  288. {
  289. RpcStringFreeA((BYTE **)&pszLogUuid);
  290. pszLogUuid = NULL;
  291. }
  292. if (pEntry != NULL)
  293. {
  294. pEntry->Dereference();
  295. pEntry = NULL;
  296. }
  297. return hr;
  298. }
  299. HRESULT
  300. SERVER_PROCESS::OutputEnvironmentVariables
  301. (
  302. MULTISZ* pmszOutput,
  303. ENVIRONMENT_VAR_HASH* pEnvironmentVarTable
  304. )
  305. {
  306. HRESULT hr = S_OK;
  307. LPWSTR pszEnvironmentVariables = NULL;
  308. LPWSTR pszCurrentVariable = NULL;
  309. LPWSTR pszNextVariable = NULL;
  310. LPWSTR pszEqualChar = NULL;
  311. STRU strEnvVar;
  312. ENVIRONMENT_VAR_ENTRY* pEntry = NULL;
  313. DBG_ASSERT(pmszOutput);
  314. DBG_ASSERT(pEnvironmentVarTable); // We added some startup variables
  315. DBG_ASSERT(pEnvironmentVarTable->Count() >0);
  316. // cleanup, as we may in retry logic
  317. pmszOutput->Reset();
  318. pszEnvironmentVariables = GetEnvironmentStringsW();
  319. if (pszEnvironmentVariables == NULL)
  320. {
  321. hr = HRESULT_FROM_WIN32(ERROR_INVALID_ENVIRONMENT);
  322. goto Finished;
  323. }
  324. pszCurrentVariable = pszEnvironmentVariables;
  325. while (*pszCurrentVariable != L'\0')
  326. {
  327. pszNextVariable = pszCurrentVariable + wcslen(pszCurrentVariable) + 1;
  328. pszEqualChar = wcschr(pszCurrentVariable, L'=');
  329. if (pszEqualChar != NULL)
  330. {
  331. if (FAILED_LOG(hr = strEnvVar.Copy(pszCurrentVariable, (DWORD)(pszEqualChar - pszCurrentVariable) + 1)))
  332. {
  333. goto Finished;
  334. }
  335. pEnvironmentVarTable->FindKey(strEnvVar.QueryStr(), &pEntry);
  336. if (pEntry != NULL)
  337. {
  338. // same env variable is defined in configuration, use it
  339. if (FAILED_LOG(hr = strEnvVar.Append(pEntry->QueryValue())))
  340. {
  341. goto Finished;
  342. }
  343. pmszOutput->Append(strEnvVar); //should we check the returned bool
  344. // remove the record from hash table as we already output it
  345. pEntry->Dereference();
  346. pEnvironmentVarTable->DeleteKey(pEntry->QueryName());
  347. strEnvVar.Reset();
  348. pEntry = NULL;
  349. }
  350. else
  351. {
  352. pmszOutput->Append(pszCurrentVariable);
  353. }
  354. }
  355. else
  356. {
  357. // env varaible is not well formated
  358. hr = HRESULT_FROM_WIN32(ERROR_INVALID_ENVIRONMENT);
  359. goto Finished;
  360. }
  361. // move to next env variable
  362. pszCurrentVariable = pszNextVariable;
  363. }
  364. // append the remaining env variable in hash table
  365. pEnvironmentVarTable->Apply(ENVIRONMENT_VAR_HELPERS::CopyToMultiSz, pmszOutput);
  366. Finished:
  367. if (pszEnvironmentVariables != NULL)
  368. {
  369. FreeEnvironmentStringsW(pszEnvironmentVariables);
  370. pszEnvironmentVariables = NULL;
  371. }
  372. return hr;
  373. }
  374. HRESULT
  375. SERVER_PROCESS::SetupCommandLine(
  376. STRU* pstrCommandLine
  377. )
  378. {
  379. HRESULT hr = S_OK;
  380. LPWSTR pszPath = NULL;
  381. LPWSTR pszFullPath = NULL;
  382. STRU strRelativePath;
  383. DWORD dwBufferSize = 0;
  384. FILE *file = NULL;
  385. DBG_ASSERT(pstrCommandLine);
  386. if (!m_struCommandLine.IsEmpty() &&
  387. pstrCommandLine == (&m_struCommandLine))
  388. {
  389. // already set up the commandline string, skip
  390. goto Finished;
  391. }
  392. pszPath = m_ProcessPath.QueryStr();
  393. if ((wcsstr(pszPath, L":") == NULL) && (wcsstr(pszPath, L"%") == NULL))
  394. {
  395. // let's check whether it is a relative path
  396. if (FAILED_LOG(hr = strRelativePath.Copy(m_struPhysicalPath.QueryStr())) ||
  397. FAILED_LOG(hr = strRelativePath.Append(L"\\")) ||
  398. FAILED_LOG(hr = strRelativePath.Append(pszPath)))
  399. {
  400. goto Finished;
  401. }
  402. dwBufferSize = strRelativePath.QueryCCH() + 1;
  403. pszFullPath = new WCHAR[dwBufferSize];
  404. if (pszFullPath == NULL)
  405. {
  406. hr = E_OUTOFMEMORY;
  407. goto Finished;
  408. }
  409. if (_wfullpath(pszFullPath,
  410. strRelativePath.QueryStr(),
  411. dwBufferSize) == NULL)
  412. {
  413. hr = HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER);
  414. goto Finished;
  415. }
  416. if ((file = _wfsopen(pszFullPath, L"r", _SH_DENYNO)) != NULL)
  417. {
  418. fclose(file);
  419. pszPath = pszFullPath;
  420. }
  421. }
  422. if (FAILED_LOG(hr = pstrCommandLine->Copy(L"\"")) ||
  423. FAILED_LOG(hr = pstrCommandLine->Append(pszPath)) ||
  424. FAILED_LOG(hr = pstrCommandLine->Append(L"\" ")) ||
  425. FAILED_LOG(hr = pstrCommandLine->Append(m_Arguments.QueryStr())))
  426. {
  427. goto Finished;
  428. }
  429. Finished:
  430. if (pszFullPath != NULL)
  431. {
  432. delete pszFullPath;
  433. }
  434. return hr;
  435. }
  436. HRESULT
  437. SERVER_PROCESS::PostStartCheck(
  438. VOID
  439. )
  440. {
  441. HRESULT hr = S_OK;
  442. BOOL fReady = FALSE;
  443. BOOL fProcessMatch = FALSE;
  444. BOOL fDebuggerAttached = FALSE;
  445. DWORD dwTickCount = 0;
  446. DWORD dwTimeDifference = 0;
  447. DWORD dwActualProcessId = 0;
  448. INT iChildProcessIndex = -1;
  449. STACK_STRU(strEventMsg, 256);
  450. if (CheckRemoteDebuggerPresent(m_hProcessHandle, &fDebuggerAttached) == 0)
  451. {
  452. // some error occurred - assume debugger is not attached;
  453. fDebuggerAttached = FALSE;
  454. }
  455. dwTickCount = GetTickCount();
  456. do
  457. {
  458. DWORD processStatus = 0;
  459. if (GetExitCodeProcess(m_hProcessHandle, &processStatus))
  460. {
  461. // make sure the process is still running
  462. if (processStatus != STILL_ACTIVE)
  463. {
  464. // double check
  465. if (GetExitCodeProcess(m_hProcessHandle, &processStatus) && processStatus != STILL_ACTIVE)
  466. {
  467. hr = E_APPLICATION_ACTIVATION_EXEC_FAILURE;
  468. goto Finished;
  469. }
  470. }
  471. }
  472. //
  473. // dwActualProcessId will be set only when NsiAPI(GetExtendedTcpTable) is supported
  474. //
  475. hr = CheckIfServerIsUp(m_dwPort, &dwActualProcessId, &fReady);
  476. fDebuggerAttached = IsDebuggerIsAttached();
  477. if (!fReady)
  478. {
  479. Sleep(250);
  480. }
  481. dwTimeDifference = (GetTickCount() - dwTickCount);
  482. } while (fReady == FALSE &&
  483. ((dwTimeDifference < m_dwStartupTimeLimitInMS) || fDebuggerAttached));
  484. if (!fReady)
  485. {
  486. hr = E_APPLICATION_ACTIVATION_TIMED_OUT;
  487. goto Finished;
  488. }
  489. // register call back with the created process
  490. if (FAILED_LOG(hr = RegisterProcessWait(&m_hProcessWaitHandle, m_hProcessHandle)))
  491. {
  492. goto Finished;
  493. }
  494. //
  495. // check if debugger is attached after startupTimeout.
  496. //
  497. if (!fDebuggerAttached &&
  498. CheckRemoteDebuggerPresent(m_hProcessHandle, &fDebuggerAttached) == 0)
  499. {
  500. // some error occurred - assume debugger is not attached;
  501. fDebuggerAttached = FALSE;
  502. }
  503. //
  504. // NsiAPI(GetExtendedTcpTable) is supported. we should check whether processIds match
  505. //
  506. if (dwActualProcessId == m_dwProcessId)
  507. {
  508. m_dwListeningProcessId = m_dwProcessId;
  509. fProcessMatch = TRUE;
  510. }
  511. if (!fProcessMatch)
  512. {
  513. // could be the scenario that backend creates child process
  514. if (FAILED_LOG(hr = GetChildProcessHandles()))
  515. {
  516. goto Finished;
  517. }
  518. for (DWORD i = 0; i < m_cChildProcess; ++i)
  519. {
  520. // a child process listen on the assigned port
  521. if (dwActualProcessId == m_dwChildProcessIds[i])
  522. {
  523. m_dwListeningProcessId = m_dwChildProcessIds[i];
  524. fProcessMatch = TRUE;
  525. if (m_hChildProcessHandles[i] != NULL)
  526. {
  527. if (fDebuggerAttached == FALSE &&
  528. CheckRemoteDebuggerPresent(m_hChildProcessHandles[i], &fDebuggerAttached) == 0)
  529. {
  530. // some error occurred - assume debugger is not attached;
  531. fDebuggerAttached = FALSE;
  532. }
  533. if (FAILED_LOG(hr = RegisterProcessWait(&m_hChildProcessWaitHandles[i],
  534. m_hChildProcessHandles[i])))
  535. {
  536. goto Finished;
  537. }
  538. iChildProcessIndex = i;
  539. }
  540. break;
  541. }
  542. }
  543. }
  544. if (!fProcessMatch)
  545. {
  546. //
  547. // process that we created is not listening
  548. // on the port we specified.
  549. //
  550. fReady = FALSE;
  551. hr = HRESULT_FROM_WIN32(ERROR_CREATE_FAILED);
  552. strEventMsg.SafeSnwprintf(
  553. ASPNETCORE_EVENT_PROCESS_START_WRONGPORT_ERROR_MSG,
  554. m_struAppFullPath.QueryStr(),
  555. m_struPhysicalPath.QueryStr(),
  556. m_struCommandLine.QueryStr(),
  557. m_dwPort,
  558. hr);
  559. goto Finished;
  560. }
  561. if (!fReady)
  562. {
  563. //
  564. // hr is already set by CheckIfServerIsUp
  565. //
  566. if (dwTimeDifference >= m_dwStartupTimeLimitInMS)
  567. {
  568. hr = HRESULT_FROM_WIN32(ERROR_TIMEOUT);
  569. strEventMsg.SafeSnwprintf(
  570. ASPNETCORE_EVENT_PROCESS_START_NOTREADY_ERROR_MSG,
  571. m_struAppFullPath.QueryStr(),
  572. m_struPhysicalPath.QueryStr(),
  573. m_struCommandLine.QueryStr(),
  574. m_dwPort,
  575. hr);
  576. }
  577. goto Finished;
  578. }
  579. if (iChildProcessIndex >= 0)
  580. {
  581. //
  582. // final check to make sure child process listening on HTTP is still UP
  583. // This is needed because, the child process might have crashed/exited between
  584. // the previous call to checkIfServerIsUp and RegisterProcessWait
  585. // and we would not know about it.
  586. //
  587. hr = CheckIfServerIsUp(m_dwPort, &dwActualProcessId, &fReady);
  588. if ((FAILED_LOG(hr) || fReady == FALSE))
  589. {
  590. strEventMsg.SafeSnwprintf(
  591. ASPNETCORE_EVENT_PROCESS_START_NOTREADY_ERROR_MSG,
  592. m_struAppFullPath.QueryStr(),
  593. m_struPhysicalPath.QueryStr(),
  594. m_struCommandLine.QueryStr(),
  595. m_dwPort,
  596. hr);
  597. goto Finished;
  598. }
  599. }
  600. //
  601. // ready to mark the server process ready but before this,
  602. // create and initialize the FORWARDER_CONNECTION
  603. //
  604. if (m_pForwarderConnection == NULL)
  605. {
  606. m_pForwarderConnection = new FORWARDER_CONNECTION();
  607. if (m_pForwarderConnection == NULL)
  608. {
  609. hr = E_OUTOFMEMORY;
  610. goto Finished;
  611. }
  612. hr = m_pForwarderConnection->Initialize(m_dwPort);
  613. if (FAILED_LOG(hr))
  614. {
  615. goto Finished;
  616. }
  617. }
  618. m_hListeningProcessHandle = OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE | PROCESS_DUP_HANDLE,
  619. FALSE,
  620. m_dwListeningProcessId);
  621. //
  622. // mark server process as Ready
  623. //
  624. m_fReady = TRUE;
  625. Finished:
  626. m_fDebuggerAttached = fDebuggerAttached;
  627. if (FAILED_LOG(hr))
  628. {
  629. if (m_pForwarderConnection != NULL)
  630. {
  631. m_pForwarderConnection->DereferenceForwarderConnection();
  632. m_pForwarderConnection = NULL;
  633. }
  634. if (!strEventMsg.IsEmpty())
  635. {
  636. EventLog::Warn(
  637. ASPNETCORE_EVENT_PROCESS_START_ERROR,
  638. strEventMsg.QueryStr());
  639. }
  640. }
  641. return hr;
  642. }
  643. HRESULT
  644. SERVER_PROCESS::StartProcess(
  645. VOID
  646. )
  647. {
  648. HRESULT hr = S_OK;
  649. PROCESS_INFORMATION processInformation = {0};
  650. STARTUPINFOW startupInfo = {0};
  651. DWORD dwRetryCount = 2; // should we allow customer to config it
  652. DWORD dwCreationFlags = 0;
  653. MULTISZ mszNewEnvironment;
  654. ENVIRONMENT_VAR_HASH *pHashTable = NULL;
  655. PWSTR pStrStage = NULL;
  656. BOOL fCriticalError = FALSE;
  657. std::map<std::wstring, std::wstring, ignore_case_comparer> variables;
  658. GetStartupInfoW(&startupInfo);
  659. //
  660. // setup stdout and stderr handles to our stdout handle only if
  661. // the handle is valid.
  662. //
  663. SetupStdHandles(&startupInfo);
  664. while (dwRetryCount > 0)
  665. {
  666. m_dwPort = 0;
  667. dwRetryCount--;
  668. //
  669. // generate process command line.
  670. //
  671. if (FAILED_LOG(hr = SetupCommandLine(&m_struCommandLine)))
  672. {
  673. pStrStage = L"SetupCommandLine";
  674. goto Failure;
  675. }
  676. try
  677. {
  678. variables = ENVIRONMENT_VAR_HELPERS::InitEnvironmentVariablesTable(
  679. m_pEnvironmentVarTable,
  680. m_fWindowsAuthEnabled,
  681. m_fBasicAuthEnabled,
  682. m_fAnonymousAuthEnabled,
  683. true, // fAddHostingStartup
  684. m_struAppFullPath.QueryStr(),
  685. m_struHttpsPort.QueryStr());
  686. variables = ENVIRONMENT_VAR_HELPERS::AddWebsocketEnabledToEnvironmentVariables(variables, m_fWebSocketSupported);
  687. }
  688. CATCH_RETURN();
  689. pHashTable = new ENVIRONMENT_VAR_HASH();
  690. RETURN_IF_FAILED(pHashTable->Initialize(37 /*prime*/));
  691. // Copy environment variables to old style hash table
  692. for (auto & variable : variables)
  693. {
  694. auto pNewEntry = std::unique_ptr<ENVIRONMENT_VAR_ENTRY, ENVIRONMENT_VAR_ENTRY_DELETER>(new ENVIRONMENT_VAR_ENTRY());
  695. RETURN_IF_FAILED(pNewEntry->Initialize((variable.first + L"=").c_str(), variable.second.c_str()));
  696. RETURN_IF_FAILED(pHashTable->InsertRecord(pNewEntry.get()));
  697. }
  698. //
  699. // setup the the port that the backend process will listen on
  700. //
  701. if (FAILED_LOG(hr = SetupListenPort(pHashTable, &fCriticalError)))
  702. {
  703. pStrStage = L"SetupListenPort";
  704. goto Failure;
  705. }
  706. //
  707. // get app path
  708. //
  709. if (FAILED_LOG(hr = SetupAppPath(pHashTable)))
  710. {
  711. pStrStage = L"SetupAppPath";
  712. goto Failure;
  713. }
  714. //
  715. // generate new guid for each process
  716. //
  717. if (FAILED_LOG(hr = SetupAppToken(pHashTable)))
  718. {
  719. pStrStage = L"SetupAppToken";
  720. goto Failure;
  721. }
  722. //
  723. // setup environment variables for new process
  724. //
  725. if (FAILED_LOG(hr = OutputEnvironmentVariables(&mszNewEnvironment, pHashTable)))
  726. {
  727. pStrStage = L"OutputEnvironmentVariables";
  728. goto Failure;
  729. }
  730. dwCreationFlags = CREATE_NO_WINDOW |
  731. CREATE_UNICODE_ENVIRONMENT |
  732. CREATE_SUSPENDED |
  733. CREATE_NEW_PROCESS_GROUP;
  734. if (!CreateProcessW(
  735. NULL, // applicationName
  736. m_struCommandLine.QueryStr(),
  737. NULL, // processAttr
  738. NULL, // threadAttr
  739. TRUE, // inheritHandles
  740. dwCreationFlags,
  741. mszNewEnvironment.QueryStr(),
  742. m_struPhysicalPath.QueryStr(), // currentDir
  743. &startupInfo,
  744. &processInformation))
  745. {
  746. pStrStage = L"CreateProcessW";
  747. hr = HRESULT_FROM_WIN32(GetLastError());
  748. goto Failure;
  749. }
  750. m_hProcessHandle = processInformation.hProcess;
  751. m_dwProcessId = processInformation.dwProcessId;
  752. if (FAILED_LOG(hr = SetupJobObject()))
  753. {
  754. pStrStage = L"SetupJobObject";
  755. goto Failure;
  756. }
  757. if (m_hJobObject != NULL)
  758. {
  759. if (!AssignProcessToJobObject(m_hJobObject, m_hProcessHandle))
  760. {
  761. hr = HRESULT_FROM_WIN32(GetLastError());
  762. if (hr != HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED))
  763. {
  764. pStrStage = L"AssignProcessToJobObject";
  765. goto Failure;
  766. }
  767. }
  768. }
  769. if (ResumeThread(processInformation.hThread) == -1)
  770. {
  771. pStrStage = L"ResumeThread";
  772. hr = HRESULT_FROM_WIN32(GetLastError());
  773. goto Failure;
  774. }
  775. //
  776. // need to make sure the server is up and listening on the port specified.
  777. //
  778. if (FAILED_LOG(hr = PostStartCheck()))
  779. {
  780. pStrStage = L"PostStartCheck";
  781. goto Failure;
  782. }
  783. // Backend process starts successfully. Set retry counter to 0
  784. dwRetryCount = 0;
  785. EventLog::Info(
  786. ASPNETCORE_EVENT_PROCESS_START_SUCCESS,
  787. ASPNETCORE_EVENT_PROCESS_START_SUCCESS_MSG,
  788. m_struAppFullPath.QueryStr(),
  789. m_dwProcessId,
  790. m_dwListeningProcessId,
  791. m_dwPort);
  792. goto Finished;
  793. Failure:
  794. if (fCriticalError)
  795. {
  796. // Critical error, no retry need to avoid wasting resource and polluting log
  797. dwRetryCount = 0;
  798. }
  799. EventLog::Warn(
  800. ASPNETCORE_EVENT_PROCESS_START_ERROR,
  801. ASPNETCORE_EVENT_PROCESS_START_ERROR_MSG,
  802. m_struAppFullPath.QueryStr(),
  803. m_struPhysicalPath.QueryStr(),
  804. m_struCommandLine.QueryStr(),
  805. pStrStage,
  806. hr,
  807. m_dwPort,
  808. dwRetryCount);
  809. if (processInformation.hThread != NULL)
  810. {
  811. CloseHandle(processInformation.hThread);
  812. processInformation.hThread = NULL;
  813. }
  814. if (pHashTable != NULL)
  815. {
  816. pHashTable->Clear();
  817. delete pHashTable;
  818. pHashTable = NULL;
  819. }
  820. CleanUp();
  821. }
  822. Finished:
  823. if (FAILED_LOG(hr) || m_fReady == FALSE)
  824. {
  825. if (m_hStdErrWritePipe != NULL)
  826. {
  827. if (m_hStdErrWritePipe != INVALID_HANDLE_VALUE)
  828. {
  829. CloseHandle(m_hStdErrWritePipe);
  830. }
  831. m_hStdErrWritePipe = NULL;
  832. }
  833. if (m_hStdoutHandle != NULL)
  834. {
  835. if (m_hStdoutHandle != INVALID_HANDLE_VALUE)
  836. {
  837. CloseHandle(m_hStdoutHandle);
  838. }
  839. m_hStdoutHandle = NULL;
  840. }
  841. if (m_fStdoutLogEnabled)
  842. {
  843. m_Timer.CancelTimer();
  844. }
  845. EventLog::Error(
  846. ASPNETCORE_EVENT_PROCESS_START_FAILURE,
  847. ASPNETCORE_EVENT_PROCESS_START_FAILURE_MSG,
  848. m_struAppFullPath.QueryStr(),
  849. m_struPhysicalPath.QueryStr(),
  850. m_struCommandLine.QueryStr(),
  851. m_dwPort,
  852. m_output.str().c_str());
  853. }
  854. return hr;
  855. }
  856. HRESULT
  857. SERVER_PROCESS::SetWindowsAuthToken(
  858. HANDLE hToken,
  859. LPHANDLE pTargetTokenHandle
  860. )
  861. {
  862. HRESULT hr = S_OK;
  863. if (m_hListeningProcessHandle != NULL && m_hListeningProcessHandle != INVALID_HANDLE_VALUE)
  864. {
  865. if (!DuplicateHandle( GetCurrentProcess(),
  866. hToken,
  867. m_hListeningProcessHandle,
  868. pTargetTokenHandle,
  869. 0,
  870. FALSE,
  871. DUPLICATE_SAME_ACCESS ))
  872. {
  873. hr = HRESULT_FROM_WIN32(GetLastError());
  874. goto Finished;
  875. }
  876. }
  877. Finished:
  878. return hr;
  879. }
  880. HRESULT
  881. SERVER_PROCESS::SetupStdHandles(
  882. LPSTARTUPINFOW pStartupInfo
  883. )
  884. {
  885. HRESULT hr = S_OK;
  886. SYSTEMTIME systemTime;
  887. SECURITY_ATTRIBUTES saAttr = { 0 };
  888. STRU struPath;
  889. DBG_ASSERT(pStartupInfo);
  890. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  891. saAttr.bInheritHandle = TRUE;
  892. saAttr.lpSecurityDescriptor = NULL;
  893. if (!m_fEnableOutOfProcessConsoleRedirection)
  894. {
  895. pStartupInfo->dwFlags = STARTF_USESTDHANDLES;
  896. pStartupInfo->hStdInput = INVALID_HANDLE_VALUE;
  897. pStartupInfo->hStdError = INVALID_HANDLE_VALUE;
  898. pStartupInfo->hStdOutput = INVALID_HANDLE_VALUE;
  899. return hr;
  900. }
  901. if (!m_fStdoutLogEnabled)
  902. {
  903. CreatePipe(&m_hStdoutHandle, &m_hStdErrWritePipe, &saAttr, 0 /*nSize*/);
  904. // Read the stderr handle on a separate thread until we get 30Kb.
  905. m_hReadThread = CreateThread(
  906. nullptr, // default security attributes
  907. 0, // default stack size
  908. reinterpret_cast<LPTHREAD_START_ROUTINE>(ReadStdErrHandle),
  909. this, // thread function arguments
  910. 0, // default creation flags
  911. nullptr); // receive thread identifier
  912. pStartupInfo->dwFlags = STARTF_USESTDHANDLES;
  913. pStartupInfo->hStdInput = INVALID_HANDLE_VALUE;
  914. pStartupInfo->hStdError = m_hStdErrWritePipe;
  915. pStartupInfo->hStdOutput = m_hStdErrWritePipe;
  916. return hr;
  917. }
  918. hr = FILE_UTILITY::ConvertPathToFullPath(
  919. m_struLogFile.QueryStr(),
  920. m_struPhysicalPath.QueryStr(),
  921. &struPath);
  922. if (FAILED_LOG(hr))
  923. {
  924. goto Finished;
  925. }
  926. GetSystemTime(&systemTime);
  927. hr = m_struFullLogFile.SafeSnwprintf(L"%s_%d%02d%02d%02d%02d%02d_%d.log",
  928. struPath.QueryStr(),
  929. systemTime.wYear,
  930. systemTime.wMonth,
  931. systemTime.wDay,
  932. systemTime.wHour,
  933. systemTime.wMinute,
  934. systemTime.wSecond,
  935. GetCurrentProcessId());
  936. if (FAILED_LOG(hr))
  937. {
  938. goto Finished;
  939. }
  940. hr = FILE_UTILITY::EnsureDirectoryPathExists(struPath.QueryStr());
  941. if (FAILED_LOG(hr))
  942. {
  943. goto Finished;
  944. }
  945. m_hStdoutHandle = CreateFileW(m_struFullLogFile.QueryStr(),
  946. FILE_WRITE_DATA,
  947. FILE_SHARE_READ,
  948. &saAttr,
  949. CREATE_ALWAYS,
  950. FILE_ATTRIBUTE_NORMAL,
  951. NULL);
  952. if (m_hStdoutHandle == INVALID_HANDLE_VALUE)
  953. {
  954. hr = HRESULT_FROM_WIN32(GetLastError());
  955. goto Finished;
  956. }
  957. pStartupInfo->dwFlags = STARTF_USESTDHANDLES;
  958. pStartupInfo->hStdInput = INVALID_HANDLE_VALUE;
  959. pStartupInfo->hStdError = m_hStdoutHandle;
  960. pStartupInfo->hStdOutput = m_hStdoutHandle;
  961. // start timer to open and close handles regularly.
  962. m_Timer.InitializeTimer(STTIMER::TimerCallback, &m_struFullLogFile, 3000, 3000);
  963. Finished:
  964. if (FAILED_LOG(hr))
  965. {
  966. pStartupInfo->dwFlags = STARTF_USESTDHANDLES;
  967. pStartupInfo->hStdInput = INVALID_HANDLE_VALUE;
  968. pStartupInfo->hStdError = INVALID_HANDLE_VALUE;
  969. pStartupInfo->hStdOutput = INVALID_HANDLE_VALUE;
  970. if (m_fStdoutLogEnabled)
  971. {
  972. // Log the error
  973. EventLog::Warn(
  974. ASPNETCORE_EVENT_CONFIG_ERROR,
  975. ASPNETCORE_EVENT_INVALID_STDOUT_LOG_FILE_MSG,
  976. m_struFullLogFile.IsEmpty()? m_struLogFile.QueryStr() : m_struFullLogFile.QueryStr(),
  977. hr);
  978. }
  979. // The log file was not created yet in case of failure. No need to clean it
  980. m_struFullLogFile.Reset();
  981. }
  982. return hr;
  983. }
  984. void
  985. SERVER_PROCESS::ReadStdErrHandle(
  986. LPVOID pContext
  987. )
  988. {
  989. auto pLoggingProvider = static_cast<SERVER_PROCESS*>(pContext);
  990. DBG_ASSERT(pLoggingProvider != NULL);
  991. pLoggingProvider->ReadStdErrHandleInternal();
  992. }
  993. void
  994. SERVER_PROCESS::ReadStdErrHandleInternal()
  995. {
  996. const size_t bufferSize = 4096;
  997. size_t charactersLeft = 30000;
  998. std::string tempBuffer;
  999. tempBuffer.resize(bufferSize);
  1000. DWORD dwNumBytesRead = 0;
  1001. while (charactersLeft > 0)
  1002. {
  1003. if (ReadFile(m_hStdoutHandle,
  1004. tempBuffer.data(),
  1005. bufferSize,
  1006. &dwNumBytesRead,
  1007. nullptr))
  1008. {
  1009. auto text = to_wide_string(tempBuffer, dwNumBytesRead, GetConsoleOutputCP());
  1010. auto const writeSize = min(charactersLeft, text.size());
  1011. m_output.write(text.c_str(), writeSize);
  1012. charactersLeft -= writeSize;
  1013. }
  1014. else
  1015. {
  1016. return;
  1017. }
  1018. }
  1019. // Continue reading from console out until the program ends or the handle is invalid.
  1020. // Otherwise, the program may hang as nothing is reading stdout.
  1021. while (ReadFile(m_hStdoutHandle,
  1022. tempBuffer.data(),
  1023. bufferSize,
  1024. &dwNumBytesRead,
  1025. nullptr))
  1026. {
  1027. }
  1028. }
  1029. HRESULT
  1030. SERVER_PROCESS::CheckIfServerIsUp(
  1031. _In_ DWORD dwPort,
  1032. _Out_ DWORD * pdwProcessId,
  1033. _Out_ BOOL * pfReady
  1034. )
  1035. {
  1036. HRESULT hr = S_OK;
  1037. DWORD dwResult = ERROR_INSUFFICIENT_BUFFER;
  1038. MIB_TCPTABLE_OWNER_PID *pTCPInfo = NULL;
  1039. MIB_TCPROW_OWNER_PID *pOwner = NULL;
  1040. DWORD dwSize = 1000; // Initial size for pTCPInfo buffer
  1041. int iResult = 0;
  1042. SOCKET socketCheck = INVALID_SOCKET;
  1043. DBG_ASSERT(pfReady);
  1044. DBG_ASSERT(pdwProcessId);
  1045. *pfReady = FALSE;
  1046. //
  1047. // it's OK for us to return processID 0 in case we cannot detect the real one
  1048. //
  1049. *pdwProcessId = 0;
  1050. while (dwResult == ERROR_INSUFFICIENT_BUFFER)
  1051. {
  1052. // Increase the buffer size with additional space, MIB_TCPROW 20 bytes
  1053. // New entries may be added by other processes before calling GetExtendedTcpTable
  1054. dwSize += 200;
  1055. if (pTCPInfo != NULL)
  1056. {
  1057. HeapFree(GetProcessHeap(), 0, pTCPInfo);
  1058. }
  1059. pTCPInfo = (MIB_TCPTABLE_OWNER_PID*)HeapAlloc(GetProcessHeap(), 0, dwSize);
  1060. if (pTCPInfo == NULL)
  1061. {
  1062. hr = E_OUTOFMEMORY;
  1063. goto Finished;
  1064. }
  1065. dwResult = GetExtendedTcpTable(pTCPInfo,
  1066. &dwSize,
  1067. FALSE,
  1068. AF_INET,
  1069. TCP_TABLE_OWNER_PID_LISTENER,
  1070. 0);
  1071. if (dwResult != NO_ERROR && dwResult != ERROR_INSUFFICIENT_BUFFER)
  1072. {
  1073. hr = HRESULT_FROM_WIN32(dwResult);
  1074. goto Finished;
  1075. }
  1076. }
  1077. // iterate pTcpInfo struct to find PID/PORT entry
  1078. for (DWORD dwLoop = 0; dwLoop < pTCPInfo->dwNumEntries; dwLoop++)
  1079. {
  1080. pOwner = &pTCPInfo->table[dwLoop];
  1081. if (ntohs((USHORT)pOwner->dwLocalPort) == dwPort)
  1082. {
  1083. *pdwProcessId = pOwner->dwOwningPid;
  1084. *pfReady = TRUE;
  1085. break;
  1086. }
  1087. }
  1088. Finished:
  1089. if (socketCheck != INVALID_SOCKET)
  1090. {
  1091. iResult = closesocket(socketCheck);
  1092. if (iResult == SOCKET_ERROR)
  1093. {
  1094. hr = HRESULT_FROM_WIN32(WSAGetLastError());
  1095. }
  1096. socketCheck = INVALID_SOCKET;
  1097. }
  1098. if (pTCPInfo != NULL)
  1099. {
  1100. HeapFree(GetProcessHeap(), 0, pTCPInfo);
  1101. pTCPInfo = NULL;
  1102. }
  1103. return hr;
  1104. }
  1105. // send signal to the process to let it gracefully shutdown
  1106. // if the process cannot shutdown within given time, terminate it
  1107. VOID
  1108. SERVER_PROCESS::SendSignal(
  1109. VOID
  1110. )
  1111. {
  1112. HRESULT hr = S_OK;
  1113. HANDLE hThread = NULL;
  1114. ReferenceServerProcess();
  1115. m_hShutdownHandle = OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE, FALSE, m_dwProcessId);
  1116. if (m_hShutdownHandle == NULL)
  1117. {
  1118. // since we cannot open the process. let's terminate the process
  1119. hr = HRESULT_FROM_WIN32(GetLastError());
  1120. goto Finished;
  1121. }
  1122. hThread = CreateThread(
  1123. NULL, // default security attributes
  1124. 0, // default stack size
  1125. (LPTHREAD_START_ROUTINE)SendShutDownSignal,
  1126. this, // thread function arguments
  1127. 0, // default creation flags
  1128. NULL); // receive thread identifier
  1129. if (hThread == NULL)
  1130. {
  1131. hr = HRESULT_FROM_WIN32(GetLastError());
  1132. goto Finished;
  1133. }
  1134. //
  1135. // Reset the shutdown timeout if debugger is attached.
  1136. // Do it only for the case that debugger is attached during process creation
  1137. // as IsDebuggerIsAttached call is too heavy
  1138. //
  1139. if (WaitForSingleObject(m_hShutdownHandle, m_fDebuggerAttached ? INFINITE : m_dwShutdownTimeLimitInMS) != WAIT_OBJECT_0)
  1140. {
  1141. hr = HRESULT_FROM_WIN32(ERROR_TIMEOUT);
  1142. goto Finished;
  1143. }
  1144. // thread should already exit
  1145. CloseHandle(hThread);
  1146. hThread = NULL;
  1147. Finished:
  1148. if (hThread != NULL)
  1149. {
  1150. // if the send shutdown message thread is still running, terminate it
  1151. DWORD dwThreadStatus = 0;
  1152. if (GetExitCodeThread(hThread, &dwThreadStatus)!= 0 && dwThreadStatus == STILL_ACTIVE)
  1153. {
  1154. TerminateThread(hThread, STATUS_CONTROL_C_EXIT);
  1155. }
  1156. CloseHandle(hThread);
  1157. hThread = NULL;
  1158. }
  1159. if (FAILED_LOG(hr))
  1160. {
  1161. TerminateBackendProcess();
  1162. }
  1163. if (m_hShutdownHandle != NULL && m_hShutdownHandle != INVALID_HANDLE_VALUE)
  1164. {
  1165. CloseHandle(m_hShutdownHandle);
  1166. m_hShutdownHandle = NULL;
  1167. }
  1168. DereferenceServerProcess();
  1169. }
  1170. //
  1171. // StopProcess is only called if process crashes OR if the process
  1172. // creation failed and calling this counts towards RapidFailCounts.
  1173. //
  1174. VOID
  1175. SERVER_PROCESS::StopProcess(
  1176. VOID
  1177. )
  1178. {
  1179. m_fReady = FALSE;
  1180. m_pProcessManager->IncrementRapidFailCount();
  1181. for (INT i=0; i<MAX_ACTIVE_CHILD_PROCESSES; ++i)
  1182. {
  1183. if (m_hChildProcessHandles[i] != NULL)
  1184. {
  1185. if (m_hChildProcessHandles[i] != INVALID_HANDLE_VALUE)
  1186. {
  1187. TerminateProcess(m_hChildProcessHandles[i], 0);
  1188. CloseHandle(m_hChildProcessHandles[i]);
  1189. }
  1190. m_hChildProcessHandles[i] = NULL;
  1191. m_dwChildProcessIds[i] = 0;
  1192. }
  1193. }
  1194. if (m_hProcessHandle != NULL)
  1195. {
  1196. if (m_hProcessHandle != INVALID_HANDLE_VALUE)
  1197. {
  1198. TerminateProcess(m_hProcessHandle, 0);
  1199. CloseHandle(m_hProcessHandle);
  1200. }
  1201. m_hProcessHandle = NULL;
  1202. }
  1203. }
  1204. BOOL
  1205. SERVER_PROCESS::IsDebuggerIsAttached(
  1206. VOID
  1207. )
  1208. {
  1209. HRESULT hr = S_OK;
  1210. PJOBOBJECT_BASIC_PROCESS_ID_LIST processList = NULL;
  1211. DWORD dwPid = 0;
  1212. DWORD dwWorkerProcessPid = 0;
  1213. DWORD cbNumBytes = 1024;
  1214. DWORD dwRetries = 0;
  1215. DWORD dwError = NO_ERROR;
  1216. BOOL fDebuggerPresent = FALSE;
  1217. dwWorkerProcessPid = GetCurrentProcessId();
  1218. do
  1219. {
  1220. dwError = NO_ERROR;
  1221. if (processList != NULL)
  1222. {
  1223. HeapFree(GetProcessHeap(), 0, processList);
  1224. processList = NULL;
  1225. // resize
  1226. cbNumBytes = cbNumBytes * 2;
  1227. }
  1228. processList = (PJOBOBJECT_BASIC_PROCESS_ID_LIST) HeapAlloc(
  1229. GetProcessHeap(),
  1230. 0,
  1231. cbNumBytes
  1232. );
  1233. if (processList == NULL)
  1234. {
  1235. hr = E_OUTOFMEMORY;
  1236. goto Finished;
  1237. }
  1238. RtlZeroMemory(processList, cbNumBytes);
  1239. if (!QueryInformationJobObject(
  1240. m_hJobObject,
  1241. JobObjectBasicProcessIdList,
  1242. processList,
  1243. cbNumBytes,
  1244. NULL))
  1245. {
  1246. dwError = GetLastError();
  1247. if (dwError != ERROR_MORE_DATA)
  1248. {
  1249. hr = HRESULT_FROM_WIN32(dwError);
  1250. goto Finished;
  1251. }
  1252. }
  1253. } while (dwRetries++ < 5 &&
  1254. processList != NULL &&
  1255. (processList->NumberOfAssignedProcesses > processList->NumberOfProcessIdsInList ||
  1256. processList->NumberOfProcessIdsInList == 0));
  1257. if (dwError == ERROR_MORE_DATA)
  1258. {
  1259. hr = E_OUTOFMEMORY;
  1260. // some error
  1261. goto Finished;
  1262. }
  1263. if (processList == NULL ||
  1264. (processList->NumberOfAssignedProcesses > processList->NumberOfProcessIdsInList ||
  1265. processList->NumberOfProcessIdsInList == 0))
  1266. {
  1267. hr = HRESULT_FROM_WIN32(ERROR_PROCESS_ABORTED);
  1268. // some error
  1269. goto Finished;
  1270. }
  1271. if (processList->NumberOfProcessIdsInList > MAX_ACTIVE_CHILD_PROCESSES)
  1272. {
  1273. hr = HRESULT_FROM_WIN32(ERROR_CREATE_FAILED);
  1274. goto Finished;
  1275. }
  1276. for (DWORD i=0; i<processList->NumberOfProcessIdsInList; i++)
  1277. {
  1278. dwPid = (DWORD)processList->ProcessIdList[i];
  1279. if (dwPid != dwWorkerProcessPid)
  1280. {
  1281. HANDLE hProcess = OpenProcess(
  1282. PROCESS_QUERY_INFORMATION | SYNCHRONIZE | PROCESS_TERMINATE | PROCESS_DUP_HANDLE,
  1283. FALSE,
  1284. dwPid);
  1285. BOOL returnValue = CheckRemoteDebuggerPresent(hProcess, &fDebuggerPresent);
  1286. if (hProcess != NULL)
  1287. {
  1288. CloseHandle(hProcess);
  1289. hProcess = NULL;
  1290. }
  1291. if (!returnValue)
  1292. {
  1293. goto Finished;
  1294. }
  1295. if (fDebuggerPresent)
  1296. {
  1297. break;
  1298. }
  1299. }
  1300. }
  1301. Finished:
  1302. if (processList != NULL)
  1303. {
  1304. HeapFree(GetProcessHeap(), 0, processList);
  1305. }
  1306. return fDebuggerPresent;
  1307. }
  1308. HRESULT
  1309. SERVER_PROCESS::GetChildProcessHandles(
  1310. VOID
  1311. )
  1312. {
  1313. HRESULT hr = S_OK;
  1314. PJOBOBJECT_BASIC_PROCESS_ID_LIST processList = NULL;
  1315. DWORD dwPid = 0;
  1316. DWORD dwWorkerProcessPid = 0;
  1317. DWORD cbNumBytes = 1024;
  1318. DWORD dwRetries = 0;
  1319. DWORD dwError = NO_ERROR;
  1320. dwWorkerProcessPid = GetCurrentProcessId();
  1321. do
  1322. {
  1323. dwError = NO_ERROR;
  1324. if (processList != NULL)
  1325. {
  1326. HeapFree(GetProcessHeap(), 0, processList);
  1327. processList = NULL;
  1328. // resize
  1329. cbNumBytes = cbNumBytes * 2;
  1330. }
  1331. processList = (PJOBOBJECT_BASIC_PROCESS_ID_LIST) HeapAlloc(
  1332. GetProcessHeap(),
  1333. 0,
  1334. cbNumBytes
  1335. );
  1336. if (processList == NULL)
  1337. {
  1338. hr = E_OUTOFMEMORY;
  1339. goto Finished;
  1340. }
  1341. RtlZeroMemory(processList, cbNumBytes);
  1342. if (!QueryInformationJobObject(
  1343. m_hJobObject,
  1344. JobObjectBasicProcessIdList,
  1345. processList,
  1346. cbNumBytes,
  1347. NULL))
  1348. {
  1349. dwError = GetLastError();
  1350. if (dwError != ERROR_MORE_DATA)
  1351. {
  1352. hr = HRESULT_FROM_WIN32(dwError);
  1353. goto Finished;
  1354. }
  1355. }
  1356. } while (dwRetries++ < 5 &&
  1357. processList != NULL &&
  1358. (processList->NumberOfAssignedProcesses > processList->NumberOfProcessIdsInList || processList->NumberOfProcessIdsInList == 0));
  1359. if (dwError == ERROR_MORE_DATA)
  1360. {
  1361. hr = E_OUTOFMEMORY;
  1362. // some error
  1363. goto Finished;
  1364. }
  1365. if (processList == NULL || (processList->NumberOfAssignedProcesses > processList->NumberOfProcessIdsInList || processList->NumberOfProcessIdsInList == 0))
  1366. {
  1367. hr = HRESULT_FROM_WIN32(ERROR_PROCESS_ABORTED);
  1368. // some error
  1369. goto Finished;
  1370. }
  1371. if (processList->NumberOfProcessIdsInList > MAX_ACTIVE_CHILD_PROCESSES)
  1372. {
  1373. hr = HRESULT_FROM_WIN32(ERROR_CREATE_FAILED);
  1374. goto Finished;
  1375. }
  1376. for (DWORD i=0; i<processList->NumberOfProcessIdsInList; i++)
  1377. {
  1378. dwPid = (DWORD)processList->ProcessIdList[i];
  1379. if (dwPid != m_dwProcessId &&
  1380. dwPid != dwWorkerProcessPid )
  1381. {
  1382. m_hChildProcessHandles[m_cChildProcess] = OpenProcess(
  1383. PROCESS_QUERY_INFORMATION | SYNCHRONIZE | PROCESS_TERMINATE | PROCESS_DUP_HANDLE,
  1384. FALSE,
  1385. dwPid
  1386. );
  1387. m_dwChildProcessIds[m_cChildProcess] = dwPid;
  1388. m_cChildProcess ++;
  1389. }
  1390. }
  1391. Finished:
  1392. if (processList != NULL)
  1393. {
  1394. HeapFree(GetProcessHeap(), 0, processList);
  1395. }
  1396. return hr;
  1397. }
  1398. HRESULT
  1399. SERVER_PROCESS::StopAllProcessesInJobObject(
  1400. VOID
  1401. )
  1402. {
  1403. HRESULT hr = S_OK;
  1404. PJOBOBJECT_BASIC_PROCESS_ID_LIST processList = NULL;
  1405. HANDLE hProcess = NULL;
  1406. DWORD dwWorkerProcessPid = 0;
  1407. DWORD cbNumBytes = 1024;
  1408. DWORD dwRetries = 0;
  1409. dwWorkerProcessPid = GetCurrentProcessId();
  1410. do
  1411. {
  1412. if (processList != NULL)
  1413. {
  1414. HeapFree(GetProcessHeap(), 0, processList);
  1415. processList = NULL;
  1416. // resize
  1417. cbNumBytes = cbNumBytes * 2;
  1418. }
  1419. processList = (PJOBOBJECT_BASIC_PROCESS_ID_LIST) HeapAlloc(
  1420. GetProcessHeap(),
  1421. 0,
  1422. cbNumBytes
  1423. );
  1424. if (processList == NULL)
  1425. {
  1426. hr = E_OUTOFMEMORY;
  1427. goto Finished;
  1428. }
  1429. RtlZeroMemory(processList, cbNumBytes);
  1430. if (!QueryInformationJobObject(
  1431. m_hJobObject,
  1432. JobObjectBasicProcessIdList,
  1433. processList,
  1434. cbNumBytes,
  1435. NULL))
  1436. {
  1437. DWORD dwError = GetLastError();
  1438. if (dwError != ERROR_MORE_DATA)
  1439. {
  1440. hr = HRESULT_FROM_WIN32(dwError);
  1441. goto Finished;
  1442. }
  1443. }
  1444. } while (dwRetries++ < 5 &&
  1445. processList != NULL &&
  1446. (processList->NumberOfAssignedProcesses > processList->NumberOfProcessIdsInList || processList->NumberOfProcessIdsInList == 0));
  1447. if (processList == NULL || (processList->NumberOfAssignedProcesses > processList->NumberOfProcessIdsInList || processList->NumberOfProcessIdsInList == 0))
  1448. {
  1449. hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
  1450. // some error
  1451. goto Finished;
  1452. }
  1453. for (DWORD i=0; i<processList->NumberOfProcessIdsInList; i++)
  1454. {
  1455. if (dwWorkerProcessPid != (DWORD)processList->ProcessIdList[i])
  1456. {
  1457. hProcess = OpenProcess(PROCESS_TERMINATE,
  1458. FALSE,
  1459. (DWORD)processList->ProcessIdList[i]);
  1460. if (hProcess != NULL)
  1461. {
  1462. if (!TerminateProcess(hProcess, 1))
  1463. {
  1464. hr = HRESULT_FROM_WIN32(GetLastError());
  1465. }
  1466. else
  1467. {
  1468. WaitForSingleObject(hProcess, INFINITE);
  1469. }
  1470. if (hProcess != NULL)
  1471. {
  1472. CloseHandle(hProcess);
  1473. hProcess = NULL;
  1474. }
  1475. }
  1476. }
  1477. }
  1478. Finished:
  1479. if (processList != NULL)
  1480. {
  1481. HeapFree(GetProcessHeap(), 0, processList);
  1482. }
  1483. return hr;
  1484. }
  1485. SERVER_PROCESS::SERVER_PROCESS() :
  1486. m_cRefs(1),
  1487. m_hProcessHandle(NULL),
  1488. m_hProcessWaitHandle(NULL),
  1489. m_dwProcessId(0),
  1490. m_cChildProcess(0),
  1491. m_fReady(FALSE),
  1492. m_lStopping(0L),
  1493. m_hStdoutHandle(NULL),
  1494. m_fStdoutLogEnabled(FALSE),
  1495. m_hJobObject(NULL),
  1496. m_pForwarderConnection(NULL),
  1497. m_dwListeningProcessId(0),
  1498. m_hListeningProcessHandle(NULL),
  1499. m_hShutdownHandle(NULL),
  1500. m_hStdErrWritePipe(NULL),
  1501. m_hReadThread(nullptr),
  1502. m_randomGenerator(std::random_device()())
  1503. {
  1504. //InterlockedIncrement(&g_dwActiveServerProcesses);
  1505. for (INT i=0; i<MAX_ACTIVE_CHILD_PROCESSES; ++i)
  1506. {
  1507. m_dwChildProcessIds[i] = 0;
  1508. m_hChildProcessHandles[i] = NULL;
  1509. m_hChildProcessWaitHandles[i] = NULL;
  1510. }
  1511. }
  1512. VOID
  1513. SERVER_PROCESS::CleanUp()
  1514. {
  1515. if (m_hProcessWaitHandle != NULL)
  1516. {
  1517. UnregisterWait(m_hProcessWaitHandle);
  1518. m_hProcessWaitHandle = NULL;
  1519. }
  1520. for (INT i = 0; i<MAX_ACTIVE_CHILD_PROCESSES; ++i)
  1521. {
  1522. if (m_hChildProcessWaitHandles[i] != NULL)
  1523. {
  1524. UnregisterWait(m_hChildProcessWaitHandles[i]);
  1525. m_hChildProcessWaitHandles[i] = NULL;
  1526. }
  1527. }
  1528. if (m_hProcessHandle != NULL)
  1529. {
  1530. if (m_hProcessHandle != INVALID_HANDLE_VALUE)
  1531. {
  1532. TerminateProcess(m_hProcessHandle, 1);
  1533. CloseHandle(m_hProcessHandle);
  1534. }
  1535. m_hProcessHandle = NULL;
  1536. }
  1537. if (m_hListeningProcessHandle != NULL)
  1538. {
  1539. if (m_hListeningProcessHandle != INVALID_HANDLE_VALUE)
  1540. {
  1541. CloseHandle(m_hListeningProcessHandle);
  1542. }
  1543. m_hListeningProcessHandle = NULL;
  1544. }
  1545. for (INT i = 0; i<MAX_ACTIVE_CHILD_PROCESSES; ++i)
  1546. {
  1547. if (m_hChildProcessHandles[i] != NULL)
  1548. {
  1549. if (m_hChildProcessHandles[i] != INVALID_HANDLE_VALUE)
  1550. {
  1551. TerminateProcess(m_hChildProcessHandles[i], 1);
  1552. CloseHandle(m_hChildProcessHandles[i]);
  1553. }
  1554. m_hChildProcessHandles[i] = NULL;
  1555. m_dwChildProcessIds[i] = 0;
  1556. }
  1557. }
  1558. if (m_hJobObject != NULL)
  1559. {
  1560. if (m_hJobObject != INVALID_HANDLE_VALUE)
  1561. {
  1562. CloseHandle(m_hJobObject);
  1563. }
  1564. m_hJobObject = NULL;
  1565. }
  1566. if (m_pForwarderConnection != NULL)
  1567. {
  1568. m_pForwarderConnection->DereferenceForwarderConnection();
  1569. m_pForwarderConnection = NULL;
  1570. }
  1571. }
  1572. SERVER_PROCESS::~SERVER_PROCESS()
  1573. {
  1574. DWORD dwThreadStatus = 0;
  1575. CleanUp();
  1576. // no need to free m_pEnvironmentVarTable, as it references to
  1577. // the same hash table hold by configuration.
  1578. // the hashtable memory will be freed once onfiguration got recycled
  1579. if (m_pProcessManager != NULL)
  1580. {
  1581. m_pProcessManager->DereferenceProcessManager();
  1582. m_pProcessManager = NULL;
  1583. }
  1584. if (m_hStdErrWritePipe != NULL)
  1585. {
  1586. if (m_hStdErrWritePipe != INVALID_HANDLE_VALUE)
  1587. {
  1588. FlushFileBuffers(m_hStdErrWritePipe);
  1589. CloseHandle(m_hStdErrWritePipe);
  1590. }
  1591. m_hStdErrWritePipe = NULL;
  1592. }
  1593. // Forces ReadFile to cancel, causing the read loop to complete.
  1594. // Don't check return value as IO may or may not be completed already.
  1595. if (m_hReadThread != nullptr)
  1596. {
  1597. LOG_INFO(L"Canceling standard stream pipe reader.");
  1598. CancelSynchronousIo(m_hReadThread);
  1599. }
  1600. // GetExitCodeThread returns 0 on failure; thread status code is invalid.
  1601. if (m_hReadThread != nullptr &&
  1602. !LOG_LAST_ERROR_IF(!GetExitCodeThread(m_hReadThread, &dwThreadStatus)) &&
  1603. dwThreadStatus == STILL_ACTIVE)
  1604. {
  1605. // Wait for graceful shutdown, i.e., the exit of the background thread or timeout
  1606. if (WaitForSingleObject(m_hReadThread, PIPE_OUTPUT_THREAD_TIMEOUT) != WAIT_OBJECT_0)
  1607. {
  1608. // If the thread is still running, we need kill it first before exit to avoid AV
  1609. if (!LOG_LAST_ERROR_IF(GetExitCodeThread(m_hReadThread, &dwThreadStatus) == 0) &&
  1610. dwThreadStatus == STILL_ACTIVE)
  1611. {
  1612. LOG_WARN(L"Thread reading stdout/err hit timeout, forcibly closing thread.");
  1613. TerminateThread(m_hReadThread, STATUS_CONTROL_C_EXIT);
  1614. }
  1615. }
  1616. }
  1617. if (m_hReadThread != nullptr)
  1618. {
  1619. CloseHandle(m_hReadThread);
  1620. m_hReadThread = nullptr;
  1621. }
  1622. if (m_hStdoutHandle != NULL)
  1623. {
  1624. if (m_hStdoutHandle != INVALID_HANDLE_VALUE)
  1625. {
  1626. CloseHandle(m_hStdoutHandle);
  1627. }
  1628. m_hStdoutHandle = NULL;
  1629. }
  1630. if (m_fStdoutLogEnabled)
  1631. {
  1632. m_Timer.CancelTimer();
  1633. }
  1634. if (!m_fStdoutLogEnabled && !m_struFullLogFile.IsEmpty())
  1635. {
  1636. WIN32_FIND_DATA fileData;
  1637. HANDLE handle = FindFirstFile(m_struFullLogFile.QueryStr(), &fileData);
  1638. if (handle != INVALID_HANDLE_VALUE &&
  1639. fileData.nFileSizeHigh == 0 &&
  1640. fileData.nFileSizeLow == 0)
  1641. {
  1642. FindClose(handle);
  1643. // no need to check whether the deletion succeeds
  1644. // as nothing can be done
  1645. DeleteFile(m_struFullLogFile.QueryStr());
  1646. }
  1647. }
  1648. }
  1649. //static
  1650. VOID
  1651. CALLBACK
  1652. SERVER_PROCESS::ProcessHandleCallback(
  1653. _In_ PVOID pContext,
  1654. _In_ BOOL
  1655. )
  1656. {
  1657. SERVER_PROCESS *pServerProcess = (SERVER_PROCESS*) pContext;
  1658. pServerProcess->HandleProcessExit();
  1659. }
  1660. HRESULT
  1661. SERVER_PROCESS::RegisterProcessWait(
  1662. PHANDLE phWaitHandle,
  1663. HANDLE hProcessToWaitOn
  1664. )
  1665. {
  1666. HRESULT hr = S_OK;
  1667. NTSTATUS status = 0;
  1668. _ASSERT(phWaitHandle != NULL && *phWaitHandle == NULL);
  1669. *phWaitHandle = NULL;
  1670. // wait thread will dereference.
  1671. ReferenceServerProcess();
  1672. status = RegisterWaitForSingleObject(
  1673. phWaitHandle,
  1674. hProcessToWaitOn,
  1675. (WAITORTIMERCALLBACKFUNC)&ProcessHandleCallback,
  1676. this,
  1677. INFINITE,
  1678. WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD
  1679. );
  1680. if (status < 0)
  1681. {
  1682. hr = HRESULT_FROM_NT(status);
  1683. goto Finished;
  1684. }
  1685. Finished:
  1686. if (FAILED_LOG(hr))
  1687. {
  1688. *phWaitHandle = NULL;
  1689. DereferenceServerProcess();
  1690. }
  1691. return hr;
  1692. }
  1693. VOID
  1694. SERVER_PROCESS::HandleProcessExit( VOID )
  1695. {
  1696. BOOL fReady = FALSE;
  1697. DWORD dwProcessId = 0;
  1698. if (InterlockedCompareExchange(&m_lStopping, 1L, 0L) == 0L)
  1699. {
  1700. CheckIfServerIsUp(m_dwPort, &dwProcessId, &fReady);
  1701. if (!fReady)
  1702. {
  1703. EventLog::Info(
  1704. ASPNETCORE_EVENT_PROCESS_SHUTDOWN,
  1705. ASPNETCORE_EVENT_PROCESS_SHUTDOWN_MSG,
  1706. m_struAppFullPath.QueryStr(),
  1707. m_struPhysicalPath.QueryStr(),
  1708. m_dwProcessId,
  1709. m_dwPort);
  1710. m_pProcessManager->ShutdownProcess(this);
  1711. }
  1712. DereferenceServerProcess();
  1713. }
  1714. }
  1715. HRESULT
  1716. SERVER_PROCESS::SendShutdownHttpMessage( VOID )
  1717. {
  1718. HRESULT hr = S_OK;
  1719. HINTERNET hSession = NULL;
  1720. HINTERNET hConnect = NULL;
  1721. HINTERNET hRequest = NULL;
  1722. STACK_STRU(strHeaders, 256);
  1723. STRU strAppToken;
  1724. STRU strUrl;
  1725. DWORD dwStatusCode = 0;
  1726. DWORD dwSize = sizeof(dwStatusCode);
  1727. hSession = WinHttpOpen(L"",
  1728. WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
  1729. WINHTTP_NO_PROXY_NAME,
  1730. WINHTTP_NO_PROXY_BYPASS,
  1731. 0);
  1732. if (hSession == NULL)
  1733. {
  1734. hr = HRESULT_FROM_WIN32(GetLastError());
  1735. goto Finished;
  1736. }
  1737. hConnect = WinHttpConnect(hSession,
  1738. L"127.0.0.1",
  1739. (USHORT)m_dwPort,
  1740. 0);
  1741. if (hConnect == NULL)
  1742. {
  1743. hr = HRESULT_FROM_WIN32(GetLastError());
  1744. goto Finished;
  1745. }
  1746. if (m_struAppVirtualPath.QueryCCH() > 1)
  1747. {
  1748. // app path size is 1 means site root, i.e., "/"
  1749. // we don't want to add duplicated '/' to the request url
  1750. // otherwise the request will fail
  1751. strUrl.Copy(m_struAppVirtualPath);
  1752. }
  1753. strUrl.Append(L"/iisintegration");
  1754. hRequest = WinHttpOpenRequest(hConnect,
  1755. L"POST",
  1756. strUrl.QueryStr(),
  1757. NULL,
  1758. WINHTTP_NO_REFERER,
  1759. NULL,
  1760. 0);
  1761. if (hRequest == NULL)
  1762. {
  1763. hr = HRESULT_FROM_WIN32(GetLastError());
  1764. goto Finished;
  1765. }
  1766. // set timeout
  1767. if (!WinHttpSetTimeouts(hRequest,
  1768. m_dwShutdownTimeLimitInMS, // dwResolveTimeout
  1769. m_dwShutdownTimeLimitInMS, // dwConnectTimeout
  1770. m_dwShutdownTimeLimitInMS, // dwSendTimeout
  1771. m_dwShutdownTimeLimitInMS)) // dwReceiveTimeout
  1772. {
  1773. hr = HRESULT_FROM_WIN32(GetLastError());
  1774. goto Finished;
  1775. }
  1776. // set up the shutdown headers
  1777. if (FAILED_LOG(hr = strHeaders.Append(L"MS-ASPNETCORE-EVENT:shutdown \r\n")) ||
  1778. FAILED_LOG(hr = strAppToken.Append(L"MS-ASPNETCORE-TOKEN:")) ||
  1779. FAILED_LOG(hr = strAppToken.AppendA(m_straGuid.QueryStr())) ||
  1780. FAILED_LOG(hr = strHeaders.Append(strAppToken.QueryStr())))
  1781. {
  1782. goto Finished;
  1783. }
  1784. if (!WinHttpSendRequest(hRequest,
  1785. strHeaders.QueryStr(), // pwszHeaders
  1786. strHeaders.QueryCCH(), // dwHeadersLength
  1787. WINHTTP_NO_REQUEST_DATA,
  1788. 0, // dwOptionalLength
  1789. 0, // dwTotalLength
  1790. 0)) // dwContext
  1791. {
  1792. hr = HRESULT_FROM_WIN32(GetLastError());
  1793. goto Finished;
  1794. }
  1795. if (!WinHttpReceiveResponse(hRequest , NULL))
  1796. {
  1797. hr = HRESULT_FROM_WIN32(GetLastError());
  1798. goto Finished;
  1799. }
  1800. if (!WinHttpQueryHeaders(hRequest,
  1801. WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
  1802. WINHTTP_HEADER_NAME_BY_INDEX,
  1803. &dwStatusCode,
  1804. &dwSize,
  1805. WINHTTP_NO_HEADER_INDEX))
  1806. {
  1807. hr = HRESULT_FROM_WIN32(GetLastError());
  1808. goto Finished;
  1809. }
  1810. if (dwStatusCode != 202)
  1811. {
  1812. // not expected http status
  1813. hr = E_FAIL;
  1814. }
  1815. // log
  1816. EventLog::Info(
  1817. ASPNETCORE_EVENT_SENT_SHUTDOWN_HTTP_REQUEST,
  1818. ASPNETCORE_EVENT_SENT_SHUTDOWN_HTTP_REQUEST_MSG,
  1819. m_dwProcessId,
  1820. dwStatusCode);
  1821. Finished:
  1822. if (hRequest)
  1823. {
  1824. WinHttpCloseHandle(hRequest);
  1825. hRequest = NULL;
  1826. }
  1827. if (hConnect)
  1828. {
  1829. WinHttpCloseHandle(hConnect);
  1830. hConnect = NULL;
  1831. }
  1832. if (hSession)
  1833. {
  1834. WinHttpCloseHandle(hSession);
  1835. hSession = NULL;
  1836. }
  1837. return hr;
  1838. }
  1839. //static
  1840. VOID
  1841. SERVER_PROCESS::SendShutDownSignal(
  1842. LPVOID lpParam
  1843. )
  1844. {
  1845. SERVER_PROCESS* pThis = static_cast<SERVER_PROCESS *>(lpParam);
  1846. DBG_ASSERT(pThis);
  1847. pThis->SendShutDownSignalInternal();
  1848. }
  1849. //
  1850. // send shutdown message first, if fail then send
  1851. // ctrl-c to the backend process to let it gracefully shutdown
  1852. //
  1853. VOID
  1854. SERVER_PROCESS::SendShutDownSignalInternal(
  1855. VOID
  1856. )
  1857. {
  1858. ReferenceServerProcess();
  1859. if (FAILED_LOG(SendShutdownHttpMessage()))
  1860. {
  1861. //
  1862. // failed to send shutdown http message
  1863. // try send ctrl signal
  1864. //
  1865. HWND hCurrentConsole = NULL;
  1866. BOOL fFreeConsole = FALSE;
  1867. hCurrentConsole = GetConsoleWindow();
  1868. if (hCurrentConsole)
  1869. {
  1870. // free current console first, as we may have one, e.g., hostedwebcore case
  1871. fFreeConsole = FreeConsole();
  1872. }
  1873. if (AttachConsole(m_dwProcessId))
  1874. {
  1875. // As we called CreateProcess with CREATE_NEW_PROCESS_GROUP
  1876. // call ctrl-break instead of ctrl-c as child process ignores ctrl-c
  1877. if (!GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, m_dwProcessId))
  1878. {
  1879. // failed to send the ctrl signal. terminate the backend process immediately instead of waiting for timeout
  1880. TerminateBackendProcess();
  1881. }
  1882. FreeConsole();
  1883. if (fFreeConsole)
  1884. {
  1885. // IISExpress and hostedwebcore w3wp run as background process
  1886. // have to attach console back to ensure post app_offline scenario still works
  1887. AttachConsole(ATTACH_PARENT_PROCESS);
  1888. }
  1889. }
  1890. else
  1891. {
  1892. // terminate the backend process immediately instead of waiting for timeout
  1893. TerminateBackendProcess();
  1894. }
  1895. }
  1896. DereferenceServerProcess();
  1897. }
  1898. VOID
  1899. SERVER_PROCESS::TerminateBackendProcess(
  1900. VOID
  1901. )
  1902. {
  1903. if (InterlockedCompareExchange(&m_lStopping, 1L, 0L) == 0L)
  1904. {
  1905. // backend process will be terminated, remove the waitcallback
  1906. if (m_hProcessWaitHandle != NULL)
  1907. {
  1908. UnregisterWait(m_hProcessWaitHandle);
  1909. // as we skipped process exit callback (ProcessHandleCallback),
  1910. // need to dereference the object otherwise memory leak
  1911. DereferenceServerProcess();
  1912. m_hProcessWaitHandle = NULL;
  1913. }
  1914. // cannot gracefully shutdown or timeout, terminate the process
  1915. if (m_hProcessHandle != NULL && m_hProcessHandle != INVALID_HANDLE_VALUE)
  1916. {
  1917. TerminateProcess(m_hProcessHandle, 0);
  1918. m_hProcessHandle = NULL;
  1919. }
  1920. // log a warning for ungraceful shutdown
  1921. EventLog::Warn(
  1922. ASPNETCORE_EVENT_GRACEFUL_SHUTDOWN_FAILURE,
  1923. ASPNETCORE_EVENT_GRACEFUL_SHUTDOWN_FAILURE_MSG,
  1924. m_dwProcessId);
  1925. }
  1926. }