Source code of Windows XP (NT5)
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.

2214 lines
66 KiB

  1. /*++
  2. Copyright (c) 1991 Microsoft Corporation
  3. Module Name:
  4. control.cxx
  5. Abstract:
  6. Contains code for setting up and maintaining the control interface
  7. and sending controls to services. Functions in this module:
  8. RControlService
  9. RI_ScSendTSMessage
  10. ScCreateControlInstance
  11. ScWaitForConnect
  12. ScSendControl
  13. ScInitTransactNamedPipe
  14. ScShutdownAllServices
  15. Author:
  16. Dan Lafferty (danl) 20-Mar-1991
  17. Environment:
  18. User Mode -Win32
  19. Revision History:
  20. 13-Mar-1999 jschwart
  21. Added per-account security on the SCM <--> service control pipe
  22. 07-Apr-1998 jschwart
  23. ScInitTransactNamedPipe: Check registry for a user-supplied named
  24. pipe timeout value before setting it to the default. With the old
  25. default (30000 ms), services could be double-started on a heavily
  26. loaded machine when the server would send to the client, the client's
  27. response would time out, and the server would assume it hadn't started.
  28. 10-Mar-1998 jschwart
  29. Added ScSendPnPMessage and code to ScSendControl to enable passing
  30. of PnP-related service controls to services. Got rid of flag added
  31. on 06-Aug-1997 since we can just check the passed-in OpCode instead
  32. 06-Aug-1997 jschwart
  33. SendControl: Added flag to tell SendControl if it is sending a
  34. shutdown message. If so, it uses WriteFile, since using
  35. TransactNamedPipe with a poorly behaved service (that doesn't send
  36. an ACK back to the SCM) otherwise hangs the SCM.
  37. ShutdownAllServices: Since SendControl now uses WriteFile (asynch
  38. write), added a case to the switch that checks to see if any services
  39. are still running. If so, it gives them 30 seconds to become
  40. STOP_PENDING before it gives up and shuts itself down.
  41. 05-Mar-1997 AnirudhS
  42. Eliminated limit of 100 pipe instances.
  43. 04-Mar-1997 AnirudhS
  44. Added PARAMCHANGE, NETBINDADD, etc. controls for Plug and Play.
  45. 28-May-1996 AnirudhS
  46. ScSendControl, ScWaitForConnect and ScCleanoutPipe: If we time out
  47. waiting for a named pipe operation to complete, cancel it before
  48. returning. Otherwise it trashes the stack if it does complete later.
  49. 21-Feb-1995 AnirudhS
  50. ScShutdownAllServices: Fixed logic to wait for services in pending
  51. stop state.
  52. 19-Oct-1993 Danl
  53. Initialize the Overlapped structures that are allocated on the stack.
  54. 20-Jul-1993 danl
  55. SendControl: If we get ERROR_PIPE_BUSY back from the transact call,
  56. then we need to clean out the pipe by reading it first - then do
  57. the transact.
  58. 29-Dec-1992 danl
  59. Simplified calculation of elapsed time. This removed complier
  60. warning about overflow in constant arithmetic.
  61. 06-Mar-1992 danl
  62. SendControl: Fixed heap trashing problem where it didn't allocate
  63. the 4 extra alignment bytes in the case where there are no arguments.
  64. The registry name path becomes an argument even if there are no
  65. other agruments. Therefore it requires alignment for any start cmd.
  66. 20-Feb-1992 danl
  67. Get Pipe Handle only after we know we have an active service & the
  68. image record is good.
  69. 20-Feb-1992 danl
  70. Only add 4 extra alignment bytes to control buffer when there
  71. are arguments to pass.
  72. 31-Oct-1991 danl
  73. Fixed the logic governing the behavior under various service state
  74. and control opcode conditions. Added State Table to description.
  75. This logic was taken directly from LM2.0.
  76. 03-Sept-1991 danl
  77. Fixed alignment problem when marshalling args in ScSendControl.
  78. The array of offsets needs to be 4 byte aligned after the Service
  79. Name.
  80. 20-Mar-1991 danl
  81. created
  82. --*/
  83. //
  84. // INCLUDES
  85. //
  86. #include "precomp.hxx"
  87. #include <stdlib.h> // wide character c runtimes.
  88. #include <tstr.h> // Unicode string macros
  89. #include <align.h> // ROUND_UP_POINTER macro
  90. #include <control.h>
  91. #include <scseclib.h> // ScCreateAndSetSD
  92. #include "depend.h" // ScDependentsStopped()
  93. #include "driver.h" // ScControlDriver()
  94. #include "sclib.h" // ScIsValidServiceName()
  95. #include "scsec.h" // ScStatusAccessCheck()
  96. #include <dbt.h> // PDEV_BROADCAST_HDR
  97. //
  98. // Constants
  99. //
  100. #define SC_DEFAULT_PIPE_TRANSACT_TIMEOUT 30000 // 30 sec
  101. #define SC_PIPE_CLEANOUT_TIMEOUT 30 // 30 msec
  102. //
  103. // Registry key and value for the pipe timeout value
  104. //
  105. #define REGKEY_PIPE_TIMEOUT L"System\\CurrentControlSet\\Control"
  106. #define REGVAL_PIPE_TIMEOUT L"ServicesPipeTimeout"
  107. //
  108. // Registry key, value, and constant for the shutdown performance metric
  109. //
  110. // #define SC_SHUTDOWN_METRIC
  111. #ifdef SC_SHUTDOWN_METRIC
  112. #define REGKEY_SHUTDOWN_TIMEOUT L"System\\CurrentControlSet\\Control"
  113. #define REGVAL_SHUTDOWN_TIMEOUT L"ShutdownTimeout"
  114. #endif // SC_SHUTDOWN_METRIC
  115. //
  116. // STATIC DATA
  117. //
  118. /* static */ CRITICAL_SECTION ScTransactNPCriticalSection;
  119. //
  120. // Globals
  121. //
  122. DWORD g_dwScPipeTransactTimeout = SC_DEFAULT_PIPE_TRANSACT_TIMEOUT;
  123. //
  124. // Local Structure/Function Prototypes
  125. //
  126. typedef struct
  127. {
  128. LPWSTR lpServiceName;
  129. LPWSTR lpDisplayName;
  130. HANDLE hPipe;
  131. }
  132. TS_CONTROL_INFO, *PTS_CONTROL_INFO, *LPTS_CONTROL_INFO;
  133. VOID
  134. ScCleanOutPipe(
  135. HANDLE PipeHandle
  136. );
  137. /****************************************************************************/
  138. DWORD
  139. RControlService (
  140. IN SC_RPC_HANDLE hService,
  141. IN DWORD OpCode,
  142. OUT LPSERVICE_STATUS lpServiceStatus
  143. )
  144. /*++
  145. Routine Description:
  146. RPC entry point for the RServiceControl API function.
  147. The following state table describes what is to happen under various
  148. state/Opcode conditions:
  149. [OpCode]
  150. STOP INTERROGATE OTHER
  151. [Current State] _____________________________________
  152. | | | |
  153. STOPPED | (c) | (c) | (c) |
  154. | | | |
  155. STOP_PENDING | (b) | (b) | (b) |
  156. | | | |
  157. START_PEND | (a) | (d) | (b) |
  158. | | | |
  159. RUNNING | (a) | (a) | (a) |
  160. | | | |
  161. CONTINUE_PEND | (a) | (a) | (a) |
  162. | | | |
  163. PAUSE_PENDING | (a) | (a) | (a) |
  164. | | | |
  165. PAUSED | (a) | (a) | (a) |
  166. |___________|____________|____________|
  167. (a) Send control code to the service if the service is set up
  168. to receive this type of opcode. If it is not set up to
  169. receive the opcode, return ERROR_INVALID_SERVICE_CONTROL.
  170. An example of this would be the case of sending a PAUSE to a
  171. service that is listed as NOT_PAUSABLE.
  172. (b) Do NOT send control code to the service. Instead return
  173. ERROR_SERVICE_CANNOT_ACCEPT_CTRL.
  174. (c) Do NOT send control code to the service. Instead, return
  175. ERROR_SERVICE_NOT_ACTIVE.
  176. (d) Do NOT send control code to the service. Instead, return
  177. the last known state of the service with a SUCCESS status.
  178. NOTE -- this case (and this case only) differs from the
  179. SDK doc, which hides the fact that you can interrogate a
  180. service that's in the START_PENDING state
  181. Arguments:
  182. hService - This is a handle to the service. It is actually a pointer
  183. to a service handle structure.
  184. OpCode - The control request code.
  185. lpServiceStatus - pointer to a location where the service status is to
  186. be returned. If this pointer is invalid, it will be set to NULL
  187. upon return.
  188. Return Value:
  189. The returned lpServiceStatus structure is valid as long as the returned
  190. status is NO_ERROR.
  191. NO_ERROR - The operation was successful.
  192. ERROR_INVALID_HANDLE - The handle passed in was not a valid hService
  193. handle.
  194. NERR_InternalError - LocalAlloc or TransactNamedPipe failed, or
  195. TransactNamedPipe returned fewer bytes than expected.
  196. ERROR_SERVICE_REQUEST_TIMEOUT - The service did not respond with a status
  197. message within the fixed timeout limit (RESPONSE_WAIT_TIMEOUT).
  198. NERR_ServiceKillProc - The service process had to be killed because
  199. it wouldn't terminate when requested.
  200. ERROR_SERVICE_CANNOT_ACCEPT_CTRL - The service cannot accept control
  201. messages at this time.
  202. ERROR_INVALID_SERVICE_CONTROL - The request is not valid for this service.
  203. For instance, a PAUSE request is not valid for a service that
  204. lists itself as NOT_PAUSABLE.
  205. ERROR_INVALID_PARAMETER - The requested control is not valid.
  206. ERROR_ACCESS_DENIED - This is a status response from the service
  207. security check.
  208. Note:
  209. Because there are multiple services in a process, we cannot simply
  210. kill the process if the service does not respond to a terminate
  211. request. This situation is handled by first checking to see if
  212. this is the last service in the process. If it is, then it is
  213. removed from the installed database, and the process is terminated.
  214. If it isn't the last service, then we indicate timeout and do
  215. nothing.
  216. --*/
  217. {
  218. DWORD status = NO_ERROR;
  219. LPSERVICE_RECORD serviceRecord;
  220. DWORD currentState;
  221. DWORD controlsAccepted;
  222. DWORD controlsAcceptedMask = 0;
  223. HANDLE pipeHandle = NULL;
  224. LPWSTR serviceName;
  225. LPWSTR displayName;
  226. ACCESS_MASK desiredAccess;
  227. if (ScShutdownInProgress)
  228. {
  229. return(ERROR_SHUTDOWN_IN_PROGRESS);
  230. }
  231. //
  232. // Check the handle.
  233. //
  234. if (!ScIsValidServiceHandle(hService))
  235. {
  236. return ERROR_INVALID_HANDLE;
  237. }
  238. #ifdef SC_DEBUG
  239. //****************************************************************************
  240. if (OpCode == 5555)
  241. {
  242. ScShutdownNotificationRoutine(CTRL_SHUTDOWN_EVENT);
  243. }
  244. //****************************************************************************
  245. #endif // SC_DEBUG
  246. //
  247. // Set the desired access based on the control requested.
  248. // Figure out which "controls accepted" bits must be set for the
  249. // service to accept the control.
  250. //
  251. switch (OpCode) {
  252. case SERVICE_CONTROL_STOP:
  253. desiredAccess = SERVICE_STOP;
  254. controlsAcceptedMask = SERVICE_ACCEPT_STOP;
  255. break;
  256. case SERVICE_CONTROL_PAUSE:
  257. case SERVICE_CONTROL_CONTINUE:
  258. desiredAccess = SERVICE_PAUSE_CONTINUE;
  259. controlsAcceptedMask = SERVICE_ACCEPT_PAUSE_CONTINUE;
  260. break;
  261. case SERVICE_CONTROL_INTERROGATE:
  262. desiredAccess = SERVICE_INTERROGATE;
  263. break;
  264. case SERVICE_CONTROL_PARAMCHANGE:
  265. desiredAccess = SERVICE_PAUSE_CONTINUE;
  266. controlsAcceptedMask = SERVICE_ACCEPT_PARAMCHANGE;
  267. break;
  268. case SERVICE_CONTROL_NETBINDADD:
  269. case SERVICE_CONTROL_NETBINDREMOVE:
  270. case SERVICE_CONTROL_NETBINDENABLE:
  271. case SERVICE_CONTROL_NETBINDDISABLE:
  272. desiredAccess = SERVICE_PAUSE_CONTINUE;
  273. controlsAcceptedMask = SERVICE_ACCEPT_NETBINDCHANGE;
  274. break;
  275. default:
  276. if ((OpCode >= OEM_LOWER_LIMIT) &&
  277. (OpCode <= OEM_UPPER_LIMIT)) {
  278. desiredAccess = SERVICE_USER_DEFINED_CONTROL;
  279. }
  280. else {
  281. return ERROR_INVALID_PARAMETER;
  282. }
  283. }
  284. //
  285. // Was the handle opened with desired control access?
  286. //
  287. if (! RtlAreAllAccessesGranted(
  288. ((LPSC_HANDLE_STRUCT)hService)->AccessGranted,
  289. desiredAccess
  290. )) {
  291. return(ERROR_ACCESS_DENIED);
  292. }
  293. serviceRecord =
  294. ((LPSC_HANDLE_STRUCT)hService)->Type.ScServiceObject.ServiceRecord;
  295. //
  296. // If this control is for a driver, call ScControlDriver and return.
  297. //
  298. if (serviceRecord->ServiceStatus.dwServiceType & SERVICE_DRIVER) {
  299. return(ScControlDriver(OpCode, serviceRecord, lpServiceStatus));
  300. }
  301. //
  302. // Obtain a shared lock on the database - read the data we need,
  303. // Then free the lock.
  304. //
  305. {
  306. CServiceRecordSharedLock RLock;
  307. //
  308. // Once we get to this point, copy in the last known
  309. // status to return to the caller (Bug #188874)
  310. //
  311. RtlCopyMemory(lpServiceStatus,
  312. &(serviceRecord->ServiceStatus),
  313. sizeof(SERVICE_STATUS));
  314. currentState = serviceRecord->ServiceStatus.dwCurrentState;
  315. controlsAccepted = serviceRecord->ServiceStatus.dwControlsAccepted;
  316. serviceName = serviceRecord->ServiceName;
  317. displayName = serviceRecord->DisplayName;
  318. //
  319. // If we can obtain a pipe handle, do so. Otherwise, return an error.
  320. // (but first release the lock).
  321. //
  322. if ((currentState != SERVICE_STOPPED) &&
  323. (serviceRecord->ImageRecord != NULL)) {
  324. pipeHandle = serviceRecord->ImageRecord->PipeHandle;
  325. }
  326. else {
  327. status = ERROR_SERVICE_NOT_ACTIVE;
  328. }
  329. }
  330. if (status != NO_ERROR) {
  331. return(status);
  332. }
  333. //
  334. // The control is not sent to the service if the service is in
  335. // either the STOP_PENDING or START_PENDING state EXCEPT - we
  336. // allow STOP controls to a service that is START_PENDING.
  337. //
  338. // If we decide not to allow the control to be sent, we either
  339. // return current info (INTERROGATE) or an error (any other opcode).
  340. //
  341. if (currentState == SERVICE_STOP_PENDING) {
  342. return(ERROR_SERVICE_CANNOT_ACCEPT_CTRL);
  343. }
  344. else if (currentState == SERVICE_START_PENDING) {
  345. switch(OpCode) {
  346. case SERVICE_CONTROL_INTERROGATE:
  347. //
  348. // Just return the last known status. This behavior is unpublished.
  349. //
  350. return(NO_ERROR);
  351. case SERVICE_CONTROL_STOP:
  352. break;
  353. default:
  354. return(ERROR_SERVICE_CANNOT_ACCEPT_CTRL);
  355. }
  356. }
  357. //
  358. // Check if the service accepts the control.
  359. //
  360. if ( (controlsAccepted & controlsAcceptedMask) != controlsAcceptedMask ) {
  361. return(ERROR_INVALID_SERVICE_CONTROL);
  362. }
  363. //
  364. // Check for dependent services still running
  365. //
  366. BOOL fLastService = FALSE;
  367. if (OpCode == SERVICE_CONTROL_STOP) {
  368. CServiceRecordSharedLock RLock;
  369. if (! ScDependentsStopped(serviceRecord)) {
  370. return(ERROR_DEPENDENT_SERVICES_RUNNING);
  371. }
  372. if (serviceRecord->ImageRecord != NULL &&
  373. serviceRecord->ImageRecord->ServiceCount == 1) {
  374. fLastService = TRUE;
  375. }
  376. }
  377. //
  378. // Send the control request to the target service
  379. //
  380. status = ScSendControl(serviceName, // ServiceName
  381. displayName, // DisplayName
  382. pipeHandle, // pipeHandle
  383. OpCode, // Opcode
  384. NULL, // CmdArgs (vector ptr)
  385. 0L, // NumArgs
  386. NULL); // Ignore handler return value
  387. if (status == NO_ERROR) {
  388. //
  389. // If no errors occured, copy the latest status into the return
  390. // buffer. The shared lock is required for this.
  391. //
  392. CServiceRecordSharedLock RLock;
  393. RtlCopyMemory(lpServiceStatus,
  394. &(serviceRecord->ServiceStatus),
  395. sizeof(SERVICE_STATUS));
  396. }
  397. else {
  398. SC_LOG2(ERROR,"RControlService:SendControl to %ws service failed %ld\n",
  399. serviceRecord->ServiceName, status);
  400. if (OpCode == SERVICE_CONTROL_STOP) {
  401. //
  402. // If sending the control failed, and the control was a request
  403. // to stop, and if this service is the only running service in
  404. // the process, we can force the process to stop. ScRemoveService
  405. // will handle this if the ServiceCount is one.
  406. //
  407. if (fLastService) {
  408. SC_LOG0(TRACE,"RControlService:Forcing Service Shutdown\n");
  409. ScRemoveService(serviceRecord);
  410. }
  411. }
  412. }
  413. return(status);
  414. }
  415. /****************************************************************************/
  416. DWORD
  417. ScCreateControlInstance (
  418. OUT LPHANDLE PipeHandlePtr,
  419. IN DWORD dwCurrentService,
  420. IN PSID pAccountSid
  421. )
  422. /*++
  423. Routine Description:
  424. This function creates an instance of the control pipe
  425. Arguments:
  426. PipeHandlePtr - This is a pointer to a location where the pipe handle
  427. is to be placed upon return.
  428. dwCurrentService - This is used to create a uniquely-named pipe
  429. pAccountSid - The SID of the account that is allowed to access this pipe
  430. Return Value:
  431. NO_ERROR - The operation was successful.
  432. other - Any error returned by CreateNamedPipe could be returned.
  433. --*/
  434. {
  435. DWORD status;
  436. NTSTATUS ntstatus;
  437. SECURITY_ATTRIBUTES SecurityAttr;
  438. PSECURITY_DESCRIPTOR SecurityDescriptor;
  439. WCHAR wszPipeName[sizeof(CONTROL_PIPE_NAME) / sizeof(WCHAR) + PID_LEN] = CONTROL_PIPE_NAME;
  440. SC_ACE_DATA AceData[1] = {
  441. {ACCESS_ALLOWED_ACE_TYPE, 0, 0,
  442. GENERIC_ALL, &pAccountSid}
  443. };
  444. //
  445. // Generate the pipe name
  446. //
  447. _itow(dwCurrentService, wszPipeName + sizeof(CONTROL_PIPE_NAME) / sizeof(WCHAR) - 1, 10);
  448. //
  449. // Create a security descriptor for the control named pipe so
  450. // that we can grant access to it solely to the service's account
  451. //
  452. ntstatus = ScCreateAndSetSD(
  453. AceData,
  454. 1,
  455. LocalSystemSid,
  456. LocalSystemSid,
  457. &SecurityDescriptor
  458. );
  459. if (! NT_SUCCESS(ntstatus)) {
  460. SC_LOG1(ERROR, "ScCreateAndSetSD failed " FORMAT_NTSTATUS
  461. "\n", ntstatus);
  462. return (RtlNtStatusToDosError(ntstatus));
  463. }
  464. SecurityAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  465. SecurityAttr.lpSecurityDescriptor = SecurityDescriptor;
  466. SecurityAttr.bInheritHandle = FALSE;
  467. //
  468. // Create the service controller's end of the named pipe that will
  469. // be used for communicating control requests to the service process.
  470. // Use FILE_FLAG_FIRST_PIPE_INSTANCE to make sure that we're the
  471. // creator of the named pipe (vs. a malicious process that creates
  472. // the pipe first and thereby gains access to the client service
  473. // that connects to it).
  474. //
  475. *PipeHandlePtr = CreateNamedPipe (
  476. wszPipeName,
  477. PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
  478. PIPE_WAIT | PIPE_READMODE_MESSAGE | PIPE_TYPE_MESSAGE,
  479. 1, // one instance per process
  480. 8000,
  481. sizeof(PIPE_RESPONSE_MSG),
  482. CONTROL_TIMEOUT, // Default Timeout
  483. &SecurityAttr); // Security Descriptor
  484. status = NO_ERROR;
  485. if (*PipeHandlePtr == INVALID_HANDLE_VALUE) {
  486. status = GetLastError();
  487. SC_LOG1(ERROR,
  488. "CreateControlInstance: CreateNamedPipe failed, %ld\n",status);
  489. }
  490. (void) RtlDeleteSecurityObject(&SecurityDescriptor);
  491. return(status);
  492. }
  493. /****************************************************************************/
  494. DWORD
  495. ScWaitForConnect (
  496. IN HANDLE PipeHandle,
  497. IN HANDLE hProcess OPTIONAL,
  498. IN LPWSTR lpDisplayName,
  499. OUT LPDWORD ProcessIdPtr
  500. )
  501. /*++
  502. Routine Description:
  503. This function waits until a connection is made to the pipe handle.
  504. It then waits for the first status message to be sent from the
  505. service process.
  506. The first message from the service contains the processId. This
  507. helps to verify that we are talking to the correct process.
  508. Arguments:
  509. PipeHandle - This is the handle to the pipe instance that is waiting
  510. for a connect.
  511. hProcess - The handle to the service process. We wait on this handle
  512. and the pipe handle in case the process exits before the
  513. pipe transaction times out.
  514. lpDisplayName - The name of the service for which we're waiting.
  515. ProcessIdPtr - This is a pointer to the location where the processId is
  516. to be stored.
  517. Return Value:
  518. NO_ERROR - The pipe is in the connected state.
  519. any error that ReadFile can produce may be returned.
  520. Note:
  521. The ConnectNamedPipe called is done asynchronously and we wait
  522. on its completion using the pipe handle. This can only work
  523. correctly when it is guaranteed that no other IO is issued
  524. while we are waiting on the pipe handle (except for the service
  525. itself to connect to the pipe with call to CreateFile).
  526. --*/
  527. {
  528. PIPE_RESPONSE_MSG serviceResponseBuffer;
  529. DWORD numBytesRead;
  530. BOOL status;
  531. DWORD apiStatus;
  532. OVERLAPPED overlapped={0,0,0,0,0};// overlapped structure to implement
  533. // timeout on TransactNamedPipe
  534. CONST HANDLE phHandles[] = { PipeHandle, hProcess };
  535. DWORD dwCount = (hProcess == NULL ? 1 : 2);
  536. #if DBG
  537. DWORD dwStartTick;
  538. DWORD dwTotalTime;
  539. #endif // DBG
  540. SC_LOG(TRACE,"ServiceController waiting for pipe connect\n",0);
  541. overlapped.hEvent = (HANDLE) NULL; // Wait on pipe handle
  542. //
  543. // Wait for the service to connect.
  544. //
  545. status = ConnectNamedPipe(PipeHandle, &overlapped);
  546. if (status == FALSE) {
  547. apiStatus = GetLastError();
  548. if (apiStatus == ERROR_IO_PENDING) {
  549. #if DBG
  550. dwStartTick = GetTickCount();
  551. #endif // DBG
  552. //
  553. // Connection is pending
  554. //
  555. apiStatus = WaitForMultipleObjects(dwCount,
  556. phHandles,
  557. FALSE, // Wait for any
  558. g_dwScPipeTransactTimeout);
  559. #if DBG
  560. dwTotalTime = GetTickCount() - dwStartTick;
  561. if (dwTotalTime > SC_DEFAULT_PIPE_TRANSACT_TIMEOUT) {
  562. SC_LOG1(ERROR,
  563. "ScWaitForConnect: Wait on ConnectNamedPipe took %u milliseconds\n",
  564. dwTotalTime);
  565. }
  566. #endif // DBG
  567. if (apiStatus == WAIT_OBJECT_0) {
  568. //
  569. // Wait completed successfully -- the object that
  570. // signalled was the pipe handle
  571. //
  572. status = GetOverlappedResult(
  573. PipeHandle,
  574. &overlapped,
  575. &numBytesRead,
  576. TRUE
  577. );
  578. if (status == FALSE) {
  579. apiStatus = GetLastError();
  580. SC_LOG(ERROR,
  581. "ScWaitForConnect: GetOverlappedResult failed, rc=%lu\n",
  582. apiStatus);
  583. return apiStatus;
  584. }
  585. }
  586. else {
  587. //
  588. // Either the connection timed out or the service process
  589. // exited before calling StartServiceCtrlDispatcher
  590. //
  591. SC_LOG2(ERROR,
  592. "ScWaitForConnect: Wait for connection for %u secs timed out --"
  593. "service process DID %s exit\n",
  594. g_dwScPipeTransactTimeout / 1000,
  595. (apiStatus == WAIT_TIMEOUT ? "NOT" : ""));
  596. //
  597. // The service didn't respond. Cancel the named pipe operation.
  598. //
  599. status = CancelIo(PipeHandle);
  600. if (status == FALSE) {
  601. SC_LOG(ERROR, "ScWaitForConnect: CancelIo failed, %lu\n", GetLastError());
  602. }
  603. ScLogEvent(
  604. NEVENT_CONNECTION_TIMEOUT,
  605. g_dwScPipeTransactTimeout,
  606. lpDisplayName
  607. );
  608. return ERROR_SERVICE_REQUEST_TIMEOUT;
  609. }
  610. }
  611. else if (apiStatus != ERROR_PIPE_CONNECTED) {
  612. SC_LOG(ERROR,"ScWaitForConnect: ConnectNamedPipe failed, rc=%lu\n",
  613. apiStatus);
  614. return apiStatus;
  615. }
  616. //
  617. // If we received the ERROR_PIPE_CONNECTED status, then things
  618. // are still ok.
  619. //
  620. }
  621. SC_LOG(TRACE,"WaitForConnect:ConnectNamedPipe Success\n",0);
  622. //
  623. // Wait for initial status message
  624. //
  625. overlapped.hEvent = (HANDLE) NULL; // Wait on pipe handle
  626. status = ReadFile (PipeHandle,
  627. (LPVOID)&serviceResponseBuffer,
  628. sizeof(serviceResponseBuffer),
  629. &numBytesRead,
  630. &overlapped);
  631. if (status == FALSE) {
  632. apiStatus = GetLastError();
  633. if (apiStatus == ERROR_IO_PENDING) {
  634. #if DBG
  635. dwStartTick = GetTickCount();
  636. #endif // DBG
  637. //
  638. // Connection is pending
  639. //
  640. apiStatus = WaitForSingleObject(PipeHandle, g_dwScPipeTransactTimeout);
  641. #if DBG
  642. dwTotalTime = GetTickCount() - dwStartTick;
  643. if (dwTotalTime > SC_DEFAULT_PIPE_TRANSACT_TIMEOUT) {
  644. SC_LOG1(ERROR,
  645. "ScWaitForConnect: Wait on ReadFile took %u milliseconds\n",
  646. dwTotalTime);
  647. }
  648. #endif // DBG
  649. if (apiStatus == WAIT_TIMEOUT) {
  650. SC_LOG(ERROR,
  651. "ScWaitForConnect: Wait for ReadFile for %u secs timed out\n",
  652. g_dwScPipeTransactTimeout / 1000 );
  653. //
  654. // Cancel the named pipe operation.
  655. //
  656. status = CancelIo(PipeHandle);
  657. if (status == FALSE) {
  658. SC_LOG(ERROR, "ScWaitForConnect: CancelIo failed, %lu\n", GetLastError());
  659. }
  660. ScLogEvent(
  661. NEVENT_READFILE_TIMEOUT,
  662. g_dwScPipeTransactTimeout
  663. );
  664. return ERROR_SERVICE_REQUEST_TIMEOUT;
  665. } else if (apiStatus == 0) {
  666. //
  667. // Wait completed successfully
  668. //
  669. status = GetOverlappedResult(PipeHandle,
  670. &overlapped,
  671. &numBytesRead,
  672. TRUE);
  673. if (status == FALSE) {
  674. apiStatus = GetLastError();
  675. SC_LOG(ERROR,
  676. "ScWaitForConnect: GetOverlappedResult for ReadFile failed, rc=%lu\n",
  677. apiStatus);
  678. return apiStatus;
  679. }
  680. }
  681. }
  682. else {
  683. SC_LOG(ERROR,"ScWaitForConnect: ReadFile failed, rc=%lu\n",
  684. apiStatus);
  685. return apiStatus;
  686. }
  687. }
  688. SC_LOG0(TRACE,"WaitForConnect:ReadFile success\n");
  689. SC_LOG(
  690. TRACE,
  691. "WaitForConnect:ReadFile buffer size = %ld\n",
  692. sizeof(serviceResponseBuffer));
  693. SC_LOG(
  694. TRACE,
  695. "WaitForConnect:ReadFile numBytesRead = %ld\n",
  696. numBytesRead);
  697. *ProcessIdPtr = serviceResponseBuffer.dwDispatcherStatus;
  698. return(NO_ERROR);
  699. }
  700. /****************************************************************************/
  701. DWORD
  702. ScValidatePnPService(
  703. IN LPWSTR lpServiceName,
  704. OUT SERVICE_STATUS_HANDLE *lphServiceStatus
  705. )
  706. {
  707. DWORD dwError;
  708. LPSERVICE_RECORD lpServiceRecord;
  709. //
  710. // Make sure PnP is supplying a valid OUT parameter
  711. //
  712. SC_ASSERT(lphServiceStatus != NULL);
  713. //
  714. // Validate the format of the service name.
  715. //
  716. if (! ScIsValidServiceName(lpServiceName))
  717. {
  718. return ERROR_INVALID_NAME;
  719. }
  720. //
  721. // Find the service record in the database.
  722. //
  723. CServiceListSharedLock LLock;
  724. dwError = ScGetNamedServiceRecord(lpServiceName,
  725. &lpServiceRecord);
  726. if (dwError != NO_ERROR)
  727. {
  728. return(dwError);
  729. }
  730. CServiceRecordSharedLock RLock;
  731. //
  732. // Make sure the service specified is the service
  733. // that requested device notification
  734. //
  735. dwError = ScStatusAccessCheck(lpServiceRecord);
  736. if (dwError == NO_ERROR)
  737. {
  738. *lphServiceStatus = (SERVICE_STATUS_HANDLE)lpServiceRecord;
  739. }
  740. return dwError;
  741. }
  742. DWORD
  743. ScSendPnPMessage(
  744. IN SERVICE_STATUS_HANDLE hServiceStatus,
  745. IN DWORD OpCode,
  746. IN DWORD dwEventType,
  747. IN LPARAM EventData,
  748. OUT LPDWORD lpdwHandlerRetVal
  749. )
  750. /*++
  751. Routine Description:
  752. This function is called by PnP when it needs to send a control to a
  753. service that has requested notification. It simply packs the args and
  754. calls ScSendControl.
  755. Arguments:
  756. OpCode - This is the opcode that is to be passed to the service.
  757. dwEventType - The PnP event that has occurred
  758. EventData - Pointer to other information the service may want
  759. Return Value:
  760. ERROR_SERVICE_NOT_ACTIVE - The named service has no image record
  761. In addition, any value passed back from ScGetNamedImageRecord or ScSendControl
  762. --*/
  763. {
  764. LPSERVICE_RECORD lpServiceRecord;
  765. CONTROL_ARGS ControlArgs;
  766. LPWSTR lpServiceName;
  767. LPWSTR lpDisplayName;
  768. HANDLE hPipe;
  769. //
  770. // Make sure this handle is valid (in case the service in question
  771. // was deleted and was signed up for device notifications)
  772. //
  773. // BUGBUG -- We should call a PnP callback and have it free up the
  774. // node for the service in question if it's deleted
  775. //
  776. SC_ASSERT(((LPSERVICE_RECORD) hServiceStatus)->Signature == SERVICE_SIGNATURE);
  777. //
  778. // Make sure PnP is giving us a valid OUT parameter
  779. //
  780. SC_ASSERT(lpdwHandlerRetVal != NULL);
  781. lpServiceRecord = (LPSERVICE_RECORD)hServiceStatus;
  782. {
  783. //
  784. // Get the information we need then release the lock
  785. //
  786. CServiceRecordSharedLock RLock;
  787. if (lpServiceRecord->ImageRecord == NULL)
  788. {
  789. return ERROR_SERVICE_NOT_ACTIVE;
  790. }
  791. lpServiceName = lpServiceRecord->ServiceName;
  792. lpDisplayName = lpServiceRecord->DisplayName;
  793. hPipe = lpServiceRecord->ImageRecord->PipeHandle;
  794. }
  795. //
  796. // If it's a PnP device event, pass along the arguments for the named pipe
  797. //
  798. switch (OpCode) {
  799. case SERVICE_CONTROL_DEVICEEVENT:
  800. //
  801. // Make sure that either both the size and buffer are
  802. // 0 and NULL or that they're non-zero and non-NULL
  803. //
  804. SC_ASSERT(((PDEV_BROADCAST_HDR)EventData)->dbch_size && EventData ||
  805. !((PDEV_BROADCAST_HDR)EventData)->dbch_size && !EventData);
  806. ControlArgs.PnPArgs.dwEventType = dwEventType;
  807. ControlArgs.PnPArgs.dwEventDataSize = ((PDEV_BROADCAST_HDR)EventData)->dbch_size;
  808. ControlArgs.PnPArgs.EventData = (VOID *)EventData;
  809. break;
  810. case SERVICE_CONTROL_POWEREVENT:
  811. case SERVICE_CONTROL_HARDWAREPROFILECHANGE:
  812. //
  813. // Hardware Profile Change and Power messages have no LPARAM.
  814. // They just tell a service that something noteworthy has happened.
  815. //
  816. SC_ASSERT(EventData == NULL);
  817. ControlArgs.PnPArgs.dwEventType = dwEventType;
  818. ControlArgs.PnPArgs.dwEventDataSize = 0;
  819. ControlArgs.PnPArgs.EventData = NULL;
  820. break;
  821. default:
  822. SC_ASSERT(FALSE);
  823. break;
  824. }
  825. return ScSendControl(lpServiceName,
  826. lpDisplayName,
  827. hPipe,
  828. OpCode,
  829. &ControlArgs,
  830. 3, // 3 PnP arguments
  831. lpdwHandlerRetVal);
  832. }
  833. DWORD
  834. RI_ScSendTSMessage (
  835. IN SC_RPC_HANDLE hSCManager,
  836. IN DWORD OpCode,
  837. IN DWORD dwEvent,
  838. IN DWORD cbData,
  839. IN LPBYTE lpData
  840. )
  841. {
  842. LPSERVICE_RECORD lpServiceRecord;
  843. CONTROL_ARGS ControlArgs;
  844. DWORD dwAcceptedMask;
  845. DWORD dwError;
  846. DWORD dwNumServices = 0;
  847. DWORD i;
  848. LPTS_CONTROL_INFO lpControlInfo;
  849. lpServiceRecord = NULL;
  850. ControlArgs.PnPArgs.dwEventType = dwEvent;
  851. ControlArgs.PnPArgs.dwEventDataSize = cbData;
  852. ControlArgs.PnPArgs.EventData = lpData;
  853. if (OpCode != SERVICE_CONTROL_SESSIONCHANGE)
  854. {
  855. ASSERT(OpCode == SERVICE_CONTROL_SESSIONCHANGE);
  856. return ERROR_INVALID_PARAMETER;
  857. }
  858. dwAcceptedMask = SERVICE_ACCEPT_SESSIONCHANGE;
  859. //
  860. // Make sure that the caller is LocalSystem
  861. //
  862. dwError = ScStatusAccessCheck(NULL);
  863. if (dwError != NO_ERROR)
  864. {
  865. SC_LOG1(ERROR,
  866. "RI_ScSendTSMessage: ScStatusAccessCheck failed %d\n",
  867. dwError);
  868. return dwError;
  869. }
  870. {
  871. CServiceListSharedLock LLock;
  872. CServiceRecordExclusiveLock RLock;
  873. //
  874. // Go through the list and copy out the pointer to the service name and
  875. // the pipe handle for each service that wants to receive this control.
  876. // We do this so we can call ScSendControl for each service afterwards
  877. // without holding the locks required to traverse the list. Note that
  878. // it's conceivable that the service name will be junk by the time
  879. // ScSendControl is called (if the service is deleted before the call)
  880. // but if that's the case, the pipe handle will be invalid, causing the
  881. // call to fail gracefully.
  882. //
  883. FOR_SERVICES_THAT(lpServiceRecord,
  884. (lpServiceRecord->ServiceStatus.dwServiceType & SERVICE_WIN32) &&
  885. (lpServiceRecord->ServiceStatus.dwCurrentState != SERVICE_STOPPED) &&
  886. (lpServiceRecord->ServiceStatus.dwCurrentState != SERVICE_STOP_PENDING) &&
  887. (lpServiceRecord->ServiceStatus.dwControlsAccepted & dwAcceptedMask) &&
  888. (lpServiceRecord->ImageRecord != NULL)
  889. )
  890. {
  891. dwNumServices++;
  892. }
  893. if (dwNumServices == 0)
  894. {
  895. //
  896. // No services accept the control
  897. //
  898. return NO_ERROR;
  899. }
  900. lpControlInfo = (LPTS_CONTROL_INFO) LocalAlloc(LMEM_FIXED,
  901. dwNumServices * sizeof(TS_CONTROL_INFO));
  902. if (lpControlInfo == NULL)
  903. {
  904. return ERROR_NOT_ENOUGH_MEMORY;
  905. }
  906. dwNumServices = 0;
  907. FOR_SERVICES_THAT(lpServiceRecord,
  908. (lpServiceRecord->ServiceStatus.dwServiceType & SERVICE_WIN32) &&
  909. (lpServiceRecord->ServiceStatus.dwCurrentState != SERVICE_STOPPED) &&
  910. (lpServiceRecord->ServiceStatus.dwCurrentState != SERVICE_STOP_PENDING) &&
  911. (lpServiceRecord->ServiceStatus.dwControlsAccepted & dwAcceptedMask) &&
  912. (lpServiceRecord->ImageRecord != NULL)
  913. )
  914. {
  915. //
  916. // Copy out the information we need
  917. //
  918. lpControlInfo[dwNumServices].lpServiceName = lpServiceRecord->ServiceName;
  919. lpControlInfo[dwNumServices].lpDisplayName = lpServiceRecord->DisplayName;
  920. lpControlInfo[dwNumServices].hPipe = lpServiceRecord->ImageRecord->PipeHandle;
  921. dwNumServices++;
  922. }
  923. }
  924. for (i = 0; i < dwNumServices; i++)
  925. {
  926. //
  927. // Send the control
  928. //
  929. dwError = ScSendControl(lpControlInfo[i].lpServiceName,
  930. lpControlInfo[i].lpDisplayName,
  931. lpControlInfo[i].hPipe,
  932. OpCode,
  933. &ControlArgs,
  934. 3,
  935. NULL);
  936. //
  937. // Ignore any errors sending the control
  938. //
  939. if (dwError != NO_ERROR)
  940. {
  941. SC_LOG2(ERROR,
  942. "RI_ScSendTSMessage: Error %d sending control to %ws service\n",
  943. dwError,
  944. lpControlInfo[i].lpServiceName);
  945. }
  946. }
  947. LocalFree(lpControlInfo);
  948. return NO_ERROR;
  949. }
  950. /****************************************************************************/
  951. DWORD
  952. ScSendControl(
  953. IN LPWSTR ServiceName,
  954. IN LPWSTR DisplayName,
  955. IN HANDLE PipeHandle,
  956. IN DWORD OpCode,
  957. IN LPCONTROL_ARGS lpControlArgs OPTIONAL,
  958. IN DWORD NumArgs,
  959. OUT LPDWORD lpdwHandlerRetVal OPTIONAL
  960. )
  961. /*++
  962. Routine Description:
  963. This function sends a control request to a service via a
  964. TransactNamedPipe call. A buffer is allocated for the transaction,
  965. and then freed when done.
  966. LOCKS:
  967. Normally locks are not held when this function is called. This is
  968. because we need to allow status messages to come in prior to the
  969. transact completing. The exception is when we send the message
  970. to the control dispatcher to shutdown. No status message is sent
  971. in response to that.
  972. There is a ScTransactNPCriticalSection that is held during the actual
  973. Transact.
  974. Arguments:
  975. ServiceName - This is a pointer to a NUL terminated service name string.
  976. PipeHandle - This is the pipe handle to which the request is directed.
  977. OpCode - This is the opcode that is to be passed to the service.
  978. lpControlArgs - This is an optional pointer to a CONTROL_ARGS union,
  979. which can contain either an array of pointers to NUL-terminated
  980. strings (for the SERVICE_CONTROL_START case) or a structure that
  981. holds Plug-and-Play arguments (for the SERVICE_CONTROL_DEVICEEVENT,
  982. SERVICE_CONTROL_POWEREVENT, SERVICE_CONTROL_HARDWAREPROFILECHANGE,
  983. and SERVICE_CONTROL_SESSIONCHANGE cases).
  984. NumArgs - This indicates how many arguments are in the structure
  985. lpControlArgs contains. For SERVICE_CONTROL_START, it's the number
  986. of strings in the argument array. For Plug-and-Play events, it's
  987. the number of arguments in a Plug-and-Play message (currently 3)
  988. lpdwHandlerRetVal - The return value from the Service's control handler
  989. Return Value:
  990. NO_ERROR - The operation was successful.
  991. ERROR_GEN_FAILURE - An incorrect number of bytes was received
  992. in the response message.
  993. ERROR_ACCESS_DENIED - This is a status response from the service
  994. security check by the Control Dispatcher on the other end of the
  995. pipe.
  996. ERROR_NOT_ENOUGH_MEMORY - Unable to allocate memory for the transaction
  997. buffer. (Local Alloc failed).
  998. other - Any error from TransactNamedPipe could be returned - Or any
  999. error from the Control Dispatcher on the other end of the pipe.
  1000. --*/
  1001. {
  1002. DWORD returnStatus = NO_ERROR;
  1003. LPCTRL_MSG_HEADER lpcmhBuffer; // Message buffer
  1004. DWORD serviceNameSize;
  1005. DWORD sendBufferSize;
  1006. BOOL status;
  1007. PIPE_RESPONSE_MSG serviceResponseBuffer;
  1008. DWORD bytesRead;
  1009. DWORD i;
  1010. static OVERLAPPED overlapped={0,0,0,0,0}; // overlapped structure to implement
  1011. // timeout on TransactNamedPipe
  1012. // static because on shutdown, we'll
  1013. // be firing off a bunch of async
  1014. // writes, which write to the overlapped
  1015. // structure upon completion, and we
  1016. // don't want them trashing the stack
  1017. if (ARGUMENT_PRESENT(lpdwHandlerRetVal))
  1018. {
  1019. //
  1020. // Initialize the OUT pointer
  1021. //
  1022. *lpdwHandlerRetVal = NO_ERROR;
  1023. }
  1024. serviceNameSize = (DWORD) WCSSIZE(ServiceName);
  1025. sendBufferSize = serviceNameSize + sizeof(CTRL_MSG_HEADER);
  1026. //
  1027. // Add an extra PVOID size to help settle alignment problems that
  1028. // may occur when the array of pointers follows the service name string.
  1029. //
  1030. sendBufferSize += sizeof(PVOID);
  1031. //
  1032. // There are control arguments, so add their size to the buffer size
  1033. //
  1034. if (lpControlArgs != NULL) {
  1035. if (OpCode == SERVICE_CONTROL_START_SHARE ||
  1036. OpCode == SERVICE_CONTROL_START_OWN) {
  1037. //
  1038. // Service is starting
  1039. //
  1040. for (i = 0; i < NumArgs; i++) {
  1041. sendBufferSize += (DWORD) WCSSIZE(lpControlArgs->CmdArgs[i]) +
  1042. sizeof(LPWSTR);
  1043. }
  1044. }
  1045. else {
  1046. SC_ASSERT(OpCode == SERVICE_CONTROL_DEVICEEVENT ||
  1047. OpCode == SERVICE_CONTROL_HARDWAREPROFILECHANGE ||
  1048. OpCode == SERVICE_CONTROL_POWEREVENT ||
  1049. OpCode == SERVICE_CONTROL_SESSIONCHANGE);
  1050. //
  1051. // PnP event
  1052. //
  1053. sendBufferSize += sizeof(lpControlArgs->PnPArgs.dwEventType);
  1054. sendBufferSize += sizeof(lpControlArgs->PnPArgs.dwEventDataSize);
  1055. sendBufferSize += lpControlArgs->PnPArgs.dwEventDataSize;
  1056. }
  1057. }
  1058. //
  1059. // Allocate the buffer and set a pointer to it that knows the structure
  1060. // of the header.
  1061. //
  1062. lpcmhBuffer = (LPCTRL_MSG_HEADER)LocalAlloc(LMEM_ZEROINIT, sendBufferSize);
  1063. if (lpcmhBuffer == NULL) {
  1064. SC_LOG(TRACE,"SendControl:LocalAlloc failed, rc=%d/n", GetLastError());
  1065. return (ERROR_NOT_ENOUGH_MEMORY);
  1066. }
  1067. /////////////////////////////////////////////////////////////////////
  1068. // Marshall the data into the buffer.
  1069. //
  1070. //
  1071. // The Control Message looks like this for service start:
  1072. // CTRL_MSG_HEADER Header
  1073. // WCHAR ServiceName[?]
  1074. // LPWSTR Argv0 offset
  1075. // LPWSTR Argv1 offset
  1076. // LPWSTR Argv2 offset
  1077. // LPWSTR ...
  1078. // WCHAR Argv0[?]
  1079. // WCHAR Argv1[?]
  1080. // WCHAR Argv2[?]
  1081. // WCHAR ...
  1082. //
  1083. // and like this for PNP events:
  1084. // CTRL_MSG_HEADER Header
  1085. // WCHAR ServiceName[?]
  1086. // DWORD wParam
  1087. // BYTE lParam[?]
  1088. //
  1089. lpcmhBuffer->OpCode = OpCode;
  1090. lpcmhBuffer->Count = sendBufferSize;
  1091. //
  1092. // Copy the service name to buffer and store the offset.
  1093. //
  1094. lpcmhBuffer->ServiceNameOffset = sizeof(CTRL_MSG_HEADER);
  1095. wcscpy((LPWSTR)(lpcmhBuffer + 1), ServiceName);
  1096. //
  1097. // Pack message-specific arguments as necessary
  1098. //
  1099. switch (OpCode) {
  1100. case SERVICE_CONTROL_START_SHARE:
  1101. case SERVICE_CONTROL_START_OWN:
  1102. if (NumArgs > 0) {
  1103. //
  1104. // Service start -- Determine the offset from the top of the argv
  1105. // array to the first argv string. Also determine the pointer value
  1106. // for that location.
  1107. //
  1108. DWORD dwOffset = NumArgs * sizeof(LPWSTR);
  1109. LPWSTR *ppwszArgs;
  1110. //
  1111. // Calculate the beginning of the string area and the beginning
  1112. // of the arg vector area. Align the vector pointer on a PVOID
  1113. // boundary.
  1114. //
  1115. ppwszArgs = (LPWSTR *)((LPBYTE)(lpcmhBuffer + 1) + serviceNameSize);
  1116. ppwszArgs = (LPWSTR *)ROUND_UP_POINTER(ppwszArgs, sizeof(PVOID));
  1117. lpcmhBuffer->ArgvOffset = (DWORD)((LPBYTE)ppwszArgs - (LPBYTE)lpcmhBuffer);
  1118. lpcmhBuffer->NumCmdArgs = NumArgs;
  1119. //
  1120. // Copy the command arg strings to the buffer and update the argv
  1121. // pointers with offsets. Remember - we already have one argument
  1122. // in there for the service registry path.
  1123. //
  1124. for (i = 0; i < NumArgs; i++) {
  1125. wcscpy((LPWSTR) ((LPBYTE)ppwszArgs + dwOffset),
  1126. lpControlArgs->CmdArgs[i]);
  1127. ppwszArgs[i] = (LPWSTR)(DWORD_PTR) dwOffset;
  1128. dwOffset += (DWORD) WCSSIZE(lpControlArgs->CmdArgs[i]);
  1129. }
  1130. }
  1131. break;
  1132. case SERVICE_CONTROL_DEVICEEVENT:
  1133. case SERVICE_CONTROL_HARDWAREPROFILECHANGE:
  1134. case SERVICE_CONTROL_POWEREVENT:
  1135. case SERVICE_CONTROL_SESSIONCHANGE:
  1136. {
  1137. LPDWORD lpdwArgLocation;
  1138. //
  1139. // Calculate the location for the PnP/power arguments.
  1140. // Align the pointer on a PVOID boundary.
  1141. //
  1142. lpdwArgLocation = (LPDWORD)((LPBYTE)(lpcmhBuffer + 1) + serviceNameSize);
  1143. lpdwArgLocation = (LPDWORD)ROUND_UP_POINTER(lpdwArgLocation, sizeof(PVOID));
  1144. lpcmhBuffer->ArgvOffset = (DWORD)((LPBYTE)lpdwArgLocation - (LPBYTE)lpcmhBuffer);
  1145. //
  1146. // Copy the wParam into the buffer
  1147. //
  1148. *lpdwArgLocation = lpControlArgs->PnPArgs.dwEventType;
  1149. //
  1150. // Copy the lParam into the buffer
  1151. //
  1152. RtlCopyMemory(lpdwArgLocation + 1,
  1153. lpControlArgs->PnPArgs.EventData,
  1154. lpControlArgs->PnPArgs.dwEventDataSize);
  1155. break;
  1156. }
  1157. }
  1158. // If the SCM is sending a shutdown message to a service, we want to just
  1159. // use WriteFile instead of TransactNamedPipe, since a badly behaved service
  1160. // that doesn't write back to the pipe leaves the SCM hanging and unable to
  1161. // properly shut down the remaining services
  1162. SC_LOG0(LOCKS,"SendControl: Entering TransactPipe Critical Section.\n");
  1163. EnterCriticalSection(&ScTransactNPCriticalSection);
  1164. if (OpCode == SERVICE_CONTROL_SHUTDOWN) {
  1165. SC_LOG0(SHUTDOWN,
  1166. "ScSendControl: Using WriteFile to send a service shutdown message.\n");
  1167. status = WriteFile(
  1168. PipeHandle,
  1169. lpcmhBuffer,
  1170. sendBufferSize,
  1171. &bytesRead,
  1172. &overlapped);
  1173. if (status || (returnStatus = GetLastError()) == ERROR_IO_PENDING) {
  1174. returnStatus = NO_ERROR;
  1175. }
  1176. SC_LOG(SHUTDOWN, "ScSendControl returning with code %d\n", returnStatus);
  1177. }
  1178. else {
  1179. //
  1180. // The parameters are marshalled, now send the buffer and wait for
  1181. // response.
  1182. //
  1183. SC_LOG(TRACE,"SendControl: Sending a TransactMessage.\n",0);
  1184. returnStatus = NO_ERROR;
  1185. status = TransactNamedPipe(PipeHandle,
  1186. lpcmhBuffer,
  1187. sendBufferSize,
  1188. &serviceResponseBuffer,
  1189. sizeof(PIPE_RESPONSE_MSG),
  1190. &bytesRead,
  1191. &overlapped);
  1192. if (status == FALSE) {
  1193. returnStatus = GetLastError();
  1194. if (returnStatus == ERROR_PIPE_BUSY) {
  1195. SC_LOG(ERROR, "Cleaning out pipe for %ws service\n", ServiceName);
  1196. ScCleanOutPipe(PipeHandle);
  1197. status = TRUE;
  1198. returnStatus = NO_ERROR;
  1199. status = TransactNamedPipe(PipeHandle,
  1200. lpcmhBuffer,
  1201. sendBufferSize,
  1202. &serviceResponseBuffer,
  1203. sizeof(PIPE_RESPONSE_MSG),
  1204. &bytesRead,
  1205. &overlapped);
  1206. if (status == FALSE) {
  1207. returnStatus = GetLastError();
  1208. }
  1209. }
  1210. }
  1211. if (status == FALSE) {
  1212. if (returnStatus != ERROR_IO_PENDING) {
  1213. SC_LOG2(ERROR,
  1214. "SendControl:TransactNamedPipe to %ws service failed, rc=%lu\n",
  1215. ServiceName,
  1216. returnStatus);
  1217. goto CleanUp;
  1218. } else {
  1219. #if DBG
  1220. DWORD dwStartTick = GetTickCount();
  1221. DWORD dwTotalTime;
  1222. #endif // DBG
  1223. //
  1224. // Transaction is pending
  1225. //
  1226. status = WaitForSingleObject(PipeHandle, g_dwScPipeTransactTimeout);
  1227. #if DBG
  1228. dwTotalTime = GetTickCount() - dwStartTick;
  1229. if (dwTotalTime > SC_DEFAULT_PIPE_TRANSACT_TIMEOUT) {
  1230. SC_LOG3(ERROR,
  1231. "ScSendControl: Pipe transaction to service %ws on "
  1232. "control %u took %u milliseconds\n",
  1233. ServiceName,
  1234. OpCode,
  1235. dwTotalTime);
  1236. }
  1237. #endif // DBG
  1238. if (status == WAIT_TIMEOUT) {
  1239. SC_LOG2(ERROR,
  1240. "SendControl: Wait on transact to %ws service for %u millisecs timed out\n",
  1241. ServiceName, g_dwScPipeTransactTimeout);
  1242. //
  1243. // Cancel the named pipe operation.
  1244. // NOTE: CancelIo cancels ALL pending I/O operations issued by
  1245. // this thread on the PipeHandle. Since the service controller
  1246. // functions do nothing but wait after starting asynchronous
  1247. // named pipe operations, there should be no other operations.
  1248. //
  1249. status = CancelIo(PipeHandle);
  1250. if (status == FALSE) {
  1251. SC_LOG(ERROR, "SendControl: CancelIo failed, %lu\n", GetLastError());
  1252. }
  1253. ScLogEvent(
  1254. NEVENT_TRANSACT_TIMEOUT,
  1255. g_dwScPipeTransactTimeout,
  1256. ServiceName
  1257. );
  1258. returnStatus = ERROR_SERVICE_REQUEST_TIMEOUT;
  1259. goto CleanUp;
  1260. } else if (status == 0) {
  1261. //
  1262. // Wait completed successfully
  1263. //
  1264. status = GetOverlappedResult(
  1265. PipeHandle,
  1266. &overlapped,
  1267. &bytesRead,
  1268. TRUE
  1269. );
  1270. if (status == FALSE) {
  1271. returnStatus = GetLastError();
  1272. SC_LOG(ERROR,
  1273. "SendControl: GetOverlappedResult failed, rc=%lu\n",
  1274. returnStatus);
  1275. goto CleanUp;
  1276. }
  1277. }
  1278. }
  1279. }
  1280. //
  1281. // Response received from the control dispatcher
  1282. //
  1283. if (bytesRead != sizeof(PIPE_RESPONSE_MSG)) {
  1284. //
  1285. // Successful transact, but we didn't get proper input.
  1286. // (note: we should never receive more bytes unless there
  1287. // is a bug in TransactNamedPipe).
  1288. //
  1289. SC_LOG(ERROR,
  1290. "SendControl: Incorrect num bytes in response, num=%d",
  1291. bytesRead);
  1292. ScLogEvent(NEVENT_TRANSACT_INVALID);
  1293. returnStatus = ERROR_GEN_FAILURE;
  1294. }
  1295. else {
  1296. returnStatus = serviceResponseBuffer.dwDispatcherStatus;
  1297. if (ARGUMENT_PRESENT(lpdwHandlerRetVal)) {
  1298. *lpdwHandlerRetVal = serviceResponseBuffer.dwHandlerRetVal;
  1299. }
  1300. }
  1301. }
  1302. CleanUp:
  1303. SC_LOG(LOCKS,"SendControl: Leaving TransactPipe Critical Section.\n",0);
  1304. LeaveCriticalSection(&ScTransactNPCriticalSection);
  1305. LocalFree(lpcmhBuffer);
  1306. if (returnStatus == NO_ERROR
  1307. &&
  1308. IS_CONTROL_LOGGABLE(OpCode)
  1309. &&
  1310. DisplayName != NULL && DisplayName[0] != L'\0')
  1311. {
  1312. ScLogControlEvent(NEVENT_SERVICE_CONTROL_SUCCESS,
  1313. DisplayName,
  1314. OpCode);
  1315. }
  1316. return(returnStatus);
  1317. }
  1318. VOID
  1319. ScInitTransactNamedPipe(
  1320. VOID
  1321. )
  1322. /*++
  1323. Routine Description:
  1324. This function initializes the Critical Section that serializes
  1325. calls to TransactNamedPipe and sets the pipe timeout value.
  1326. Arguments:
  1327. none
  1328. Return Value:
  1329. none
  1330. --*/
  1331. {
  1332. DWORD dwStatus;
  1333. HKEY hKeyControl;
  1334. DWORD dwValueType;
  1335. DWORD dwBufSize = sizeof(DWORD);
  1336. InitializeCriticalSection(&ScTransactNPCriticalSection);
  1337. //
  1338. // Read the pipe timeout value from the registry if it exists.
  1339. // If the read fails or the value's not there, use the default.
  1340. //
  1341. dwStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, // hKey
  1342. REGKEY_PIPE_TIMEOUT, // lpSubKey
  1343. 0,
  1344. KEY_READ, // Read access
  1345. &hKeyControl); // Newly Opened Key Handle
  1346. if (dwStatus == NO_ERROR) {
  1347. dwStatus = RegQueryValueEx(hKeyControl,
  1348. REGVAL_PIPE_TIMEOUT,
  1349. NULL,
  1350. &dwValueType,
  1351. (LPBYTE)&g_dwScPipeTransactTimeout,
  1352. &dwBufSize);
  1353. if (dwStatus != NO_ERROR || dwValueType != REG_DWORD) {
  1354. //
  1355. // The value's either not there or bogus so just use the default
  1356. //
  1357. SC_LOG0(TRACE,
  1358. "ScInitTransactNamedPipe: Can't find ServicesPipeTimeout "
  1359. "value in registry\n");
  1360. }
  1361. RegCloseKey(hKeyControl);
  1362. }
  1363. else {
  1364. //
  1365. // Not an error for this function, although a missing control
  1366. // key is probably relatively bad, so notify everybody
  1367. //
  1368. SC_LOG0(ERROR,
  1369. "ScInitTransactNamedPipe: Can't find Control "
  1370. "key in registry!\n");
  1371. }
  1372. SC_LOG1(TRACE,
  1373. "ScInitTransactNamedPipe: Using pipe timeout value of %u\n",
  1374. g_dwScPipeTransactTimeout);
  1375. }
  1376. VOID
  1377. ScShutdownAllServices(
  1378. VOID
  1379. )
  1380. /*++
  1381. Routine Description:
  1382. (called at system shutdown).
  1383. This function sends shutdown requests to all services that have
  1384. registered an interest in shutdown notification.
  1385. When we leave this routine, to the best of our knowledge, all the
  1386. services that should stop have stopped - or are in some hung state.
  1387. Note: It is expected that the RPC entry points are no longer serviced,
  1388. so we should not be receiving any requests that will add or delete
  1389. service records. Therefore, locks are not used when reading service
  1390. records during the shutdown loop.
  1391. Arguments:
  1392. none
  1393. Return Value:
  1394. none
  1395. Note:
  1396. --*/
  1397. {
  1398. DWORD status;
  1399. LPSERVICE_RECORD *affectedServices;
  1400. DWORD serviceIndex = 0;
  1401. DWORD arrayEnd = 0;
  1402. BOOL ServicesStopping;
  1403. DWORD maxWait = 0;
  1404. DWORD startTime;
  1405. DWORD arraySize;
  1406. #ifdef SC_SHUTDOWN_METRIC
  1407. //
  1408. // Local variables for shutdown performance metrics
  1409. //
  1410. DWORD dwShutdownTimeout = 0;
  1411. HKEY hKeyControl;
  1412. DWORD dwValueType;
  1413. DWORD dwBufSize = sizeof(DWORD);
  1414. #endif // SC_SHUTDOWN_METRIC
  1415. //
  1416. // Allocate a temporary array of services which we're interested in.
  1417. // (This is purely an optimization to avoid repeated traversals of the
  1418. // entire database of installed services.)
  1419. //
  1420. CServiceListSharedLock LLock;
  1421. arraySize = ScGetTotalNumberOfRecords();
  1422. affectedServices = (LPSERVICE_RECORD *)LocalAlloc(
  1423. LMEM_FIXED,
  1424. arraySize * sizeof(LPSERVICE_RECORD));
  1425. if (affectedServices == NULL) {
  1426. SC_LOG0(ERROR,"ScShutdownAllServices: LocalAlloc Failed\n");
  1427. return;
  1428. }
  1429. #ifdef SC_SHUTDOWN_METRIC
  1430. //
  1431. // Read the shutdown timeout value from the registry if it exists.
  1432. // If the read fails or the value's not there, use the default.
  1433. //
  1434. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, // hKey
  1435. REGKEY_SHUTDOWN_TIMEOUT, // lpSubKey
  1436. 0,
  1437. KEY_READ, // Read access
  1438. &hKeyControl) // Handle to newly-opened key
  1439. == ERROR_SUCCESS)
  1440. {
  1441. RegQueryValueEx(hKeyControl,
  1442. REGVAL_SHUTDOWN_TIMEOUT,
  1443. NULL,
  1444. &dwValueType,
  1445. (LPBYTE)&dwShutdownTimeout,
  1446. &dwBufSize);
  1447. RegCloseKey(hKeyControl);
  1448. }
  1449. #endif // SC_SHUTDOWN_METRIC
  1450. //-------------------------------------------------------------------
  1451. //
  1452. // Loop through service list sending stop requests to all that
  1453. // should receive such requests.
  1454. //
  1455. //-------------------------------------------------------------------
  1456. SC_LOG0(SHUTDOWN,"***** BEGIN SENDING STOPS TO SERVICES *****\n");
  1457. FOR_SERVICES_THAT(Service,
  1458. (Service->ServiceStatus.dwServiceType & SERVICE_WIN32) &&
  1459. (Service->ServiceStatus.dwCurrentState != SERVICE_STOPPED) &&
  1460. (Service->ServiceStatus.dwCurrentState != SERVICE_STOP_PENDING) &&
  1461. (Service->ServiceStatus.dwControlsAccepted & SERVICE_ACCEPT_SHUTDOWN) &&
  1462. (Service->ImageRecord != NULL)
  1463. )
  1464. {
  1465. //
  1466. // If the service is not in the stopped or stop pending
  1467. // state, it should be ok to send the control.
  1468. //
  1469. SC_LOG1(SHUTDOWN,"Shutdown: Sending Stop to Service : %ws\n",
  1470. Service->ServiceName);
  1471. status = ScSendControl(Service->ServiceName,
  1472. Service->DisplayName,
  1473. Service->ImageRecord->PipeHandle,
  1474. SERVICE_CONTROL_SHUTDOWN,
  1475. NULL, // CmdArgs
  1476. 0L, // NumArgs
  1477. NULL); // Ignore handler return value
  1478. if (status != NO_ERROR) {
  1479. SC_LOG1(ERROR,"ScShutdownAllServices: ScSendControl "
  1480. "Failed for %ws\n",Service->ServiceName);
  1481. }
  1482. else {
  1483. //
  1484. // Save the services that have been sent stop requests
  1485. // in the temporary array.
  1486. //
  1487. SC_ASSERT(serviceIndex < arraySize);
  1488. if (serviceIndex < arraySize) {
  1489. affectedServices[serviceIndex++] = Service;
  1490. }
  1491. }
  1492. }
  1493. SC_LOG0(SHUTDOWN,"***** DONE SENDING STOPS TO SERVICES *****\n");
  1494. //-------------------------------------------------------------------
  1495. //
  1496. // Now check to see if these services stopped.
  1497. //
  1498. //-------------------------------------------------------------------
  1499. startTime = GetTickCount();
  1500. arrayEnd = serviceIndex;
  1501. ServicesStopping = (serviceIndex != 0);
  1502. SC_LOG(SHUTDOWN,"Waiting for services to stop. Start time is %lu\n",
  1503. startTime);
  1504. while (ServicesStopping) {
  1505. //
  1506. // Wait a bit for the services to become stopped.
  1507. //
  1508. Sleep(500);
  1509. //
  1510. // We are going to check all the services in our shutdown
  1511. // list and see if we still have services to wait on.
  1512. //
  1513. ServicesStopping = FALSE;
  1514. maxWait = 0;
  1515. for (serviceIndex = 0; serviceIndex < arrayEnd ; serviceIndex++) {
  1516. Service = affectedServices[serviceIndex];
  1517. //
  1518. // If the service is in the stop pending state, then wait
  1519. // a bit and check back. Maximum wait time is the maximum
  1520. // wait hint period of all the services. If a service's
  1521. // wait hint is 0, use 20 seconds as its wait hint.
  1522. //
  1523. // Note that this is different from how dwWaitHint is
  1524. // interpreted for all other operations. We ignore
  1525. // dwCheckPoint here.
  1526. //
  1527. switch (Service->ServiceStatus.dwCurrentState) {
  1528. case SERVICE_STOP_PENDING:
  1529. SC_LOG2(SHUTDOWN,
  1530. "%ws Service is still pending, wait hint = %lu\n",
  1531. Service->ServiceName,
  1532. Service->ServiceStatus.dwWaitHint);
  1533. if (Service->ServiceStatus.dwWaitHint == 0) {
  1534. if (maxWait < 20000) {
  1535. maxWait = 20000;
  1536. }
  1537. }
  1538. else {
  1539. if (maxWait < Service->ServiceStatus.dwWaitHint) {
  1540. maxWait = Service->ServiceStatus.dwWaitHint;
  1541. }
  1542. }
  1543. ServicesStopping = TRUE;
  1544. break;
  1545. case SERVICE_STOPPED:
  1546. break;
  1547. case SERVICE_RUNNING:
  1548. if (maxWait < 30000) {
  1549. maxWait = 30000;
  1550. }
  1551. SC_LOG2(SHUTDOWN, "%ws Service is still running, maxWait is %lu\n",
  1552. Service->ServiceName, maxWait);
  1553. ServicesStopping = TRUE;
  1554. break;
  1555. default:
  1556. //
  1557. // This is an error. But we can't do anything about
  1558. // it, so it will be ignored.
  1559. //
  1560. SC_LOG2(SHUTDOWN,"ERROR: %ws Service is in invalid state %#lx\n",
  1561. Service->ServiceName,
  1562. Service->ServiceStatus.dwCurrentState);
  1563. break;
  1564. } // end switch
  1565. } // end for
  1566. //
  1567. // We have examined all the services. If there are still services
  1568. // with the STOP_PENDING, then see if we have timed out the
  1569. // maxWait period yet.
  1570. //
  1571. if (ServicesStopping) {
  1572. #ifdef SC_SHUTDOWN_METRIC
  1573. //
  1574. // Performance hook for service shutdown -- if a shutdown
  1575. // timeout was specified in the registry and it's been
  1576. // longer than the timeout, print out a list of all the
  1577. // unstopped services and break into the debugger. Do this
  1578. // on both free and checked builds. Note that this must be
  1579. // #if'ed out prior to shipping NT 5.0.
  1580. //
  1581. if (dwShutdownTimeout != 0
  1582. &&
  1583. (GetTickCount() - startTime) > dwShutdownTimeout) {
  1584. //
  1585. // Uh oh -- we've exceeded the max shutdown time
  1586. //
  1587. DbgPrint("\n[SC-SHUTDOWN] The following services failed to "
  1588. "shut down in %lu seconds:\n",
  1589. dwShutdownTimeout / 1000);
  1590. for (serviceIndex = 0; serviceIndex < arrayEnd; serviceIndex++) {
  1591. Service = affectedServices[serviceIndex];
  1592. if (Service->ServiceStatus.dwCurrentState != SERVICE_STOPPED) {
  1593. DbgPrint("%ws service is still running (state = %lu)\n",
  1594. Service->ServiceName,
  1595. Service->ServiceStatus.dwCurrentState);
  1596. }
  1597. }
  1598. DebugBreak();
  1599. }
  1600. #endif // SC_SHUTDOWN_METRIC
  1601. if ( (GetTickCount() - startTime) > maxWait ) {
  1602. //
  1603. // The maximum wait period has been exceeded. At this
  1604. // point we should end this shutdown effort. There is
  1605. // no point in forcing shutdown. So we just exit.
  1606. //
  1607. SC_LOG(ERROR,
  1608. "The Services didn't stop within the timeout "
  1609. "period of %lu.\n --- There is still at least one "
  1610. "service running\n",
  1611. maxWait);
  1612. #if DBG
  1613. SC_LOG0(ERROR, "The following Services failed to shut down:\n");
  1614. for (serviceIndex = 0; serviceIndex < arrayEnd ; serviceIndex++) {
  1615. Service = affectedServices[serviceIndex];
  1616. if (Service->ServiceStatus.dwCurrentState != SERVICE_STOPPED) {
  1617. SC_LOG2(ERROR, "%ws Service is still running (Service state = %lu)\n",
  1618. Service->ServiceName, Service->ServiceStatus.dwCurrentState);
  1619. }
  1620. }
  1621. #endif // DBG
  1622. ServicesStopping = FALSE;
  1623. }
  1624. }
  1625. }
  1626. SC_LOG0(SHUTDOWN,"Done Waiting for services to stop\n");
  1627. }
  1628. VOID
  1629. ScCleanOutPipe(
  1630. HANDLE PipeHandle
  1631. )
  1632. /*++
  1633. Routine Description:
  1634. This function reads and throws away all data that is currently in the
  1635. pipe. This function is called if the pipe is busy when it shouldn't be.
  1636. The PIPE_BUSY occurs when (1) the transact never returns, or (2) the
  1637. last transact timed-out, and the return message was eventually placed
  1638. in the pipe after the timeout.
  1639. This function is called to fix the (2) case by cleaning out the pipe.
  1640. Arguments:
  1641. PipeHandle - A Handle to the pipe to be cleaned out.
  1642. Return Value:
  1643. none.
  1644. --*/
  1645. {
  1646. #define EXPUNGE_BUF_SIZE 100
  1647. DWORD status;
  1648. DWORD returnStatus;
  1649. DWORD numBytesRead=0;
  1650. BYTE msg[EXPUNGE_BUF_SIZE];
  1651. OVERLAPPED overlapped={0,0,0,0,0};
  1652. do {
  1653. overlapped.hEvent = (HANDLE) NULL; // Wait on pipe handle
  1654. status = ReadFile (
  1655. PipeHandle,
  1656. msg,
  1657. EXPUNGE_BUF_SIZE,
  1658. &numBytesRead,
  1659. &overlapped);
  1660. if (status == FALSE) {
  1661. returnStatus = GetLastError();
  1662. if (returnStatus == ERROR_IO_PENDING) {
  1663. status = WaitForSingleObject(
  1664. PipeHandle,
  1665. SC_PIPE_CLEANOUT_TIMEOUT);
  1666. if (status == WAIT_TIMEOUT) {
  1667. SC_LOG0(ERROR, "ControlPipe was busy but we were unable to "
  1668. "clean it out in the timeout period\n");
  1669. //
  1670. // Cancel the named pipe operation.
  1671. //
  1672. status = CancelIo(PipeHandle);
  1673. if (status == FALSE) {
  1674. SC_LOG(ERROR,
  1675. "ScCleanOutPipe: CancelIo failed, %lu\n",
  1676. GetLastError());
  1677. }
  1678. }
  1679. }
  1680. else {
  1681. SC_LOG1(ERROR, "ControlPipe was busy. The attempt to clean"
  1682. "it out failed with %d\n", returnStatus);
  1683. }
  1684. }
  1685. }
  1686. while (status == ERROR_MORE_DATA);
  1687. }