Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2906 lines
82 KiB

  1. /*++
  2. Copyright (c) 1999-2000 Microsoft Corporation
  3. Module Name:
  4. sessmgr.cpp
  5. Abstract:
  6. ATL wizard generated code.
  7. Author:
  8. HueiWang 2/17/2000
  9. --*/
  10. // Note: Proxy/Stub Information
  11. // To build a separate proxy/stub DLL,
  12. // run nmake -f sessmgrps.mk in the project directory.
  13. #include "stdafx.h"
  14. #include "resource.h"
  15. #include <initguid.h>
  16. #include <process.h>
  17. #include <tchar.h>
  18. #include "sessmgr.h"
  19. #include "sessmgr_i.c"
  20. #include <stdio.h>
  21. //#include <new.h>
  22. #include "global.h"
  23. #include "HelpSess.h"
  24. #include "HelpMgr.h"
  25. #include "helper.h"
  26. #include "helpacc.h"
  27. #include <rdshost.h>
  28. #include "policy.h"
  29. #include "remotedesktoputils.h"
  30. #include <SHlWapi.h>
  31. #define SETUPLOGFILE_NAME _TEXT("sessmgr.setup.log")
  32. #define SESSMGR_SERVICE 0
  33. #define SESSMGR_REGSERVER 1
  34. #define SESSMGR_UNREGSERVER 2
  35. BEGIN_OBJECT_MAP(ObjectMap)
  36. //OBJECT_ENTRY(CLSID_RemoteDesktopHelpSession, CRemoteDesktopHelpSession)
  37. OBJECT_ENTRY(CLSID_RemoteDesktopHelpSessionMgr, CRemoteDesktopHelpSessionMgr)
  38. END_OBJECT_MAP()
  39. CServiceModule _Module;
  40. HANDLE g_hTSCertificateChanged = NULL;
  41. HANDLE g_hWaitTSCertificateChanged = NULL;
  42. HKEY g_hTSCertificateRegKey = NULL;
  43. DWORD
  44. RestartFromSystemRestore();
  45. VOID CALLBACK
  46. TSCertChangeCallback(
  47. PVOID pContext,
  48. BOOLEAN bTimerOrWaitFired
  49. )
  50. /*++
  51. Callback for TS certificate registry change from threadpool function.
  52. --*/
  53. {
  54. MYASSERT( FALSE == bTimerOrWaitFired );
  55. // Our wait is forever so can't be timeout.
  56. if( FALSE == bTimerOrWaitFired )
  57. {
  58. PostThreadMessage(
  59. _Module.dwThreadID,
  60. WM_LOADTSPUBLICKEY,
  61. 0,
  62. 0
  63. );
  64. }
  65. else
  66. {
  67. DebugPrintf(
  68. _TEXT("TSCertChangeCallback does not expect timeout...\n") );
  69. MYASSERT(FALSE);
  70. }
  71. }
  72. DWORD
  73. LoadTermSrvSecurityBlob()
  74. /*++
  75. Function to load TS machine specific identification blob, for now
  76. we use TS public key.
  77. --*/
  78. {
  79. DWORD dwStatus;
  80. PBYTE pbTSPublicKey = NULL;
  81. DWORD cbTSPublicKey = 0;
  82. DWORD dwType;
  83. DWORD cbData;
  84. BOOL bSuccess;
  85. BOOL bUsesX509PublicKey = FALSE;
  86. if( NULL == g_hTSCertificateRegKey )
  87. {
  88. MYASSERT(FALSE);
  89. dwStatus = ERROR_INTERNAL_ERROR;
  90. goto CLEANUPANDEXIT;
  91. }
  92. //
  93. // Make sure TS certificate is there before
  94. // we directly load public key from LSA
  95. //
  96. dwStatus = RegQueryValueEx(
  97. g_hTSCertificateRegKey,
  98. REGVALUE_TSX509_CERT,
  99. NULL,
  100. &dwType,
  101. NULL,
  102. &cbData
  103. );
  104. if( ERROR_SUCCESS == dwStatus )
  105. {
  106. DebugPrintf(
  107. _TEXT("TermSrv X509 certificate found, trying to load TS X509 public key\n")
  108. );
  109. cbTSPublicKey = 0;
  110. //
  111. // Current TLSAPI does not support retrival of
  112. // X509 certificate public key and TS cert is in
  113. // special format not standard x509 cert chain.
  114. //
  115. dwStatus = LsCsp_RetrieveSecret(
  116. LSA_TSX509_CERT_PUBLIC_KEY_NAME,
  117. NULL,
  118. &cbTSPublicKey
  119. );
  120. if( LICENSE_STATUS_OK != dwStatus &&
  121. LICENSE_STATUS_INSUFFICIENT_BUFFER != dwStatus )
  122. {
  123. MYASSERT( FALSE );
  124. goto CLEANUPANDEXIT;
  125. }
  126. pbTSPublicKey = (PBYTE)LocalAlloc( LPTR, cbTSPublicKey );
  127. if( NULL == pbTSPublicKey )
  128. {
  129. dwStatus = GetLastError();
  130. goto CLEANUPANDEXIT;
  131. }
  132. dwStatus = LsCsp_RetrieveSecret(
  133. LSA_TSX509_CERT_PUBLIC_KEY_NAME,
  134. pbTSPublicKey,
  135. &cbTSPublicKey
  136. );
  137. //
  138. // Critical error, We have certificate in registry
  139. // but don't have public key in LSA
  140. //
  141. MYASSERT( LICENSE_STATUS_OK == dwStatus );
  142. if( LICENSE_STATUS_OK != dwStatus )
  143. {
  144. DebugPrintf(
  145. _TEXT("TermSrv X509 certificate found but can't load X509 public key\n")
  146. );
  147. goto CLEANUPANDEXIT;
  148. }
  149. bUsesX509PublicKey = TRUE;
  150. }
  151. else
  152. {
  153. DebugPrintf(
  154. _TEXT("TermSrv X509 certificate not found\n")
  155. );
  156. //
  157. // Load pre-define TS public key
  158. //
  159. dwStatus = LsCsp_GetServerData(
  160. LsCspInfo_PublicKey,
  161. pbTSPublicKey,
  162. &cbTSPublicKey
  163. );
  164. // expecting insufficient buffer
  165. if( LICENSE_STATUS_INSUFFICIENT_BUFFER != dwStatus &&
  166. LICENSE_STATUS_OK != dwStatus )
  167. {
  168. // invalid return code.
  169. MYASSERT(FALSE);
  170. goto CLEANUPANDEXIT;
  171. }
  172. MYASSERT( cbTSPublicKey > 0 );
  173. pbTSPublicKey = (PBYTE)LocalAlloc( LPTR, cbTSPublicKey );
  174. if( NULL == pbTSPublicKey )
  175. {
  176. dwStatus = GetLastError();
  177. goto CLEANUPANDEXIT;
  178. }
  179. dwStatus = LsCsp_GetServerData(
  180. LsCspInfo_PublicKey,
  181. pbTSPublicKey,
  182. &cbTSPublicKey
  183. );
  184. if( LICENSE_STATUS_OK != dwStatus )
  185. {
  186. MYASSERT(FALSE);
  187. goto CLEANUPANDEXIT;
  188. }
  189. }
  190. if( ERROR_SUCCESS == dwStatus )
  191. {
  192. //
  193. // Lock access to g_TSSecurityBlob, this is global and
  194. // other thread might be calling get_ConnectParm which access
  195. // g_TSSecurityBlob.
  196. //
  197. CCriticalSectionLocker l(g_GlobalLock);
  198. dwStatus = HashSecurityData(
  199. pbTSPublicKey,
  200. cbTSPublicKey,
  201. g_TSSecurityBlob
  202. );
  203. MYASSERT( ERROR_SUCCESS == dwStatus );
  204. MYASSERT( g_TSSecurityBlob.Length() > 0 );
  205. DebugPrintf(
  206. _TEXT("HashSecurityData() returns %d\n"), dwStatus
  207. );
  208. if( ERROR_SUCCESS != dwStatus )
  209. {
  210. goto CLEANUPANDEXIT;
  211. }
  212. }
  213. //
  214. // SRV, ADS, ... SKU uses seperate thread
  215. // to register with license server, so we use
  216. // different thread to receive certificate change notification.
  217. // Since TermSrv cached certificate, no reason to queue
  218. // notification once we successfully loaded tersrmv public key
  219. //
  220. if( !IsPersonalOrProMachine() && FALSE == bUsesX509PublicKey )
  221. {
  222. DebugPrintf(
  223. _TEXT("Setting up registry notification...\n")
  224. );
  225. MYASSERT( NULL != g_hTSCertificateChanged );
  226. ResetEvent(g_hTSCertificateChanged);
  227. // register a registry change notification
  228. // RegNotifyChangeKeyValue() only signal once.
  229. dwStatus = RegNotifyChangeKeyValue(
  230. g_hTSCertificateRegKey,
  231. TRUE,
  232. REG_NOTIFY_CHANGE_LAST_SET,
  233. g_hTSCertificateChanged,
  234. TRUE
  235. );
  236. if( ERROR_SUCCESS != dwStatus )
  237. {
  238. MYASSERT(FALSE);
  239. DebugPrintf(
  240. _TEXT("RegNotifyChangeKeyValue() returns %d\n"), dwStatus
  241. );
  242. goto CLEANUPANDEXIT;
  243. }
  244. if( NULL != g_hWaitTSCertificateChanged )
  245. {
  246. if( FALSE == UnregisterWait( g_hWaitTSCertificateChanged ) )
  247. {
  248. dwStatus = GetLastError();
  249. DebugPrintf(
  250. _TEXT("UnregisterWait() returns %d\n"),
  251. dwStatus
  252. );
  253. MYASSERT(FALSE);
  254. }
  255. g_hWaitTSCertificateChanged = NULL;
  256. }
  257. //
  258. // Queue notification to threadpool, we need to use WT_EXECUTEONLYONCE
  259. // since we are registering manual reset event.
  260. //
  261. bSuccess = RegisterWaitForSingleObject(
  262. &g_hWaitTSCertificateChanged,
  263. g_hTSCertificateChanged,
  264. (WAITORTIMERCALLBACK) TSCertChangeCallback,
  265. NULL,
  266. INFINITE,
  267. WT_EXECUTEDEFAULT | WT_EXECUTEONLYONCE
  268. );
  269. if( FALSE == bSuccess )
  270. {
  271. dwStatus = GetLastError();
  272. DebugPrintf(
  273. _TEXT("RegisterWaitForSingleObject() returns %d\n"), dwStatus
  274. );
  275. }
  276. }
  277. CLEANUPANDEXIT:
  278. if( ERROR_SUCCESS != dwStatus )
  279. {
  280. //
  281. // Lock access to g_TSSecurityBlob, this is global and
  282. // other thread might be calling get_ConnectParm which access
  283. // g_TSSecurityBlob.
  284. //
  285. CCriticalSectionLocker l(g_GlobalLock);
  286. //
  287. // TS either update its public key or key has change
  288. // and we failed to reload it, there is no reason to
  289. // to continue create help ticket since public key already
  290. /// mismatached, set service status and log error event
  291. //
  292. g_TSSecurityBlob.Empty();
  293. }
  294. if( NULL != pbTSPublicKey )
  295. {
  296. LocalFree(pbTSPublicKey);
  297. }
  298. return HRESULT_FROM_WIN32( dwStatus );
  299. }
  300. DWORD
  301. LoadAndSetupTSCertChangeNotification()
  302. {
  303. DWORD dwStatus;
  304. DWORD dwDisp;
  305. BOOL bSuccess;
  306. //
  307. // Only setup registry change notification if we
  308. // runs on higher SKU
  309. //
  310. g_hTSCertificateChanged = CreateEvent( NULL, TRUE, FALSE, NULL );
  311. if( NULL == g_hTSCertificateChanged )
  312. {
  313. dwStatus = GetLastError();
  314. goto CLEANUPANDEXIT;
  315. }
  316. //
  317. // Open parameters key under TermServices if key isn't
  318. // there, create it, this does not interfere with TermSrv
  319. // since we only create the reg. key not updating values
  320. // under it.
  321. //
  322. dwStatus = RegCreateKeyEx(
  323. HKEY_LOCAL_MACHINE,
  324. REGKEY_TSX509_CERT ,
  325. 0,
  326. NULL,
  327. REG_OPTION_NON_VOLATILE,
  328. KEY_WRITE | KEY_READ,
  329. NULL,
  330. &g_hTSCertificateRegKey,
  331. &dwDisp
  332. );
  333. if( ERROR_SUCCESS != dwStatus )
  334. {
  335. MYASSERT(FALSE);
  336. DebugPrintf(
  337. _TEXT("RegCreateKeyEx on %s failed with 0x%08x\n"),
  338. REGKEY_TSX509_CERT,
  339. dwStatus
  340. );
  341. goto CLEANUPANDEXIT;
  342. }
  343. //
  344. // Load security blob from TS, currently, we use TS public key
  345. // as security blob
  346. //
  347. dwStatus = LoadTermSrvSecurityBlob();
  348. if( ERROR_SUCCESS != dwStatus )
  349. {
  350. MYASSERT(FALSE);
  351. }
  352. CLEANUPANDEXIT:
  353. return dwStatus;
  354. }
  355. LPCTSTR FindOneOf(LPCTSTR p1, LPCTSTR p2)
  356. {
  357. while (p1 != NULL && *p1 != NULL)
  358. {
  359. LPCTSTR p = p2;
  360. while (p != NULL && *p != NULL)
  361. {
  362. if (*p1 == *p)
  363. return CharNext(p1);
  364. p = CharNext(p);
  365. }
  366. p1 = CharNext(p1);
  367. }
  368. return NULL;
  369. }
  370. void
  371. LogSetup(
  372. IN FILE* pfd,
  373. IN LPCTSTR format, ...
  374. )
  375. /*++
  376. Routine Description:
  377. sprintf() like wrapper around OutputDebugString().
  378. Parameters:
  379. hConsole : Handle to console.
  380. format : format string.
  381. Returns:
  382. None.
  383. Note:
  384. To be replace by generic tracing code.
  385. ++*/
  386. {
  387. TCHAR buf[8096]; // max. error text
  388. DWORD dump;
  389. va_list marker;
  390. va_start(marker, format);
  391. try {
  392. _vsntprintf(
  393. buf,
  394. sizeof(buf)/sizeof(buf[0])-1,
  395. format,
  396. marker
  397. );
  398. if( NULL == pfd )
  399. {
  400. OutputDebugString(buf);
  401. }
  402. else
  403. {
  404. _fputts( buf, pfd );
  405. fflush( pfd );
  406. }
  407. }
  408. catch(...) {
  409. }
  410. va_end(marker);
  411. return;
  412. }
  413. #if DISABLESECURITYCHECKS
  414. DWORD WINAPI
  415. NotifySessionLogoff(
  416. LPARAM pParm
  417. )
  418. /*++
  419. Routine Description:
  420. Routine to notified all currently loaded help that a user has
  421. logoff/disconnect from session, routine is kick off via thread pools'
  422. QueueUserWorkItem().
  423. Parameters:
  424. pContext : logoff or disconnected Session ID
  425. Returns:
  426. None.
  427. Note :
  428. We treat disconnect same as logoff since user might be actually
  429. active on the other session logged in with same credential, so
  430. we rely on resolver.
  431. --*/
  432. {
  433. DebugPrintf(_TEXT("NotifySessionLogoff() started...\n"));
  434. //
  435. // Tell service don't shutdown, we are in process.
  436. //
  437. _Module.AddRef();
  438. CRemoteDesktopHelpSessionMgr::NotifyHelpSesionLogoff( pParm );
  439. _Module.Release();
  440. return ERROR_SUCCESS;
  441. }
  442. #endif
  443. /////////////////////////////////////////////////////////////////////////////
  444. void
  445. DeleteAccountFromFilterList(
  446. LPCTSTR lpszAccountName
  447. )
  448. /*++
  449. Routine Description:
  450. Delete HelpAssistant account from account filter list, this is temporary
  451. until we have long term solution.
  452. Parameters:
  453. lpszAccountName : Name of HelpAssistant account.
  454. Returns:
  455. None.
  456. Note:
  457. Account filter list is on
  458. HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList
  459. <name of SALEM account> REG_DWORD 0x00000000
  460. --*/
  461. {
  462. HKEY hKey = NULL;
  463. DWORD dwStatus;
  464. DWORD dwValue = 0;
  465. dwStatus = RegCreateKeyEx(
  466. HKEY_LOCAL_MACHINE,
  467. _TEXT("Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList"),
  468. 0,
  469. NULL,
  470. REG_OPTION_NON_VOLATILE,
  471. KEY_ALL_ACCESS,
  472. NULL,
  473. &hKey,
  474. NULL
  475. );
  476. if( ERROR_SUCCESS == dwStatus )
  477. {
  478. dwStatus = RegDeleteValue(
  479. hKey,
  480. lpszAccountName
  481. );
  482. }
  483. if( NULL != hKey )
  484. {
  485. RegCloseKey( hKey );
  486. }
  487. return;
  488. }
  489. void
  490. AddAccountToFilterList(
  491. LPCTSTR lpszAccountName
  492. )
  493. /*++
  494. Routine Description:
  495. Add HelpAssistant account into account filter list, this is temporary
  496. until we have long term solution.
  497. Parameters:
  498. lpszAccountName : Name of HelpAssistant account.
  499. Returns:
  500. None.
  501. Note:
  502. Account filter list is on
  503. HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList
  504. <name of SALEM account> REG_DWORD 0x00000000
  505. --*/
  506. {
  507. HKEY hKey = NULL;
  508. DWORD dwStatus;
  509. DWORD dwValue = 0;
  510. dwStatus = RegCreateKeyEx(
  511. HKEY_LOCAL_MACHINE,
  512. _TEXT("Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList"),
  513. 0,
  514. NULL,
  515. REG_OPTION_NON_VOLATILE,
  516. KEY_ALL_ACCESS,
  517. NULL,
  518. &hKey,
  519. NULL
  520. );
  521. if( ERROR_SUCCESS == dwStatus )
  522. {
  523. dwStatus = RegSetValueEx(
  524. hKey,
  525. lpszAccountName,
  526. 0,
  527. REG_DWORD,
  528. (LPBYTE) &dwValue,
  529. sizeof(DWORD)
  530. );
  531. }
  532. //MYASSERT( ERROR_SUCCESS == dwStatus );
  533. if( NULL != hKey )
  534. {
  535. RegCloseKey( hKey );
  536. }
  537. return;
  538. }
  539. void
  540. CServiceModule::LogSessmgrEventLog(
  541. DWORD dwEventType,
  542. DWORD dwEventCode,
  543. CComBSTR& bstrNoviceDomain,
  544. CComBSTR& bstrNoviceAccount,
  545. CComBSTR& bstrRaType,
  546. CComBSTR& bstrExpertIPFromClient,
  547. CComBSTR& bstrExpertIPFromTS,
  548. DWORD dwErrCode
  549. )
  550. /*++
  551. Description:
  552. Log a Salem specific event log, this includes all event log in sessmgr.
  553. Parameters:
  554. dwEventCode : Event code.
  555. bstrNoviceDomain : Ticket owner's domain name.
  556. bstrNoviceAccount : Ticket owner's user account name.
  557. bstrExpertIPFromClient : Expert's IP address send from mstacax.
  558. bstrExpertIPFromTS : Expert IP address we query from TermSrv.
  559. dwErrCode : Error code.
  560. Returns:
  561. None.
  562. Note:
  563. Max. sessmgr specific log require at most 5 parameters but must
  564. contain novice domain, account name and also expert IP address
  565. send to mstscax and expert IP address we query from TermSrv.
  566. --*/
  567. {
  568. TCHAR szErrCode[256];
  569. LPTSTR eventString[6];
  570. _stprintf( szErrCode, L"0x%x", dwErrCode );
  571. eventString[0] = (LPTSTR)bstrNoviceDomain;
  572. eventString[1] = (LPTSTR)bstrNoviceAccount;
  573. eventString[2] = (LPTSTR)bstrRaType;
  574. eventString[3] = (LPTSTR)bstrExpertIPFromClient;
  575. eventString[4] = (LPTSTR)bstrExpertIPFromTS;
  576. eventString[5] = szErrCode;
  577. LogRemoteAssistanceEventString(
  578. dwEventType,
  579. dwEventCode,
  580. sizeof(eventString)/sizeof(eventString[0]),
  581. eventString
  582. );
  583. return;
  584. }
  585. /////////////////////////////////////////////////////////////////////////////
  586. void
  587. CServiceModule::LogEventWithStatusCode(
  588. IN DWORD dwEventType,
  589. IN DWORD dwEventId,
  590. IN DWORD dwErrorCode
  591. )
  592. /*++
  593. --*/
  594. {
  595. TCHAR szErrCode[256];
  596. LPTSTR eventString[1];
  597. eventString[0] = szErrCode;
  598. _stprintf( szErrCode, L"0x%x", dwErrorCode );
  599. LogRemoteAssistanceEventString(
  600. dwEventType,
  601. dwEventId,
  602. 1,
  603. eventString
  604. );
  605. return;
  606. }
  607. inline HRESULT
  608. CServiceModule::RemoveEventViewerSource(
  609. IN FILE* pSetupLog
  610. )
  611. /*++
  612. --*/
  613. {
  614. TCHAR szBuffer[MAX_PATH + 2];
  615. DWORD dwStatus;
  616. _stprintf(
  617. szBuffer,
  618. _TEXT("%s\\%s"),
  619. REGKEY_SYSTEM_EVENTSOURCE,
  620. m_szServiceDispName
  621. );
  622. dwStatus = SHDeleteKey( HKEY_LOCAL_MACHINE, szBuffer );
  623. LogSetup(
  624. pSetupLog,
  625. L"Exiting RemoveEventViewerSource() with status code %d...\n",
  626. dwStatus
  627. );
  628. return HRESULT_FROM_WIN32(dwStatus);
  629. }
  630. // Although some of these functions are big they are declared inline since they are only used once
  631. inline HRESULT
  632. CServiceModule::RegisterServer(FILE* pSetupLog, BOOL bRegTypeLib, BOOL bService)
  633. {
  634. CRegKey key;
  635. HRESULT hr;
  636. CRegKey keyAppID;
  637. LONG lRes;
  638. LogSetup(
  639. pSetupLog,
  640. L"\nEntering CServiceModule::RegisterServer %d, %d\n",
  641. bRegTypeLib,
  642. bService
  643. );
  644. hr = CoInitialize(NULL);
  645. if (FAILED(hr))
  646. {
  647. LogSetup( pSetupLog, L"CoInitialize() failed with 0x%08x\n", hr );
  648. goto CLEANUPANDEXIT;
  649. }
  650. // Remove any previous service since it may point to
  651. // the incorrect file
  652. //Uninstall();
  653. // Add service entries
  654. UpdateRegistryFromResource(IDR_Sessmgr, TRUE);
  655. // Adjust the AppID for Local Server or Service
  656. lRes = keyAppID.Open(HKEY_CLASSES_ROOT, _T("AppID"), KEY_WRITE);
  657. if (lRes != ERROR_SUCCESS)
  658. {
  659. LogSetup( pSetupLog, L"Open key AppID failed with %d\n", lRes );
  660. hr = HRESULT_FROM_WIN32(lRes);
  661. goto CLEANUPANDEXIT;
  662. }
  663. lRes = key.Open(keyAppID, _T("{038ABBA4-4138-4AC4-A492-4A3DF068BD8A}"), KEY_WRITE);
  664. if (lRes != ERROR_SUCCESS)
  665. {
  666. LogSetup( pSetupLog, L"Open key 038ABBA4-4138-4AC4-A492-4A3DF068BD8A failed with %d\n", lRes );
  667. hr = HRESULT_FROM_WIN32(lRes);
  668. goto CLEANUPANDEXIT;
  669. }
  670. key.DeleteValue(_T("LocalService"));
  671. if (bService)
  672. {
  673. LogSetup( pSetupLog, L"Installing service...\n" );
  674. BOOL bInstallSuccess;
  675. key.SetValue(m_szServiceName, _T("LocalService"));
  676. key.SetValue(_T("-Service"), _T("ServiceParameters"));
  677. if( IsInstalled(pSetupLog) )
  678. {
  679. // update service description.
  680. bInstallSuccess = UpdateService( pSetupLog );
  681. }
  682. else
  683. {
  684. //
  685. // Create service
  686. //
  687. bInstallSuccess = Install(pSetupLog);
  688. }
  689. if( FALSE == bInstallSuccess )
  690. {
  691. LogSetup( pSetupLog, L"Install or update service description failed %d\n", GetLastError() );
  692. MYASSERT( FALSE );
  693. hr = HRESULT_FROM_WIN32(ERROR_INTERNAL_ERROR);
  694. }
  695. else
  696. {
  697. LogSetup( pSetupLog, L"successfully installing service...\n" );
  698. if( IsInstalled(pSetupLog) == FALSE )
  699. {
  700. LogSetup( pSetupLog, L"IsInstalled() return FALSE after Install()\n" );
  701. MYASSERT(FALSE);
  702. hr = HRESULT_FROM_WIN32(ERROR_INTERNAL_ERROR);
  703. }
  704. //
  705. // Event is not log via racpldlg.dll, remove previous event source.
  706. //
  707. RemoveEventViewerSource(pSetupLog);
  708. }
  709. }
  710. if( SUCCEEDED(hr) )
  711. {
  712. // Add object entries
  713. hr = CComModule::RegisterServer(bRegTypeLib);
  714. if( FAILED(hr) )
  715. {
  716. LogSetup( pSetupLog, L"CComModule::RegisterServer() on type library failed with 0x%08x\n", hr );
  717. }
  718. }
  719. CoUninitialize();
  720. CLEANUPANDEXIT:
  721. LogSetup( pSetupLog, L"Leaving CServiceModule::RegisterServer 0x%08x\n", hr );
  722. return hr;
  723. }
  724. inline HRESULT CServiceModule::UnregisterServer(FILE* pSetupLog)
  725. {
  726. LogSetup( pSetupLog, L"\nEntering CServiceModule::UnregisterServer\n" );
  727. HRESULT hr = CoInitialize(NULL);
  728. if (FAILED(hr))
  729. {
  730. LogSetup( pSetupLog, L"CoInitialize() failed with 0x%08x\n", hr );
  731. goto CLEANUPANDEXIT;
  732. }
  733. // Remove service entries
  734. UpdateRegistryFromResource(IDR_Sessmgr, FALSE);
  735. // Remove service
  736. Uninstall(pSetupLog);
  737. // Remove object entries
  738. CComModule::UnregisterServer(TRUE);
  739. CoUninitialize();
  740. CLEANUPANDEXIT:
  741. LogSetup( pSetupLog, L"Leaving CServiceModule::UnregisterServer() - 0x%08x\n", hr );
  742. return S_OK;
  743. }
  744. inline void
  745. CServiceModule::Init(
  746. _ATL_OBJMAP_ENTRY* p,
  747. HINSTANCE h,
  748. UINT nServiceNameID,
  749. UINT nServiceDispNameID,
  750. UINT nServiceDescID,
  751. const GUID* plibid
  752. )
  753. /*++
  754. ATL Wizard generated code
  755. --*/
  756. {
  757. CComModule::Init(p, h, plibid);
  758. m_bService = TRUE;
  759. m_dwServiceStartupStatus = ERROR_SUCCESS;
  760. LoadString(h, nServiceNameID, m_szServiceName, sizeof(m_szServiceName) / sizeof(TCHAR));
  761. LoadString(h, nServiceDescID, m_szServiceDesc, sizeof(m_szServiceDesc) / sizeof(TCHAR));
  762. LoadString(h, nServiceDispNameID, m_szServiceDispName, sizeof(m_szServiceDispName)/sizeof(TCHAR));
  763. // set up the initial service status
  764. m_hServiceStatus = NULL;
  765. m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
  766. m_status.dwCurrentState = SERVICE_STOPPED;
  767. m_status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SESSIONCHANGE;
  768. m_status.dwWin32ExitCode = 0;
  769. m_status.dwServiceSpecificExitCode = 0;
  770. m_status.dwCheckPoint = 0;
  771. m_status.dwWaitHint = 0;
  772. }
  773. LONG CServiceModule::Unlock()
  774. {
  775. LONG l = CComModule::Unlock();
  776. if (l == 0 && !m_bService)
  777. PostThreadMessage(dwThreadID, WM_QUIT, 0, 0);
  778. return l;
  779. }
  780. BOOL CServiceModule::IsInstalled(FILE* pSetupLog)
  781. {
  782. LogSetup( pSetupLog, L"\nEntering CServiceModule::IsInstalled()\n" );
  783. BOOL bResult = FALSE;
  784. SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
  785. if (hSCM != NULL)
  786. {
  787. SC_HANDLE hService = ::OpenService(hSCM, m_szServiceName, SERVICE_QUERY_CONFIG);
  788. if (hService != NULL)
  789. {
  790. LogSetup( pSetupLog, L"OpenService() Succeeded\n" );
  791. bResult = TRUE;
  792. ::CloseServiceHandle(hService);
  793. }
  794. else
  795. {
  796. LogSetup( pSetupLog, L"OpenService() failed with %d\n", GetLastError() );
  797. }
  798. ::CloseServiceHandle(hSCM);
  799. }
  800. else
  801. {
  802. LogSetup( pSetupLog, L"OpenSCManager() failed with %d\n", GetLastError() );
  803. }
  804. LogSetup( pSetupLog, L"Leaving IsInstalled() - %d\n", bResult );
  805. return bResult;
  806. }
  807. inline BOOL CServiceModule::UpdateService(FILE* pSetupLog)
  808. {
  809. DWORD dwStatus = ERROR_SUCCESS;
  810. SERVICE_DESCRIPTION serviceDesc;
  811. SC_HANDLE hSCM = NULL;
  812. SC_HANDLE hService = NULL;
  813. LogSetup( pSetupLog, L"\nEntering CServiceModule::UpdateServiceDescription()...\n" );
  814. hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
  815. if (hSCM == NULL)
  816. {
  817. dwStatus = GetLastError();
  818. LogSetup( pSetupLog, L"OpenSCManager() failed with %d\n", dwStatus );
  819. goto CLEANUPANDEXIT;
  820. }
  821. hService = ::OpenService( hSCM, m_szServiceName, SERVICE_CHANGE_CONFIG );
  822. if (hService == NULL)
  823. {
  824. dwStatus = GetLastError();
  825. LogSetup( pSetupLog, L"OpenService() failed with %d\n", dwStatus );
  826. goto CLEANUPANDEXIT;
  827. }
  828. serviceDesc.lpDescription = (LPTSTR)m_szServiceDesc;
  829. if( FALSE == ChangeServiceConfig2( hService, SERVICE_CONFIG_DESCRIPTION, (LPVOID)&serviceDesc ) )
  830. {
  831. dwStatus = GetLastError();
  832. LogSetup( pSetupLog, L"ChangeServiceConfig2() failed with %d\n", dwStatus );
  833. MYASSERT( ERROR_SUCCESS == dwStatus );
  834. }
  835. //
  836. // Performance : Set service to be demand start for upgrade
  837. //
  838. if( FALSE == ChangeServiceConfig(
  839. hService,
  840. SERVICE_NO_CHANGE,
  841. SERVICE_DEMAND_START,
  842. SERVICE_NO_CHANGE,
  843. NULL,
  844. NULL,
  845. NULL,
  846. NULL,
  847. NULL,
  848. NULL,
  849. m_szServiceDispName
  850. ) )
  851. {
  852. dwStatus = GetLastError();
  853. LogSetup( pSetupLog, L"ChangeServiceConfig() failed with %d\n", dwStatus );
  854. MYASSERT( ERROR_SUCCESS == dwStatus );
  855. }
  856. CLEANUPANDEXIT:
  857. if( NULL != hService )
  858. {
  859. ::CloseServiceHandle(hService);
  860. }
  861. if( NULL != hSCM )
  862. {
  863. ::CloseServiceHandle(hSCM);
  864. }
  865. LogSetup( pSetupLog, L"Leaving UpdateServiceDescription::Install() - %d\n", dwStatus );
  866. return dwStatus == ERROR_SUCCESS;
  867. }
  868. inline BOOL CServiceModule::Install(FILE* pSetupLog)
  869. {
  870. DWORD dwStatus = ERROR_SUCCESS;
  871. SERVICE_DESCRIPTION serviceDesc;
  872. SC_HANDLE hSCM;
  873. TCHAR szFilePath[_MAX_PATH];
  874. SC_HANDLE hService;
  875. LogSetup( pSetupLog, L"\nEntering CServiceModule::Install()...\n" );
  876. if (IsInstalled(pSetupLog))
  877. {
  878. LogSetup( pSetupLog, L"Service already installed\n" );
  879. dwStatus = ERROR_SUCCESS;
  880. goto CLEANUPANDEXIT;
  881. }
  882. hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
  883. if (hSCM == NULL)
  884. {
  885. dwStatus = GetLastError();
  886. LogSetup( pSetupLog, L"OpenSCManager() failed with %d\n", dwStatus );
  887. goto CLEANUPANDEXIT;
  888. }
  889. // Get the executable file path
  890. ::GetModuleFileName(NULL, szFilePath, _MAX_PATH);
  891. hService = ::CreateService(
  892. hSCM,
  893. m_szServiceName,
  894. m_szServiceDispName,
  895. SERVICE_ALL_ACCESS,
  896. SERVICE_WIN32_OWN_PROCESS,
  897. SERVICE_DEMAND_START,
  898. SERVICE_ERROR_NORMAL,
  899. szFilePath,
  900. NULL,
  901. NULL,
  902. _T("RPCSS\0"),
  903. NULL,
  904. NULL
  905. );
  906. if (hService == NULL)
  907. {
  908. dwStatus = GetLastError();
  909. LogSetup( pSetupLog, L"CreateService() failed with %d\n", dwStatus );
  910. ::CloseServiceHandle(hSCM);
  911. goto CLEANUPANDEXIT;
  912. }
  913. serviceDesc.lpDescription = (LPTSTR)m_szServiceDesc;
  914. if( FALSE == ChangeServiceConfig2( hService, SERVICE_CONFIG_DESCRIPTION, (LPVOID)&serviceDesc ) )
  915. {
  916. dwStatus = GetLastError();
  917. LogSetup( pSetupLog, L"ChangeServiceConfig2() failed with %d\n", dwStatus );
  918. MYASSERT( ERROR_SUCCESS == dwStatus );
  919. }
  920. ::CloseServiceHandle(hService);
  921. ::CloseServiceHandle(hSCM);
  922. CLEANUPANDEXIT:
  923. LogSetup( pSetupLog, L"Leaving CServiceModule::Install() - %d\n", dwStatus );
  924. return dwStatus == ERROR_SUCCESS;
  925. }
  926. inline BOOL CServiceModule::Uninstall(FILE* pSetupLog)
  927. {
  928. BOOL bStatus = TRUE;
  929. SC_HANDLE hService;
  930. SC_HANDLE hSCM;
  931. SERVICE_STATUS status;
  932. LogSetup( pSetupLog, L"\nEntering CServiceModule::Uninstall()...\n" );
  933. if (!IsInstalled(pSetupLog))
  934. {
  935. LogSetup( pSetupLog, L"Service is not installed...\n" );
  936. goto CLEANUPANDEXIT;
  937. }
  938. hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
  939. if (hSCM == NULL)
  940. {
  941. LogSetup( pSetupLog, L"OpenSCManager() failed with %d\n", GetLastError() );
  942. bStatus = FALSE;
  943. goto CLEANUPANDEXIT;
  944. }
  945. hService = ::OpenService(hSCM, m_szServiceName, SERVICE_STOP | DELETE);
  946. if (hService == NULL)
  947. {
  948. ::CloseServiceHandle(hSCM);
  949. LogSetup( pSetupLog, L"OpenService() failed with %d\n", GetLastError() );
  950. bStatus = FALSE;
  951. goto CLEANUPANDEXIT;
  952. }
  953. ::ControlService(hService, SERVICE_CONTROL_STOP, &status);
  954. bStatus = ::DeleteService(hService);
  955. if( FALSE == bStatus )
  956. {
  957. LogSetup( pSetupLog, L"DeleteService() failed with %d\n", GetLastError() );
  958. }
  959. ::CloseServiceHandle(hService);
  960. ::CloseServiceHandle(hSCM);
  961. CLEANUPANDEXIT:
  962. LogSetup( pSetupLog, L"Leaving CServiceModule::Uninstall()\n" );
  963. return bStatus;
  964. }
  965. //////////////////////////////////////////////////////////////////////////////////////////////
  966. // Service startup and registration
  967. inline void CServiceModule::Start()
  968. {
  969. SERVICE_TABLE_ENTRY st[] =
  970. {
  971. { m_szServiceName, _ServiceMain },
  972. { NULL, NULL }
  973. };
  974. if (m_bService && !::StartServiceCtrlDispatcher(st))
  975. {
  976. m_bService = FALSE;
  977. }
  978. if (m_bService == FALSE)
  979. Run();
  980. }
  981. inline void CServiceModule::ServiceMain(DWORD /* dwArgc */, LPTSTR* /* lpszArgv */)
  982. {
  983. // Register the control request handler
  984. m_status.dwCurrentState = SERVICE_START_PENDING;
  985. m_hServiceStatus = RegisterServiceCtrlHandlerEx(m_szServiceName, HandlerEx, this);
  986. if (m_hServiceStatus == NULL)
  987. {
  988. //LogEvent(_T("Handler not installed"));
  989. return;
  990. }
  991. m_status.dwWin32ExitCode = S_OK;
  992. m_status.dwCheckPoint = 0;
  993. m_status.dwWaitHint = SERVICE_STARTUP_WAITHINT;
  994. SetServiceStatus(SERVICE_START_PENDING);
  995. // When the Run function returns, the service has stopped.
  996. Run();
  997. SetServiceStatus(SERVICE_STOPPED);
  998. }
  999. inline void CServiceModule::Handler(DWORD dwOpcode)
  1000. {
  1001. switch (dwOpcode)
  1002. {
  1003. case SERVICE_CONTROL_STOP:
  1004. SetServiceStatus(SERVICE_STOP_PENDING);
  1005. if( PostThreadMessage(dwThreadID, WM_QUIT, 0, 0) == FALSE )
  1006. {
  1007. DWORD dwStatus = GetLastError();
  1008. }
  1009. break;
  1010. case SERVICE_CONTROL_PAUSE:
  1011. break;
  1012. case SERVICE_CONTROL_CONTINUE:
  1013. break;
  1014. case SERVICE_CONTROL_INTERROGATE:
  1015. break;
  1016. case SERVICE_CONTROL_SHUTDOWN:
  1017. break;
  1018. //default:
  1019. // LogEvent(_T("Bad service request"));
  1020. }
  1021. }
  1022. inline DWORD WINAPI
  1023. CServiceModule::HandlerEx(
  1024. DWORD dwControl,
  1025. DWORD dwEventType,
  1026. LPVOID lpEventData,
  1027. LPVOID lpContext
  1028. )
  1029. /*++
  1030. --*/
  1031. {
  1032. DWORD dwRetCode;
  1033. switch (dwControl)
  1034. {
  1035. case SERVICE_CONTROL_STOP:
  1036. case SERVICE_CONTROL_PAUSE:
  1037. case SERVICE_CONTROL_CONTINUE:
  1038. case SERVICE_CONTROL_INTERROGATE:
  1039. case SERVICE_CONTROL_SHUTDOWN:
  1040. dwRetCode = NO_ERROR;
  1041. _Handler(dwControl);
  1042. break;
  1043. #if DISABLESECURITYCHECKS
  1044. // this is require for Salem Unit test, we need to update
  1045. // user session status but for pcHealth, resolver will
  1046. // always popup invitation dialog so no need to track
  1047. // user session status.
  1048. case SERVICE_CONTROL_SESSIONCHANGE:
  1049. MYASSERT( NULL != lpEventData );
  1050. if( NULL != lpEventData )
  1051. {
  1052. switch( dwEventType )
  1053. {
  1054. case WTS_SESSION_LOGON:
  1055. DebugPrintf(
  1056. _TEXT("Session %d has log on...\n"),
  1057. ((WTSSESSION_NOTIFICATION *)lpEventData)->dwSessionId
  1058. );
  1059. break;
  1060. case WTS_SESSION_LOGOFF:
  1061. case WTS_CONSOLE_DISCONNECT:
  1062. case WTS_REMOTE_DISCONNECT:
  1063. DebugPrintf(
  1064. _TEXT("Session %d has log off...\n"),
  1065. ((WTSSESSION_NOTIFICATION *)lpEventData)->dwSessionId
  1066. );
  1067. //
  1068. // Deadlock if we use other thread to process logoff or
  1069. // disconnect.
  1070. //
  1071. // Notification thread lock pending help table and need
  1072. // to run Resolver in COM, COM is in the middle of
  1073. // dispatching create help ticket call which also need
  1074. // lock to pending help table, this causes deadlock
  1075. //
  1076. PostThreadMessage(
  1077. _Module.dwThreadID,
  1078. WM_SESSIONLOGOFFDISCONNECT,
  1079. 0,
  1080. (LPARAM)((WTSSESSION_NOTIFICATION *)lpEventData)->dwSessionId
  1081. );
  1082. }
  1083. }
  1084. dwRetCode = NO_ERROR;
  1085. break;
  1086. #endif
  1087. default:
  1088. dwRetCode = ERROR_CALL_NOT_IMPLEMENTED;
  1089. }
  1090. return dwRetCode;
  1091. }
  1092. void WINAPI CServiceModule::_ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv)
  1093. {
  1094. _Module.ServiceMain(dwArgc, lpszArgv);
  1095. }
  1096. void WINAPI CServiceModule::_Handler(DWORD dwOpcode)
  1097. {
  1098. _Module.Handler(dwOpcode);
  1099. }
  1100. void CServiceModule::SetServiceStatus(DWORD dwState)
  1101. {
  1102. m_status.dwCurrentState = dwState;
  1103. ::SetServiceStatus(m_hServiceStatus, &m_status);
  1104. }
  1105. HANDLE CServiceModule::gm_hIdle = NULL;
  1106. HANDLE CServiceModule::gm_hIdleMonitorThread = NULL;
  1107. ULONG
  1108. CServiceModule::AddRef()
  1109. {
  1110. CCriticalSectionLocker l( m_ModuleLock );
  1111. m_RefCount++;
  1112. if( m_RefCount > 0 )
  1113. {
  1114. ASSERT( NULL != gm_hIdle );
  1115. ResetEvent( gm_hIdle );
  1116. }
  1117. return m_RefCount;
  1118. }
  1119. ULONG
  1120. CServiceModule::Release()
  1121. {
  1122. CCriticalSectionLocker l( m_ModuleLock );
  1123. m_RefCount--;
  1124. if( m_RefCount <= 0 )
  1125. {
  1126. // Only signal idle when there is no more pending help
  1127. if( g_HelpSessTable.NumEntries() == 0 )
  1128. {
  1129. ASSERT( NULL != gm_hIdle );
  1130. SetEvent( gm_hIdle );
  1131. }
  1132. }
  1133. return m_RefCount;
  1134. }
  1135. unsigned int WINAPI
  1136. CServiceModule::GPMonitorThread( void* ptr )
  1137. {
  1138. DWORD dwStatus = ERROR_SUCCESS;
  1139. CServiceModule* pServiceModule = (CServiceModule *)ptr;
  1140. if( pServiceModule != NULL )
  1141. {
  1142. dwStatus = WaitForRAGPDisableNotification( g_hServiceShutdown );
  1143. ASSERT(ERROR_SUCCESS == dwStatus || ERROR_SHUTDOWN_IN_PROGRESS == dwStatus);
  1144. pServiceModule->Handler(SERVICE_CONTROL_STOP);
  1145. }
  1146. _endthreadex( dwStatus );
  1147. return dwStatus;
  1148. }
  1149. unsigned int WINAPI
  1150. CServiceModule::IdleMonitorThread( void* ptr )
  1151. {
  1152. DWORD dwStatus = ERROR_SUCCESS;
  1153. BOOL bIdleShutdown = FALSE;
  1154. CServiceModule* pServiceModule = (CServiceModule *)ptr;
  1155. // remove gm_hICSAlertEvent, this event will be removed from ICS lib.
  1156. HANDLE hWaitHandles[] = {g_hServiceShutdown, gm_hIdle};
  1157. CoInitialize(NULL);
  1158. if( pServiceModule != NULL )
  1159. {
  1160. while (TRUE)
  1161. {
  1162. dwStatus = WaitForMultipleObjects(
  1163. sizeof( hWaitHandles ) / sizeof( hWaitHandles[0] ),
  1164. hWaitHandles,
  1165. FALSE,
  1166. EXPIRE_HELPSESSION_PERIOD
  1167. );
  1168. if( WAIT_TIMEOUT == dwStatus )
  1169. {
  1170. // expire help ticket, refer to session logoff/disconnect
  1171. // comment above on why PostThreadMessage.
  1172. PostThreadMessage(
  1173. _Module.dwThreadID,
  1174. WM_EXPIREHELPSESSION,
  1175. 0,
  1176. 0
  1177. );
  1178. }
  1179. else if( WAIT_OBJECT_0 == dwStatus )
  1180. {
  1181. // Main thread signal shutdown.
  1182. dwStatus = ERROR_SUCCESS;
  1183. break;
  1184. }
  1185. else if( WAIT_OBJECT_0 + 1 == dwStatus )
  1186. {
  1187. // we have been idle for too long, time to try shutdown.
  1188. // idle event will only be signal when there is no
  1189. // pending help so we don't have to worry about address
  1190. // changes.
  1191. dwStatus = WaitForSingleObject( g_hServiceShutdown, IDLE_SHUTDOWN_PERIOD );
  1192. if( WAIT_TIMEOUT != dwStatus )
  1193. {
  1194. // Main thread either signnaled shutdown or wait failed due to error, baid out
  1195. break;
  1196. }
  1197. dwStatus = WaitForSingleObject( gm_hIdle, 0 );
  1198. if( WAIT_OBJECT_0 == dwStatus )
  1199. {
  1200. // no one holding object, time to shutdown
  1201. bIdleShutdown = TRUE;
  1202. dwStatus = ERROR_SUCCESS;
  1203. break;
  1204. }
  1205. }
  1206. else if( WAIT_FAILED == dwStatus )
  1207. {
  1208. // some bad thing happen, shutdown.
  1209. //MYASSERT(FALSE);
  1210. break;
  1211. }
  1212. }
  1213. // only need to stop service if shutdown is due to idle
  1214. if( bIdleShutdown )
  1215. {
  1216. pServiceModule->Handler(SERVICE_CONTROL_STOP);
  1217. }
  1218. }
  1219. CoUninitialize();
  1220. _endthreadex( dwStatus );
  1221. return dwStatus;
  1222. }
  1223. BOOL
  1224. CServiceModule::InitializeSessmgr()
  1225. {
  1226. CCriticalSectionLocker l( m_ModuleLock );
  1227. //
  1228. // Already initialize.
  1229. //
  1230. if( m_Initialized )
  1231. {
  1232. return TRUE;
  1233. }
  1234. //
  1235. // Service failed to startup, just return without initialize
  1236. // anything
  1237. //
  1238. if( !_Module.IsSuccessServiceStartup() )
  1239. {
  1240. return FALSE;
  1241. }
  1242. DWORD dwStatus;
  1243. unsigned int junk;
  1244. //
  1245. // Start ICSHELPER library, this library calls into some DLL that
  1246. // makes outgoing COM call which will trigger COM re-entrance, so
  1247. // InitializeSessmgr() must be invoke in helpsessionmgr object
  1248. // constructor instead of service startup time.
  1249. //
  1250. dwStatus = StartICSLib();
  1251. if( ERROR_SUCCESS != dwStatus )
  1252. {
  1253. // Log an error event, we still need to startup
  1254. // so that we can report error back to caller
  1255. LogEventWithStatusCode(
  1256. EVENTLOG_ERROR_TYPE,
  1257. SESSMGR_E_ICSHELPER,
  1258. dwStatus
  1259. );
  1260. _Module.m_dwServiceStartupStatus = SESSMGR_E_ICSHELPER;
  1261. }
  1262. else
  1263. {
  1264. //
  1265. // Go thru all pending tickets and re-punch ICS hole
  1266. //
  1267. CRemoteDesktopHelpSessionMgr::NotifyPendingHelpServiceStartup();
  1268. }
  1269. m_Initialized = TRUE;
  1270. return _Module.IsSuccessServiceStartup();
  1271. }
  1272. ISAFRemoteDesktopCallback* g_pIResolver = NULL;
  1273. // SERVICE_STARTUP_WAITHINT is 30 seconds, retry 6 time will give us
  1274. // 3 mins of wait time.
  1275. #define RA_ACCOUNT_CREATE_RETRYTIME 6
  1276. unsigned int WINAPI
  1277. StartupCreateAccountThread( void* ptr )
  1278. {
  1279. HRESULT hr = S_OK;
  1280. //
  1281. // BDC request pool of RID from DC and during that time, it
  1282. // will return error ERROR_DS_NO_RIDS_ALLOCATED, we wait and retry
  1283. // RA_ACCOUNT_CREATE_RETRYTIME times before we actually fail.
  1284. //
  1285. for(DWORD index=0; index < RA_ACCOUNT_CREATE_RETRYTIME; index++)
  1286. {
  1287. // Try re-create the account
  1288. hr = g_HelpAccount.CreateHelpAccount();
  1289. if( SUCCEEDED(hr) )
  1290. {
  1291. CComBSTR bstrHelpAccName;
  1292. hr = g_HelpAccount.GetHelpAccountNameEx( bstrHelpAccName );
  1293. MYASSERT( SUCCEEDED(hr) );
  1294. if( SUCCEEDED(hr) )
  1295. {
  1296. // Add HelpAssistantAccount into account filter list
  1297. AddAccountToFilterList( bstrHelpAccName );
  1298. }
  1299. break;
  1300. }
  1301. else if( hr != HRESULT_FROM_WIN32(ERROR_DS_NO_RIDS_ALLOCATED) )
  1302. {
  1303. break;
  1304. }
  1305. DebugPrintf(
  1306. _TEXT("CreateHelpAccount() return 0x%08x, retry again...\n"),
  1307. hr
  1308. );
  1309. // Wait one second before continue.
  1310. Sleep( 1000 );
  1311. }
  1312. _endthreadex( hr );
  1313. return hr;
  1314. }
  1315. void CServiceModule::Run()
  1316. {
  1317. //
  1318. // Mark we are not initialized yet...
  1319. //
  1320. m_Initialized = FALSE;
  1321. _Module.dwThreadID = GetCurrentThreadId();
  1322. DWORD dwStatus;
  1323. unsigned int dwJunk;
  1324. WSADATA wsData;
  1325. LPWSTR pszSysAccName = NULL;
  1326. DWORD cbSysAccName = 0;
  1327. LPWSTR pszSysDomainName = NULL;
  1328. DWORD cbSysDomainName = 0;
  1329. SID_NAME_USE SidType;
  1330. BOOL bReCreateRAAccount = FALSE;
  1331. HRESULT hr;
  1332. //
  1333. // make sure no other thread can access _Module until we fully
  1334. // startup.
  1335. //
  1336. m_ModuleLock.Lock();
  1337. //
  1338. // Initialize encryption library
  1339. //
  1340. dwStatus = TSHelpAssistantInitializeEncryptionLib();
  1341. if( ERROR_SUCCESS != dwStatus )
  1342. {
  1343. // Log an error event, we still need to startup
  1344. // so that we can report error back to caller
  1345. LogEventWithStatusCode(
  1346. EVENTLOG_ERROR_TYPE,
  1347. SESSMGR_E_INIT_ENCRYPTIONLIB,
  1348. dwStatus
  1349. );
  1350. _Module.m_dwServiceStartupStatus = SESSMGR_E_INIT_ENCRYPTIONLIB;
  1351. MYASSERT(FALSE);
  1352. }
  1353. else
  1354. {
  1355. //
  1356. // Check if we just started from system restore, if so, restore necessary
  1357. // LSA key.
  1358. //
  1359. RestartFromSystemRestore();
  1360. }
  1361. //
  1362. // Create an manual reset event for background thread to terminate
  1363. // service
  1364. //
  1365. gm_hIdle = CreateEvent(
  1366. NULL,
  1367. TRUE,
  1368. FALSE,
  1369. NULL
  1370. );
  1371. if( NULL == gm_hIdle )
  1372. {
  1373. LogEventWithStatusCode(
  1374. EVENTLOG_ERROR_TYPE,
  1375. SESSMGR_E_GENERALSTARTUP,
  1376. GetLastError()
  1377. );
  1378. _Module.m_dwServiceStartupStatus = SESSMGR_E_GENERALSTARTUP;
  1379. MYASSERT(FALSE);
  1380. }
  1381. //
  1382. // Create a service shutdown event for GP notification thread.
  1383. //
  1384. g_hServiceShutdown = CreateEvent(
  1385. NULL,
  1386. TRUE,
  1387. FALSE,
  1388. NULL
  1389. );
  1390. if( NULL == g_hServiceShutdown )
  1391. {
  1392. LogEventWithStatusCode(
  1393. EVENTLOG_ERROR_TYPE,
  1394. SESSMGR_E_GENERALSTARTUP,
  1395. GetLastError()
  1396. );
  1397. _Module.m_dwServiceStartupStatus = SESSMGR_E_GENERALSTARTUP;
  1398. MYASSERT(FALSE);
  1399. }
  1400. //
  1401. // **** DO NOT CHANGE SEQUENCE ****
  1402. //
  1403. // Refer to XP RAID 407457 for detail
  1404. //
  1405. // A thread named SessMgr!DpNatHlpThread is calling into dpnhupnp.dll,
  1406. // which is doing COM-related stuff, this is happening before the
  1407. // sessmgr!CServiceModule__Run method calls CoInitializeSecurity.
  1408. // When you do COM stuff before calling CoInitSec, COM do it for you,
  1409. // and you end up accepting the defaults
  1410. //
  1411. hr = g_HelpAccount.Initialize();
  1412. if( FAILED(hr) )
  1413. {
  1414. // use seperate thread to re-create RA account
  1415. //
  1416. // BDC request pool of RID from PDC, during this time, account
  1417. // creation will failed with ERROR_DS_NO_RIDS_ALLOCATED.
  1418. // since RA account is needed before we initialize our
  1419. // COM security, we will loop/retry a few time and duing this
  1420. // time, we still need to notify service control manager that
  1421. // we still pending startup.
  1422. //
  1423. HANDLE hCreateAcctThread = NULL;
  1424. bReCreateRAAccount = TRUE;
  1425. hr = S_OK;
  1426. hCreateAcctThread = (HANDLE)_beginthreadex(
  1427. NULL,
  1428. 0,
  1429. StartupCreateAccountThread,
  1430. NULL,
  1431. 0,
  1432. &dwJunk
  1433. );
  1434. if( NULL == hCreateAcctThread )
  1435. {
  1436. dwStatus = GetLastError();
  1437. hr = HRESULT_FROM_WIN32( dwStatus );
  1438. }
  1439. else
  1440. {
  1441. // wait for account creation thread to terminate, thread will retry to
  1442. // create account for number of time before it bail out.
  1443. while( WaitForSingleObject( hCreateAcctThread, SERVICE_STARTUP_WAITHINT ) == WAIT_TIMEOUT )
  1444. {
  1445. SetServiceStatus( SERVICE_START_PENDING );
  1446. continue;
  1447. }
  1448. if( FALSE == GetExitCodeThread( hCreateAcctThread, &dwStatus ) )
  1449. {
  1450. _Module.m_dwServiceStartupStatus = SESSMGR_E_HELPACCOUNT;
  1451. hr = SESSMGR_E_HELPACCOUNT;
  1452. }
  1453. else
  1454. {
  1455. _Module.m_dwServiceStartupStatus = dwStatus;
  1456. hr = HRESULT_FROM_WIN32( dwStatus );
  1457. }
  1458. CloseHandle( hCreateAcctThread );
  1459. }
  1460. if( FAILED(hr) )
  1461. {
  1462. dwStatus = SESSMGR_E_HELPACCOUNT;
  1463. LogEventWithStatusCode(
  1464. EVENTLOG_ERROR_TYPE,
  1465. SESSMGR_E_GENERALSTARTUP,
  1466. hr
  1467. );
  1468. _Module.m_dwServiceStartupStatus = SESSMGR_E_HELPACCOUNT;
  1469. }
  1470. }
  1471. hr = LoadLocalSystemSID();
  1472. if( FAILED(hr) )
  1473. {
  1474. LogEventWithStatusCode(
  1475. EVENTLOG_ERROR_TYPE,
  1476. SESSMGR_E_GENERALSTARTUP,
  1477. hr
  1478. );
  1479. _Module.m_dwServiceStartupStatus = SESSMGR_E_GENERALSTARTUP;
  1480. MYASSERT(FALSE);
  1481. }
  1482. //
  1483. // We always need to startup otherwise will cause caller to timeout
  1484. // or AV.
  1485. //
  1486. // hr = CoInitialize(NULL);
  1487. // If you are running on NT 4.0 or higher you can use the following call
  1488. // instead to make the EXE free threaded.
  1489. // This means that calls come in on a random RPC thread
  1490. hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
  1491. _ASSERTE(SUCCEEDED(hr));
  1492. CSecurityDescriptor sd;
  1493. sd.InitializeFromThreadToken(); // get a default DACL
  1494. #ifndef DISABLESECURITYCHECKS
  1495. if( _Module.IsSuccessServiceStartup() )
  1496. {
  1497. BOOL bSuccess;
  1498. CComBSTR bstrHelpAccName;
  1499. //
  1500. // Retrieve System account name, might not be necessary since this
  1501. // pre-defined account shouldn't be localizable.
  1502. //
  1503. pszSysAccName = NULL;
  1504. cbSysAccName = 0;
  1505. pszSysDomainName = NULL;
  1506. cbSysDomainName = 0;
  1507. bSuccess = LookupAccountSid(
  1508. NULL,
  1509. g_pSidSystem,
  1510. pszSysAccName,
  1511. &cbSysAccName,
  1512. pszSysDomainName,
  1513. &cbSysDomainName,
  1514. &SidType
  1515. );
  1516. if( TRUE == bSuccess ||
  1517. ERROR_INSUFFICIENT_BUFFER == GetLastError() )
  1518. {
  1519. pszSysAccName = (LPWSTR) LocalAlloc( LPTR, (cbSysAccName + 1) * sizeof(WCHAR) );
  1520. pszSysDomainName = (LPWSTR) LocalAlloc( LPTR, (cbSysDomainName + 1) * sizeof(WCHAR) );
  1521. if( NULL != pszSysAccName && NULL != pszSysDomainName )
  1522. {
  1523. bSuccess = LookupAccountSid(
  1524. NULL,
  1525. g_pSidSystem,
  1526. pszSysAccName,
  1527. &cbSysAccName,
  1528. pszSysDomainName,
  1529. &cbSysDomainName,
  1530. &SidType
  1531. );
  1532. if( TRUE == bSuccess )
  1533. {
  1534. hr = sd.Allow( pszSysAccName, COM_RIGHTS_EXECUTE );
  1535. }
  1536. }
  1537. }
  1538. if( FALSE == bSuccess )
  1539. {
  1540. dwStatus = GetLastError();
  1541. hr = HRESULT_FROM_WIN32( dwStatus );
  1542. MYASSERT( SUCCEEDED(hr) );
  1543. }
  1544. //
  1545. // Add access permission to help assistant account
  1546. if( SUCCEEDED(hr) )
  1547. {
  1548. //
  1549. // Allow access to HelpAssistant account
  1550. //
  1551. hr = g_HelpAccount.GetHelpAccountNameEx( bstrHelpAccName );
  1552. if( SUCCEEDED(hr) )
  1553. {
  1554. hr = sd.Allow( (LPCTSTR)bstrHelpAccName, COM_RIGHTS_EXECUTE );
  1555. MYASSERT( SUCCEEDED(hr) );
  1556. }
  1557. }
  1558. //
  1559. // If we failed in setting DACL, we still need to startup but without
  1560. // full security, however, our interface will fail because service
  1561. // does not initialize correctly.
  1562. //
  1563. if( FAILED(hr) )
  1564. {
  1565. LogEventWithStatusCode(
  1566. EVENTLOG_ERROR_TYPE,
  1567. SESSMGR_E_RESTRICTACCESS,
  1568. hr
  1569. );
  1570. _Module.m_dwServiceStartupStatus = SESSMGR_E_RESTRICTACCESS;
  1571. }
  1572. }
  1573. #endif
  1574. //
  1575. // We still need to startup or client might behave weird; interface call
  1576. // will be block by checking service startup status.
  1577. //
  1578. hr = CoInitializeSecurity(
  1579. sd,
  1580. -1,
  1581. NULL,
  1582. NULL,
  1583. RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
  1584. RPC_C_IMP_LEVEL_IDENTIFY,
  1585. NULL,
  1586. EOAC_NONE,
  1587. NULL
  1588. );
  1589. _ASSERTE(SUCCEEDED(hr));
  1590. hr = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE);
  1591. _ASSERTE(SUCCEEDED(hr));
  1592. //
  1593. // Load unknown string for event loggging
  1594. //
  1595. g_UnknownString.LoadString( IDS_UNKNOWN );
  1596. //
  1597. // Load RA and URA string for event log
  1598. //
  1599. g_RAString.LoadString( IDS_RA_STRING );
  1600. g_URAString.LoadString( IDS_URA_STRING );
  1601. if( _Module.IsSuccessServiceStartup() )
  1602. {
  1603. //
  1604. // Startup TLSAPI in order to get public key
  1605. //
  1606. dwStatus = TLSInit();
  1607. if( LICENSE_STATUS_OK != dwStatus )
  1608. {
  1609. LogEventWithStatusCode(
  1610. EVENTLOG_ERROR_TYPE,
  1611. SESSMGR_E_GENERALSTARTUP,
  1612. dwStatus
  1613. );
  1614. _Module.m_dwServiceStartupStatus = SESSMGR_E_GENERALSTARTUP;
  1615. MYASSERT(FALSE);
  1616. }
  1617. }
  1618. if( _Module.IsSuccessServiceStartup() )
  1619. {
  1620. //
  1621. // Load TermSrv public key, on PRO/PER we load public key from
  1622. // non-x509 certificate, on other SKU, we register a registry change
  1623. // notification and post ourself a message regarding public key
  1624. // change.
  1625. //
  1626. dwStatus = LoadAndSetupTSCertChangeNotification();
  1627. MYASSERT( ERROR_SUCCESS == dwStatus );
  1628. if( ERROR_SUCCESS != dwStatus )
  1629. {
  1630. // Log an error event, we still need to startup
  1631. // so that we can report error back to caller
  1632. LogEventWithStatusCode(
  1633. EVENTLOG_ERROR_TYPE,
  1634. SESSMGR_E_GENERALSTARTUP,
  1635. dwStatus
  1636. );
  1637. _Module.m_dwServiceStartupStatus = SESSMGR_E_GENERALSTARTUP;
  1638. }
  1639. }
  1640. if( _Module.IsSuccessServiceStartup() )
  1641. {
  1642. //
  1643. // startup WSA so we can invoke gethostname()
  1644. // critical error if we can startup WSA
  1645. if( WSAStartup(0x0101, &wsData) != 0 )
  1646. {
  1647. // Log an error event, we still need to startup
  1648. // so that we can report error back to caller
  1649. LogEventWithStatusCode(
  1650. EVENTLOG_ERROR_TYPE,
  1651. SESSMGR_E_WSASTARTUP,
  1652. GetLastError()
  1653. );
  1654. _Module.m_dwServiceStartupStatus = SESSMGR_E_WSASTARTUP;
  1655. }
  1656. }
  1657. if( _Module.IsSuccessServiceStartup() )
  1658. {
  1659. hr = g_HelpSessTable.OpenSessionTable(NULL);
  1660. if( FAILED(hr) )
  1661. {
  1662. LogEventWithStatusCode(
  1663. EVENTLOG_ERROR_TYPE,
  1664. SESSMGR_E_HELPSESSIONTABLE,
  1665. hr
  1666. );
  1667. _Module.m_dwServiceStartupStatus = SESSMGR_E_HELPSESSIONTABLE;
  1668. MYASSERT(FALSE);
  1669. }
  1670. }
  1671. if( _Module.IsSuccessServiceStartup() )
  1672. {
  1673. if( g_HelpSessTable.NumEntries() == 0)
  1674. {
  1675. // Immediately set event to signal state so idle monitor
  1676. // thread can start shutdown timer.
  1677. SetEvent( gm_hIdle );
  1678. g_HelpAccount.EnableHelpAssistantAccount(FALSE);
  1679. g_HelpAccount.EnableRemoteInteractiveRight(FALSE);
  1680. }
  1681. else
  1682. {
  1683. // outstanding ticket exists, set event to non-signal state
  1684. // and don't let idle monitor thread to start shutdown timer.
  1685. ResetEvent( gm_hIdle );
  1686. //
  1687. // make sure HelpAssistant account is enabled and can logon locally
  1688. //
  1689. g_HelpAccount.EnableHelpAssistantAccount(TRUE);
  1690. g_HelpAccount.EnableRemoteInteractiveRight(TRUE);
  1691. //
  1692. // demote BDC back to server in domain.
  1693. //
  1694. g_HelpAccount.SetupHelpAccountTSSettings( bReCreateRAAccount );
  1695. }
  1696. // Create nackground thread thread
  1697. gm_hIdleMonitorThread = (HANDLE)_beginthreadex(
  1698. NULL,
  1699. 0,
  1700. IdleMonitorThread,
  1701. (HANDLE)this,
  1702. 0,
  1703. &dwJunk
  1704. );
  1705. if( NULL == gm_hIdleMonitorThread )
  1706. {
  1707. _Module.m_dwServiceStartupStatus = SESSMGR_E_GENERALSTARTUP;
  1708. }
  1709. // Create background thread to monitor RA GP change.
  1710. // We have to use extra thread because
  1711. g_hGPMonitorThread = (HANDLE)_beginthreadex(
  1712. NULL,
  1713. 0,
  1714. GPMonitorThread,
  1715. (HANDLE)this,
  1716. 0,
  1717. &dwJunk
  1718. );
  1719. if( NULL == g_hGPMonitorThread )
  1720. {
  1721. _Module.m_dwServiceStartupStatus = SESSMGR_E_GENERALSTARTUP;
  1722. }
  1723. }
  1724. //LogEvent(_T("Service started"));
  1725. if (m_bService)
  1726. SetServiceStatus(SERVICE_RUNNING);
  1727. //
  1728. // Load resolver, this will put one ref. count on it
  1729. // so it won't got unload until we are done.
  1730. //
  1731. hr = CoCreateInstance(
  1732. SESSIONRESOLVERCLSID,
  1733. NULL,
  1734. CLSCTX_INPROC_SERVER | CLSCTX_DISABLE_AAA,
  1735. IID_ISAFRemoteDesktopCallback,
  1736. (void **)&g_pIResolver
  1737. );
  1738. MYASSERT( SUCCEEDED(hr) );
  1739. if( FAILED(hr) )
  1740. {
  1741. //
  1742. // Can't initialize session resolver,
  1743. // session resolver will not be able to
  1744. // do caching.
  1745. //
  1746. LogEventWithStatusCode(
  1747. EVENTLOG_WARNING_TYPE,
  1748. SESSMGR_E_SESSIONRESOLVER,
  1749. hr
  1750. );
  1751. _Module.m_dwServiceStartupStatus = SESSMGR_E_SESSIONRESOLVER;
  1752. }
  1753. m_ModuleLock.UnLock();
  1754. MSG msg;
  1755. while (GetMessage(&msg, 0, 0, 0))
  1756. {
  1757. switch( msg.message )
  1758. {
  1759. case WM_EXPIREHELPSESSION:
  1760. DebugPrintf(_TEXT("Executing TimeoutHelpSesion()...\n"));
  1761. CRemoteDesktopHelpSessionMgr::TimeoutHelpSesion();
  1762. break;
  1763. #if DISABLESECURITYCHECKS
  1764. case WM_SESSIONLOGOFFDISCONNECT:
  1765. DebugPrintf(_TEXT("Executing NotifySessionLogoff() %d...\n"), msg.lParam);
  1766. NotifySessionLogoff( msg.lParam );
  1767. break;
  1768. #endif
  1769. case WM_LOADTSPUBLICKEY:
  1770. DebugPrintf( _TEXT("Executing LoadTermSrvSecurityBlob() ...\n") );
  1771. dwStatus = LoadTermSrvSecurityBlob();
  1772. if( ERROR_SUCCESS != dwStatus )
  1773. {
  1774. // Log an error event, we still need to startup
  1775. // so that we can report error back to caller
  1776. LogEventWithStatusCode(
  1777. EVENTLOG_ERROR_TYPE,
  1778. SESSMGR_E_GENERALSTARTUP,
  1779. dwStatus
  1780. );
  1781. _Module.m_dwServiceStartupStatus = SESSMGR_E_GENERALSTARTUP;
  1782. }
  1783. break;
  1784. case WM_HELPERRDSADDINEXIT:
  1785. DebugPrintf( _TEXT("WM_HELPERRDSADDINEXIT()...\n") );
  1786. CRemoteDesktopHelpSessionMgr::NotifyExpertLogoff( msg.wParam, (BSTR)msg.lParam );
  1787. break;
  1788. default:
  1789. DispatchMessage(&msg);
  1790. }
  1791. }
  1792. //
  1793. // Calling StopICSLib() while there is a call into ICS lib's OpenPort()
  1794. // will cause deadlock in this main thread, ICS lib's DpNatHlpThread()'s
  1795. // shutdown and ICS lib's OpenPort().
  1796. //
  1797. // First call is to lock access to InitializeSessmgr() which is call on FinalConstruct()
  1798. // of CRemoteDesktopHelpSessionMgr, second is lock calls into ICS lib to make sure
  1799. // no client is making call into ICS lib.
  1800. m_ModuleLock.Lock();
  1801. g_ICSLibLock.Lock();
  1802. if( g_hServiceShutdown )
  1803. {
  1804. // Signal we are shutting down
  1805. SetEvent(g_hServiceShutdown);
  1806. }
  1807. if( g_hGPMonitorThread )
  1808. {
  1809. // GPMonitor thread can stuck for DELAY_SHUTDOWN_SALEM_TIME
  1810. // waiting for policy change so we wait twice that time.
  1811. dwStatus = WaitForSingleObject(
  1812. g_hGPMonitorThread,
  1813. DELAY_SHUTDOWN_SALEM_TIME * 2
  1814. );
  1815. ASSERT( dwStatus == WAIT_OBJECT_0 );
  1816. }
  1817. if( gm_hIdleMonitorThread )
  1818. {
  1819. // Wait for IdleMonitor thread to shutdown
  1820. dwStatus = WaitForSingleObject(
  1821. gm_hIdleMonitorThread,
  1822. DELAY_SHUTDOWN_SALEM_TIME * 2
  1823. );
  1824. ASSERT( dwStatus == WAIT_OBJECT_0 );
  1825. }
  1826. CleanupMonitorExpertList();
  1827. if( g_hWaitTSCertificateChanged )
  1828. {
  1829. UnregisterWait( g_hWaitTSCertificateChanged );
  1830. g_hWaitTSCertificateChanged = NULL;
  1831. }
  1832. if( g_hTSCertificateChanged )
  1833. {
  1834. CloseHandle( g_hTSCertificateChanged );
  1835. g_hTSCertificateChanged = NULL;
  1836. }
  1837. if( g_hTSCertificateRegKey )
  1838. {
  1839. RegCloseKey( g_hTSCertificateRegKey );
  1840. g_hTSCertificateRegKey = NULL;
  1841. }
  1842. //
  1843. // If service is started manually, we won't be able to call
  1844. // StartICSLib() and will close invalid handle in ICS.
  1845. //
  1846. if( m_Initialized )
  1847. {
  1848. // Close all port including close firewall.
  1849. CloseAllOpenPorts();
  1850. // Stop ICS library, ignore error code.
  1851. StopICSLib();
  1852. }
  1853. g_ICSLibLock.UnLock();
  1854. m_ModuleLock.UnLock();
  1855. //
  1856. // sync. access to resolver.
  1857. //
  1858. {
  1859. CCriticalSectionLocker Lock(g_ResolverLock);
  1860. if( NULL != g_pIResolver )
  1861. {
  1862. g_pIResolver->Release();
  1863. g_pIResolver = NULL;
  1864. }
  1865. }
  1866. _Module.RevokeClassObjects();
  1867. CoUninitialize();
  1868. //
  1869. // No outstanding ticket, delete the account
  1870. //
  1871. if( g_HelpSessTable.NumEntries() == 0)
  1872. {
  1873. CComBSTR bstrHelpAccName;
  1874. hr = g_HelpAccount.GetHelpAccountNameEx( bstrHelpAccName );
  1875. MYASSERT( SUCCEEDED(hr) );
  1876. if( SUCCEEDED(hr) )
  1877. {
  1878. // Add HelpAssistantAccount into account filter list
  1879. DeleteAccountFromFilterList( bstrHelpAccName );
  1880. }
  1881. g_HelpAccount.DeleteHelpAccount();
  1882. }
  1883. else
  1884. {
  1885. // Extra security measure, at the time of shutdown,
  1886. // if there is outstanding ticket, we disable helpassistant
  1887. // account, on service startup, we will re-enable it again.
  1888. g_HelpAccount.EnableHelpAssistantAccount(FALSE);
  1889. g_HelpAccount.EnableRemoteInteractiveRight(FALSE);
  1890. }
  1891. if( NULL != gm_hIdle )
  1892. {
  1893. CloseHandle( gm_hIdle );
  1894. gm_hIdle = NULL;
  1895. }
  1896. if( WSACleanup() != 0 )
  1897. {
  1898. // shutting down, ignore WSA error
  1899. #if DBG
  1900. OutputDebugString( _TEXT("WSACleanup() failed...\n") );
  1901. #endif
  1902. }
  1903. #if DBG
  1904. OutputDebugString( _TEXT("Help Session Manager Exited...\n") );
  1905. #endif
  1906. // Close the help session table, help session table
  1907. // open by init. thread
  1908. g_HelpSessTable.CloseSessionTable();
  1909. TSHelpAssistantEndEncryptionLib();
  1910. if( NULL != pszSysAccName )
  1911. {
  1912. LocalFree( pszSysAccName );
  1913. }
  1914. if( NULL != pszSysDomainName )
  1915. {
  1916. LocalFree( pszSysDomainName );
  1917. }
  1918. if( NULL != gm_hIdleMonitorThread )
  1919. {
  1920. CloseHandle( gm_hIdleMonitorThread );
  1921. }
  1922. if( NULL != g_hGPMonitorThread )
  1923. {
  1924. CloseHandle( g_hGPMonitorThread );
  1925. }
  1926. if( NULL != g_hServiceShutdown )
  1927. {
  1928. CloseHandle( g_hServiceShutdown );
  1929. }
  1930. TLSShutdown();
  1931. }
  1932. #define OLD_SALEMHELPASSISTANTACCOUNT_PASSWORDKEY \
  1933. L"0083343a-f925-4ed7-b1d6-d95d17a0b57b-RemoteDesktopHelpAssistantAccount"
  1934. #define OLD_SALEMHELPASSISTANTACCOUNT_SIDKEY \
  1935. L"0083343a-f925-4ed7-b1d6-d95d17a0b57b-RemoteDesktopHelpAssistantSID"
  1936. #define OLD_SALEMHELPASSISTANTACCOUNT_ENCRYPTIONKEY \
  1937. L"c261dd33-c55b-4a37-924b-746bbf3569ad-RemoteDesktopHelpAssistantEncrypt"
  1938. #define OLD_HELPACCOUNTPROPERLYSETUP \
  1939. _TEXT("20ed87e2-3b82-4114-81f9-5e219ed4c481-SALEMHELPACCOUNT")
  1940. VOID
  1941. TransferLSASecretKey()
  1942. /*++
  1943. Routine Description:
  1944. Retrieve data we store in LSA secret key and re-store it with LSA key prefixed with L$
  1945. to make LSA secret value local to machine only.
  1946. Parameters:
  1947. None.
  1948. Returns:
  1949. None.
  1950. --*/
  1951. {
  1952. PBYTE pbData = NULL;
  1953. DWORD cbData = 0;
  1954. DWORD dwStatus;
  1955. dwStatus = RetrieveKeyFromLSA(
  1956. OLD_HELPACCOUNTPROPERLYSETUP,
  1957. (PBYTE *)&pbData,
  1958. &cbData
  1959. );
  1960. if( ERROR_SUCCESS == dwStatus )
  1961. {
  1962. //
  1963. // Old key exists, store it with new key and delete the old key.
  1964. //
  1965. dwStatus = StoreKeyWithLSA(
  1966. HELPACCOUNTPROPERLYSETUP,
  1967. pbData,
  1968. cbData
  1969. );
  1970. SecureZeroMemory( pbData, cbData );
  1971. LocalFree(pbData);
  1972. pbData = NULL;
  1973. cbData = 0;
  1974. }
  1975. dwStatus = RetrieveKeyFromLSA(
  1976. OLD_SALEMHELPASSISTANTACCOUNT_PASSWORDKEY,
  1977. (PBYTE *)&pbData,
  1978. &cbData
  1979. );
  1980. if( ERROR_SUCCESS == dwStatus )
  1981. {
  1982. //
  1983. // Old key exists, store it with new key and delete the old key.
  1984. //
  1985. dwStatus = StoreKeyWithLSA(
  1986. SALEMHELPASSISTANTACCOUNT_PASSWORDKEY,
  1987. pbData,
  1988. cbData
  1989. );
  1990. SecureZeroMemory( pbData, cbData );
  1991. LocalFree(pbData);
  1992. pbData = NULL;
  1993. cbData = 0;
  1994. }
  1995. dwStatus = RetrieveKeyFromLSA(
  1996. OLD_SALEMHELPASSISTANTACCOUNT_SIDKEY,
  1997. (PBYTE *)&pbData,
  1998. &cbData
  1999. );
  2000. if( ERROR_SUCCESS == dwStatus )
  2001. {
  2002. //
  2003. // Old key exists, store it with new key and delete the old key.
  2004. //
  2005. dwStatus = StoreKeyWithLSA(
  2006. SALEMHELPASSISTANTACCOUNT_SIDKEY,
  2007. pbData,
  2008. cbData
  2009. );
  2010. SecureZeroMemory( pbData, cbData );
  2011. LocalFree(pbData);
  2012. pbData = NULL;
  2013. cbData = 0;
  2014. }
  2015. dwStatus = RetrieveKeyFromLSA(
  2016. OLD_SALEMHELPASSISTANTACCOUNT_ENCRYPTIONKEY,
  2017. (PBYTE *)&pbData,
  2018. &cbData
  2019. );
  2020. if( ERROR_SUCCESS == dwStatus )
  2021. {
  2022. //
  2023. // Old key exists, store it with new key and delete the old key.
  2024. //
  2025. dwStatus = StoreKeyWithLSA(
  2026. SALEMHELPASSISTANTACCOUNT_ENCRYPTIONKEY,
  2027. pbData,
  2028. cbData
  2029. );
  2030. SecureZeroMemory( pbData, cbData );
  2031. LocalFree(pbData);
  2032. pbData = NULL;
  2033. cbData = 0;
  2034. }
  2035. //
  2036. // Delete the key and ignore the error.
  2037. //
  2038. StoreKeyWithLSA(
  2039. OLD_HELPACCOUNTPROPERLYSETUP,
  2040. NULL,
  2041. 0
  2042. );
  2043. StoreKeyWithLSA(
  2044. OLD_SALEMHELPASSISTANTACCOUNT_PASSWORDKEY,
  2045. NULL,
  2046. 0
  2047. );
  2048. StoreKeyWithLSA(
  2049. OLD_SALEMHELPASSISTANTACCOUNT_SIDKEY,
  2050. NULL,
  2051. 0
  2052. );
  2053. StoreKeyWithLSA(
  2054. OLD_SALEMHELPASSISTANTACCOUNT_ENCRYPTIONKEY,
  2055. NULL,
  2056. 0
  2057. );
  2058. return;
  2059. }
  2060. #define UNINSTALL_BEFORE_INSTALL _TEXT("UninstallBeforeInstall")
  2061. HRESULT
  2062. InstallUninstallSessmgr(
  2063. DWORD code
  2064. )
  2065. /*++
  2066. --*/
  2067. {
  2068. FILE* pSetupLog;
  2069. TCHAR LogFile[MAX_PATH+1];
  2070. HRESULT hRes = S_OK;
  2071. DWORD dwStatus = ERROR_SUCCESS;
  2072. HKEY hKey = NULL;
  2073. DWORD dwValue = 1;
  2074. DWORD dwType;
  2075. DWORD cbData = sizeof(dwValue);
  2076. GetWindowsDirectory( LogFile, MAX_PATH );
  2077. lstrcat( LogFile, L"\\" );
  2078. lstrcat( LogFile, SETUPLOGFILE_NAME );
  2079. pSetupLog = _tfopen( LogFile, L"a+t" );
  2080. MYASSERT( NULL != pSetupLog );
  2081. LogSetup( pSetupLog, L"\n\n********* Install/uninstall sessmgr service *********\n" );
  2082. //
  2083. // no checking on return, if failure, we just do OutputDebugString();
  2084. //
  2085. switch( code )
  2086. {
  2087. case SESSMGR_UNREGSERVER:
  2088. {
  2089. LogSetup( pSetupLog, L"Uninstalling sessmgr service\n" );
  2090. //
  2091. // Delete all pending help session.
  2092. //
  2093. dwStatus = RegDelKey(
  2094. HKEY_LOCAL_MACHINE,
  2095. REGKEYCONTROL_REMDSK _TEXT("\\") REGKEY_HELPSESSIONTABLE
  2096. );
  2097. LogSetup( pSetupLog, L"Delete pending table return %d\n", dwStatus );
  2098. //
  2099. // We might not be running in system context so deleting registry and
  2100. // cleanup LSA key will fail, write a key to our control location to
  2101. // mark such that delete everything before install
  2102. //
  2103. dwStatus = RegOpenKeyEx(
  2104. HKEY_LOCAL_MACHINE,
  2105. REGKEYCONTROL_REMDSK,
  2106. 0,
  2107. KEY_ALL_ACCESS,
  2108. &hKey
  2109. );
  2110. if( ERROR_SUCCESS == dwStatus )
  2111. {
  2112. dwStatus = RegSetValueEx(
  2113. hKey,
  2114. UNINSTALL_BEFORE_INSTALL,
  2115. 0,
  2116. REG_DWORD,
  2117. (BYTE *) &dwValue,
  2118. sizeof(dwValue)
  2119. );
  2120. if( ERROR_SUCCESS != dwStatus )
  2121. {
  2122. LogSetup( pSetupLog, L"Failed to set value, error code %d\n", dwStatus );
  2123. MYASSERT(FALSE);
  2124. }
  2125. RegCloseKey( hKey );
  2126. }
  2127. else
  2128. {
  2129. // This is OK since we havn't been install before.
  2130. LogSetup( pSetupLog, L"Failed to open control key, error code %d\n", dwStatus );
  2131. }
  2132. //
  2133. // Initialize to get help account name.
  2134. //
  2135. hRes = g_HelpAccount.Initialize();
  2136. LogSetup( pSetupLog, L"Initialize help account return 0x%08x\n", hRes );
  2137. //
  2138. // ignore error, try to delete the account
  2139. hRes = g_HelpAccount.DeleteHelpAccount();
  2140. LogSetup( pSetupLog, L"Delete help account return 0x%08x\n", hRes );
  2141. MYASSERT( SUCCEEDED(hRes) );
  2142. hRes = _Module.UnregisterServer(pSetupLog);
  2143. LogSetup( pSetupLog, L"UnregisterServer() returns 0x%08x\n", hRes );
  2144. if( ERROR_SUCCESS == StartICSLib() )
  2145. {
  2146. // Non-critical if we can't startup the lib since after we shutdown,
  2147. // we would have close all the port
  2148. CloseAllOpenPorts();
  2149. StopICSLib();
  2150. }
  2151. }
  2152. break;
  2153. case SESSMGR_REGSERVER:
  2154. {
  2155. LogSetup( pSetupLog, L"Installing as non-service\n" );
  2156. #if DBG
  2157. AddAccountToFilterList( HELPASSISTANTACCOUNT_NAME );
  2158. MYASSERT( ERROR_SUCCESS == g_HelpAccount.CreateHelpAccount() ) ;
  2159. hRes = _Module.RegisterServer(pSetupLog, TRUE, FALSE);
  2160. #else
  2161. hRes = E_INVALIDARG;
  2162. #endif
  2163. }
  2164. break;
  2165. //case SESSMGR_UPGRADE:
  2166. //
  2167. // TODO - ICS work, add upgrade special code.
  2168. //
  2169. case SESSMGR_SERVICE:
  2170. {
  2171. LogSetup( pSetupLog, L"Installing sessmgr service\n" );
  2172. hRes = S_OK;
  2173. //
  2174. // Clean up again, we might not be running in system
  2175. // context at the time of uninstall so clean up will failed.
  2176. //
  2177. dwStatus = RegOpenKeyEx(
  2178. HKEY_LOCAL_MACHINE,
  2179. REGKEYCONTROL_REMDSK,
  2180. 0,
  2181. KEY_ALL_ACCESS,
  2182. &hKey
  2183. );
  2184. if( ERROR_SUCCESS == dwStatus )
  2185. {
  2186. //
  2187. // Check to see if previous uninstall failed,
  2188. // we only need to check value exists.
  2189. //
  2190. dwStatus = RegQueryValueEx(
  2191. hKey,
  2192. UNINSTALL_BEFORE_INSTALL,
  2193. 0,
  2194. &dwType,
  2195. (BYTE *) &dwValue,
  2196. &cbData
  2197. );
  2198. if( ERROR_SUCCESS != dwStatus || REG_DWORD != dwType )
  2199. {
  2200. //
  2201. // No previous uninstall information, no need to delete anything
  2202. //
  2203. LogSetup( pSetupLog, L"UninstallBeforeInstall value not found or invalid, code %d\n", dwStatus );
  2204. }
  2205. else
  2206. {
  2207. LogSetup( pSetupLog, L"UninstallBeforeInstall exists, cleanup previous uninstall\n" );
  2208. //
  2209. // Previous uninstall failed, delete all pending help session,
  2210. // and clean up encryption key
  2211. //
  2212. dwStatus = RegDelKey(
  2213. HKEY_LOCAL_MACHINE,
  2214. REGKEYCONTROL_REMDSK _TEXT("\\") REGKEY_HELPSESSIONTABLE
  2215. );
  2216. //
  2217. // It's OK to fail here since we reset encryption key making existing
  2218. // ticket useless and will be deleted on expire.
  2219. //
  2220. LogSetup( pSetupLog, L"Delete pending table return %d\n", dwStatus );
  2221. dwStatus = TSHelpAssistantInitializeEncryptionLib();
  2222. if( ERROR_SUCCESS == dwStatus )
  2223. {
  2224. dwStatus = TSHelpAssisantEndEncryptionCycle();
  2225. if( ERROR_SUCCESS != dwStatus )
  2226. {
  2227. LogSetup( pSetupLog, L"TSHelpAssisantEndEncryptionCycle() returns 0x%08x\n", dwStatus );
  2228. LogSetup( pSetupLog, L"sessmgr setup can't continue\n" );
  2229. // Critical security error, existing ticket might still be valid
  2230. hRes = HRESULT_FROM_WIN32( dwStatus );
  2231. }
  2232. TSHelpAssistantEndEncryptionLib();
  2233. }
  2234. else
  2235. {
  2236. LogSetup( pSetupLog, L"TSHelpAssistantInitializeEncryptionLib return %d\n", dwStatus );
  2237. LogSetup( pSetupLog, L"sessmgr setup can't continue\n" );
  2238. // Critical security error, existing ticket might still be valid
  2239. hRes = HRESULT_FROM_WIN32( dwStatus );
  2240. }
  2241. }
  2242. if( SUCCEEDED(hRes) )
  2243. {
  2244. //
  2245. // Delete reg. value to uninstall before install only when successfully
  2246. // resetting encryption key
  2247. //
  2248. RegDeleteValue( hKey, UNINSTALL_BEFORE_INSTALL );
  2249. }
  2250. RegCloseKey( hKey );
  2251. }
  2252. if( SUCCEEDED(hRes) )
  2253. {
  2254. // SECURITY: prefix LSA key with L$ and delete old LSA key.
  2255. TransferLSASecretKey();
  2256. // Bug Fix : 590840, delay help assistant account creation until service start.
  2257. hRes = g_HelpAccount.Initialize();
  2258. if( SUCCEEDED(hRes) )
  2259. {
  2260. hRes = g_HelpAccount.DeleteHelpAccount();
  2261. if( FAILED(hRes) )
  2262. {
  2263. // None Critical Error.
  2264. LogSetup( pSetupLog, L"Failed to delete HelpAssistant account 0x%08x\n", hRes );
  2265. }
  2266. }
  2267. hRes = _Module.RegisterServer(pSetupLog, TRUE, TRUE);
  2268. if( FAILED(hRes) )
  2269. {
  2270. LogSetup( pSetupLog, L"Failed to register/installing service - 0x%08x\n", hRes );
  2271. }
  2272. }
  2273. if( SUCCEEDED(hRes) )
  2274. {
  2275. hRes = CHelpSessionTable::CreatePendingHelpTable();
  2276. if( FAILED(hRes) )
  2277. {
  2278. LogSetup(
  2279. pSetupLog,
  2280. L"CreatePendingHelpTable() failed - 0x%08x\n",
  2281. hRes
  2282. );
  2283. }
  2284. }
  2285. }
  2286. break;
  2287. default:
  2288. LogSetup( pSetupLog, L"Invalid setup operation %d\n", code );
  2289. hRes = E_UNEXPECTED;
  2290. }
  2291. LogSetup( pSetupLog, L"\n*** Finish Setup with Status 0x%08x ***\n", hRes );
  2292. if( pSetupLog )
  2293. {
  2294. fflush( pSetupLog );
  2295. fclose( pSetupLog);
  2296. }
  2297. return hRes;
  2298. }
  2299. /////////////////////////////////////////////////////////////////////////////
  2300. //
  2301. extern "C" int WINAPI _tWinMain(HINSTANCE hInstance,
  2302. HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nShowCmd*/)
  2303. {
  2304. HRESULT hRes;
  2305. CComBSTR bstrErrMsg;
  2306. CComBSTR bstrServiceDesc;
  2307. DWORD dwStatus;
  2308. lpCmdLine = GetCommandLine(); //this line necessary for _ATL_MIN_CRT
  2309. _Module.Init(ObjectMap, hInstance, IDS_SERVICENAME, IDS_SERVICEDISPLAYNAME, IDS_SERVICEDESC, &LIBID_RDSESSMGRLib);
  2310. _Module.m_bService = TRUE;
  2311. TCHAR szTokens[] = _T("-/");
  2312. //
  2313. // We don't do OS version checking as in Win9x case, some of our
  2314. // call uses API not exists on Win9x so will get unresolve
  2315. // reference when running on Win9x box.
  2316. //
  2317. bstrServiceDesc.LoadString( IDS_SERVICEDISPLAYNAME );
  2318. LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);
  2319. while (lpszToken != NULL)
  2320. {
  2321. if (lstrcmpi(lpszToken, _T("UnregServer"))==0)
  2322. {
  2323. return InstallUninstallSessmgr( SESSMGR_UNREGSERVER );
  2324. }
  2325. else if (lstrcmpi(lpszToken, _T("RegServer"))==0)
  2326. {
  2327. return InstallUninstallSessmgr( SESSMGR_REGSERVER );
  2328. }
  2329. else if (lstrcmpi(lpszToken, _T("Service"))==0)
  2330. {
  2331. return InstallUninstallSessmgr( SESSMGR_SERVICE );
  2332. }
  2333. lpszToken = FindOneOf(lpszToken, szTokens);
  2334. }
  2335. // Are we Service or Local Server
  2336. CRegKey keyAppID;
  2337. LONG lRes = keyAppID.Open(HKEY_CLASSES_ROOT, _T("AppID"), KEY_READ);
  2338. if (lRes != ERROR_SUCCESS)
  2339. {
  2340. LogRemoteAssistanceEventString(
  2341. EVENTLOG_ERROR_TYPE,
  2342. SESSMGR_E_SETUP,
  2343. 0,
  2344. NULL
  2345. );
  2346. return lRes;
  2347. }
  2348. CRegKey key;
  2349. lRes = key.Open(keyAppID, _T("{038ABBA4-4138-4AC4-A492-4A3DF068BD8A}"), KEY_READ);
  2350. if (lRes != ERROR_SUCCESS)
  2351. {
  2352. LogRemoteAssistanceEventString(
  2353. EVENTLOG_ERROR_TYPE,
  2354. SESSMGR_E_SETUP,
  2355. 0,
  2356. NULL
  2357. );
  2358. return lRes;
  2359. }
  2360. TCHAR szValue[_MAX_PATH];
  2361. DWORD dwLen = _MAX_PATH;
  2362. lRes = key.QueryValue(szValue, _T("LocalService"), &dwLen);
  2363. _Module.m_bService = FALSE;
  2364. if (lRes == ERROR_SUCCESS)
  2365. _Module.m_bService = TRUE;
  2366. _Module.Start();
  2367. // When we get here, the service has been stopped
  2368. return _Module.m_status.dwWin32ExitCode;
  2369. }
  2370. DWORD
  2371. RestartFromSystemRestore()
  2372. {
  2373. DWORD dwStatus = ERROR_SUCCESS;
  2374. if( TSIsMachineInSystemRestore() )
  2375. {
  2376. dwStatus = TSSystemRestoreResetValues();
  2377. }
  2378. return dwStatus;
  2379. }