2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS Client/Server Runtime SubSystem
4 * FILE: subsystems/win32/csrsrv/procsup.c
5 * PURPOSE: CSR Server DLL Process Management
6 * PROGRAMMERS: ReactOS Portable Systems Group
7 * Alex Ionescu (alex@relsoft.net)
10 /* INCLUDES *******************************************************************/
17 /* GLOBALS ********************************************************************/
19 RTL_CRITICAL_SECTION CsrProcessLock
;
20 PCSR_PROCESS CsrRootProcess
= NULL
;
21 SECURITY_QUALITY_OF_SERVICE CsrSecurityQos
=
23 sizeof(SECURITY_QUALITY_OF_SERVICE
),
24 SecurityImpersonation
,
25 SECURITY_STATIC_TRACKING
,
28 ULONG CsrProcessSequenceCount
= 5;
29 extern ULONG CsrTotalPerProcessDataLength
;
32 /* PRIVATE FUNCTIONS **********************************************************/
35 * @name CsrpSetToNormalPriority
37 * The CsrpSetToNormalPriority routine sets the current NT Process'
38 * priority to the normal priority for CSR Processes.
44 * @remarks The "Normal" Priority corresponds to the Normal Forground
45 * Priority (9) plus a boost of 4.
50 CsrSetToNormalPriority(VOID
) // CsrpSetToNormalPriority
52 KPRIORITY BasePriority
= (8 + 1) + 4;
54 /* Set the Priority */
55 NtSetInformationProcess(NtCurrentProcess(),
62 * @name CsrpSetToShutdownPriority
64 * The CsrpSetToShutdownPriority routine sets the current NT Process'
65 * priority to the boosted priority for CSR Processes doing shutdown.
66 * Additonally, it acquires the Shutdown Privilege required for shutdown.
72 * @remarks The "Shutdown" Priority corresponds to the Normal Forground
73 * Priority (9) plus a boost of 6.
78 CsrSetToShutdownPriority(VOID
) // CsrpSetToShutdownPriority
80 KPRIORITY SetBasePriority
= (8 + 1) + 6;
83 /* Get the shutdown privilege */
84 if (NT_SUCCESS(RtlAdjustPrivilege(SE_SHUTDOWN_PRIVILEGE
,
89 /* Set the Priority */
90 NtSetInformationProcess(NtCurrentProcess(),
98 * @name FindProcessForShutdown
100 * The FindProcessForShutdown routine returns a CSR Process which is ready
101 * to be shutdown, and sets the appropriate shutdown flags for it.
104 * Pointer to the LUID of the CSR Process calling this routine.
106 * @return Pointer to a CSR Process which is ready to be shutdown.
113 FindProcessForShutdown(IN PLUID CallerLuid
)
115 PCSR_PROCESS CsrProcess
, ReturnCsrProcess
= NULL
;
116 // PCSR_THREAD CsrThread;
120 LUID SystemLuid
= SYSTEM_LUID
;
121 // BOOLEAN IsSystemLuid = FALSE, IsOurLuid = FALSE;
122 PLIST_ENTRY NextEntry
;
124 /* Set the List Pointers */
125 NextEntry
= CsrRootProcess
->ListLink
.Flink
;
126 while (NextEntry
!= &CsrRootProcess
->ListLink
)
128 /* Get the process */
129 CsrProcess
= CONTAINING_RECORD(NextEntry
, CSR_PROCESS
, ListLink
);
131 /* Move to the next entry */
132 NextEntry
= NextEntry
->Flink
;
134 /* Skip this process if it's already been processed */
135 if (CsrProcess
->Flags
& CsrProcessSkipShutdown
) continue;
137 /* Get the LUID of this Process */
138 Status
= CsrGetProcessLuid(CsrProcess
->ProcessHandle
, &ProcessLuid
);
140 /* Check if we didn't get access to the LUID */
141 if (Status
== STATUS_ACCESS_DENIED
)
143 /* FIXME: Check if we have any threads */
145 /\* Check if we have any threads *\/
146 if (CsrProcess->ThreadCount)
148 /\* Impersonate one of the threads and retry *\/
149 CsrThread = CONTAINING_RECORD(CsrProcess->ThreadList.Flink,
152 CsrImpersonateClient(CsrThread);
153 Status = CsrGetProcessLuid(NULL, &ProcessLuid);
159 if (!NT_SUCCESS(Status
))
161 /* We didn't have access, so skip it */
162 CsrProcess
->Flags
|= CsrProcessSkipShutdown
;
166 /* Check if this is the System LUID */
167 if ((/*IsSystemLuid =*/ RtlEqualLuid(&ProcessLuid
, &SystemLuid
)))
169 /* Mark this process */
170 CsrProcess
->ShutdownFlags
|= CsrShutdownSystem
;
172 else if (!(/*IsOurLuid =*/ RtlEqualLuid(&ProcessLuid
, CallerLuid
)))
174 /* Our LUID doesn't match with the caller's */
175 CsrProcess
->ShutdownFlags
|= CsrShutdownOther
;
178 /* Check if we're past the previous level */
179 // FIXME: if ((CsrProcess->ShutdownLevel > Level) || !(ReturnCsrProcess))
180 if (CsrProcess
->ShutdownLevel
> Level
/* || !ReturnCsrProcess */)
182 /* Update the level */
183 Level
= CsrProcess
->ShutdownLevel
;
185 /* Set the final process */
186 ReturnCsrProcess
= CsrProcess
;
190 /* Check if we found a process */
191 if (ReturnCsrProcess
)
193 /* Skip this one next time */
194 ReturnCsrProcess
->Flags
|= CsrProcessSkipShutdown
;
197 return ReturnCsrProcess
;
201 * @name CsrProcessRefcountZero
203 * The CsrProcessRefcountZero routine is executed when a CSR Process has lost
204 * all its active references. It removes and de-allocates the CSR Process.
207 * Pointer to the CSR Process that is to be deleted.
211 * @remarks Do not call this routine. It is reserved for the internal
212 * thread management routines when a CSR Process has lost all
215 * This routine is called with the Process Lock held.
220 CsrProcessRefcountZero(IN PCSR_PROCESS CsrProcess
)
222 ASSERT(ProcessStructureListLocked());
224 /* Remove the Process from the list */
225 CsrRemoveProcess(CsrProcess
);
227 /* Check if there's a session */
228 if (CsrProcess
->NtSession
)
230 /* Dereference the Session */
231 CsrDereferenceNtSession(CsrProcess
->NtSession
, 0);
234 /* Close the Client Port if there is one */
235 if (CsrProcess
->ClientPort
) NtClose(CsrProcess
->ClientPort
);
237 /* Close the process handle */
238 NtClose(CsrProcess
->ProcessHandle
);
240 /* Free the Proces Object */
241 CsrDeallocateProcess(CsrProcess
);
245 * @name CsrLockedDereferenceProcess
247 * The CsrLockedDereferenceProcess dereferences a CSR Process while the
248 * Process Lock is already being held.
251 * Pointer to the CSR Process to be dereferenced.
255 * @remarks This routine will return with the Process Lock held.
260 CsrLockedDereferenceProcess(PCSR_PROCESS CsrProcess
)
264 /* Decrease reference count */
265 LockCount
= --CsrProcess
->ReferenceCount
;
266 ASSERT(LockCount
>= 0);
269 /* Call the generic cleanup code */
270 DPRINT1("Should kill process: %p\n", CsrProcess
);
271 CsrProcessRefcountZero(CsrProcess
);
272 CsrAcquireProcessLock();
277 * @name CsrAllocateProcess
280 * The CsrAllocateProcess routine allocates a new CSR Process object.
282 * @return Pointer to the newly allocated CSR Process.
289 CsrAllocateProcess(VOID
)
291 PCSR_PROCESS CsrProcess
;
294 /* Calculate the amount of memory this should take */
295 TotalSize
= sizeof(CSR_PROCESS
) +
296 (CSR_SERVER_DLL_MAX
* sizeof(PVOID
)) +
297 CsrTotalPerProcessDataLength
;
299 /* Allocate a Process */
300 CsrProcess
= RtlAllocateHeap(CsrHeap
, HEAP_ZERO_MEMORY
, TotalSize
);
301 if (!CsrProcess
) return NULL
;
303 /* Handle the Sequence Number and protect against overflow */
304 CsrProcess
->SequenceNumber
= CsrProcessSequenceCount
++;
305 if (CsrProcessSequenceCount
< 5) CsrProcessSequenceCount
= 5;
307 /* Increase the reference count */
308 CsrProcess
->ReferenceCount
++;
310 /* Initialize the Thread List */
311 InitializeListHead(&CsrProcess
->ThreadList
);
313 /* Return the Process */
318 * @name CsrLockedReferenceProcess
320 * The CsrLockedReferenceProcess references a CSR Process while the
321 * Process Lock is already being held.
324 * Pointer to the CSR Process to be referenced.
328 * @remarks This routine will return with the Process Lock held.
333 CsrLockedReferenceProcess(IN PCSR_PROCESS CsrProcess
)
335 /* Increment the reference count */
336 ++CsrProcess
->ReferenceCount
;
340 * @name CsrInitializeProcessStructure
343 * The CsrInitializeProcessStructure routine sets up support for CSR Processes
344 * and CSR Threads by initializing our own CSR Root Process.
348 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL
356 CsrInitializeProcessStructure(VOID
)
361 /* Initialize the Lock */
362 Status
= RtlInitializeCriticalSection(&CsrProcessLock
);
363 if (!NT_SUCCESS(Status
)) return Status
;
365 /* Set up the Root Process */
366 CsrRootProcess
= CsrAllocateProcess();
367 if (!CsrRootProcess
) return STATUS_NO_MEMORY
;
369 /* Set up the minimal information for it */
370 InitializeListHead(&CsrRootProcess
->ListLink
);
371 CsrRootProcess
->ProcessHandle
= (HANDLE
)-1;
372 CsrRootProcess
->ClientId
= NtCurrentTeb()->ClientId
;
374 /* Initialize the Thread Hash List */
375 for (i
= 0; i
< 256; i
++) InitializeListHead(&CsrThreadHashTable
[i
]);
377 /* Initialize the Wait Lock */
378 return RtlInitializeCriticalSection(&CsrWaitListsLock
);
382 * @name CsrDeallocateProcess
384 * The CsrDeallocateProcess frees the memory associated with a CSR Process.
387 * Pointer to the CSR Process to be freed.
391 * @remarks Do not call this routine. It is reserved for the internal
392 * thread management routines when a CSR Process has been cleanly
393 * dereferenced and killed.
398 CsrDeallocateProcess(IN PCSR_PROCESS CsrProcess
)
400 /* Free the process object from the heap */
401 RtlFreeHeap(CsrHeap
, 0, CsrProcess
);
405 * @name CsrRemoveProcess
407 * The CsrRemoveProcess function undoes a CsrInsertProcess operation and
408 * removes the CSR Process from the Process List and notifies Server DLLs
412 * Pointer to the CSR Process to remove.
421 CsrRemoveProcess(IN PCSR_PROCESS CsrProcess
)
423 PCSR_SERVER_DLL ServerDll
;
425 ASSERT(ProcessStructureListLocked());
427 /* Remove us from the Process List */
428 RemoveEntryList(&CsrProcess
->ListLink
);
430 /* Release the lock */
431 CsrReleaseProcessLock();
433 /* Loop every Server DLL */
434 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
436 /* Get the Server DLL */
437 ServerDll
= CsrLoadedServerDll
[i
];
439 /* Check if it's valid and if it has a Disconnect Callback */
440 if (ServerDll
&& ServerDll
->DisconnectCallback
)
443 ServerDll
->DisconnectCallback(CsrProcess
);
449 * @name CsrInsertProcess
451 * The CsrInsertProcess routine inserts a CSR Process into the Process List
452 * and notifies Server DLLs of the creation of a new CSR Process.
455 * Optional pointer to the CSR Process creating this CSR Process.
457 * @param CurrentProcess
458 * Optional pointer to the current CSR Process.
461 * Pointer to the CSR Process which is to be inserted.
470 CsrInsertProcess(IN PCSR_PROCESS Parent OPTIONAL
, // ParentProcess
471 IN PCSR_PROCESS CurrentProcess OPTIONAL
, // CallingProcess
472 IN PCSR_PROCESS CsrProcess
) // Process
474 PCSR_SERVER_DLL ServerDll
;
476 ASSERT(ProcessStructureListLocked());
479 CsrProcess
->Parent
= Parent
;
481 /* Insert it into the Root List */
482 InsertTailList(&CsrRootProcess
->ListLink
, &CsrProcess
->ListLink
);
484 /* Notify the Server DLLs */
485 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
487 /* Get the current Server DLL */
488 ServerDll
= CsrLoadedServerDll
[i
];
490 /* Make sure it's valid and that it has callback */
491 if (ServerDll
&& ServerDll
->NewProcessCallback
)
493 ServerDll
->NewProcessCallback(CurrentProcess
, CsrProcess
);
499 /* PUBLIC FUNCTIONS ***********************************************************/
502 * @name CsrCreateProcess
505 * Do nothing for 500ms.
507 * @param ArgumentCount
508 * Description of the parameter. Wrapped to more lines on ~70th
512 * Description of the parameter. Wrapped to more lines on ~70th
515 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL
523 CsrCreateProcess(IN HANDLE hProcess
,
525 IN PCLIENT_ID ClientId
,
526 IN PCSR_NT_SESSION NtSession
,
528 IN PCLIENT_ID DebugCid
)
530 PCSR_THREAD CurrentThread
= CsrGetClientThread();
531 CLIENT_ID CurrentCid
;
532 PCSR_PROCESS CurrentProcess
;
533 PCSR_SERVER_DLL ServerDll
;
536 PCSR_PROCESS CsrProcess
;
538 PCSR_THREAD CsrThread
;
539 KERNEL_USER_TIMES KernelTimes
;
541 /* Get the current CID and lock Processes */
542 CurrentCid
= CurrentThread
->ClientId
;
543 CsrAcquireProcessLock();
545 /* Get the current CSR Thread */
546 CurrentThread
= CsrLocateThreadByClientId(&CurrentProcess
, &CurrentCid
);
549 /* We've failed to locate the thread */
550 CsrReleaseProcessLock();
551 return STATUS_THREAD_IS_TERMINATING
;
554 /* Allocate a new Process Object */
555 CsrProcess
= CsrAllocateProcess();
558 /* Couldn't allocate Process */
559 CsrReleaseProcessLock();
560 return STATUS_NO_MEMORY
;
563 /* Inherit the Process Data */
564 CurrentProcess
= CurrentThread
->Process
;
565 ProcessData
= &CurrentProcess
->ServerData
[CSR_SERVER_DLL_MAX
];
566 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
568 /* Get the current Server */
569 ServerDll
= CsrLoadedServerDll
[i
];
571 /* Check if the DLL is Loaded and has Per Process Data */
572 if (ServerDll
&& ServerDll
->SizeOfProcessData
)
574 /* Set the pointer */
575 CsrProcess
->ServerData
[i
] = ProcessData
;
578 RtlMoveMemory(ProcessData
,
579 CurrentProcess
->ServerData
[i
],
580 ServerDll
->SizeOfProcessData
);
582 /* Update next data pointer */
583 ProcessData
= (PVOID
)((ULONG_PTR
)ProcessData
+
584 ServerDll
->SizeOfProcessData
);
588 /* No data for this Server */
589 CsrProcess
->ServerData
[i
] = NULL
;
593 /* Set the Exception port for us */
594 Status
= NtSetInformationProcess(hProcess
,
595 ProcessExceptionPort
,
598 if (!NT_SUCCESS(Status
))
601 CsrDeallocateProcess(CsrProcess
);
602 CsrReleaseProcessLock();
603 return STATUS_NO_MEMORY
;
606 /* Check if CreateProcess got CREATE_NEW_PROCESS_GROUP */
607 if (!(Flags
& CsrProcessCreateNewGroup
))
609 /* Create new data */
610 CsrProcess
->ProcessGroupId
= HandleToUlong(ClientId
->UniqueProcess
);
611 CsrProcess
->ProcessGroupSequence
= CsrProcess
->SequenceNumber
;
615 /* Copy it from the current process */
616 CsrProcess
->ProcessGroupId
= CurrentProcess
->ProcessGroupId
;
617 CsrProcess
->ProcessGroupSequence
= CurrentProcess
->ProcessGroupSequence
;
620 /* Check if this is a console process */
621 if (Flags
& CsrProcessIsConsoleApp
) CsrProcess
->Flags
|= CsrProcessIsConsoleApp
;
623 /* Mask out non-debug flags */
624 Flags
&= ~(CsrProcessIsConsoleApp
| CsrProcessCreateNewGroup
| CsrProcessPriorityFlags
);
626 /* Check if every process will be debugged */
627 if (!(Flags
) && (CurrentProcess
->DebugFlags
& CsrDebugProcessChildren
))
629 /* Pass it on to the current process */
630 CsrProcess
->DebugFlags
= CsrDebugProcessChildren
;
631 CsrProcess
->DebugCid
= CurrentProcess
->DebugCid
;
634 /* Check if Debugging was used on this process */
635 if ((Flags
& (CsrDebugOnlyThisProcess
| CsrDebugProcessChildren
)) && (DebugCid
))
637 /* Save the debug flag used */
638 CsrProcess
->DebugFlags
= Flags
;
641 CsrProcess
->DebugCid
= *DebugCid
;
644 /* Check if Debugging is enabled */
645 if (CsrProcess
->DebugFlags
)
647 /* Set the Debug Port for us */
648 Status
= NtSetInformationProcess(hProcess
,
652 ASSERT(NT_SUCCESS(Status
));
653 if (!NT_SUCCESS(Status
))
656 CsrDeallocateProcess(CsrProcess
);
657 CsrReleaseProcessLock();
658 return STATUS_NO_MEMORY
;
662 /* Get the Thread Create Time */
663 Status
= NtQueryInformationThread(hThread
,
668 if (!NT_SUCCESS(Status
))
671 CsrDeallocateProcess(CsrProcess
);
672 CsrReleaseProcessLock();
673 return STATUS_NO_MEMORY
;
676 /* Allocate a CSR Thread Structure */
677 CsrThread
= CsrAllocateThread(CsrProcess
);
681 CsrDeallocateProcess(CsrProcess
);
682 CsrReleaseProcessLock();
683 return STATUS_NO_MEMORY
;
686 /* Save the data we have */
687 CsrThread
->CreateTime
= KernelTimes
.CreateTime
;
688 CsrThread
->ClientId
= *ClientId
;
689 CsrThread
->ThreadHandle
= hThread
;
690 ProtectHandle(hThread
);
691 CsrThread
->Flags
= 0;
693 /* Insert the Thread into the Process */
694 CsrInsertThread(CsrProcess
, CsrThread
);
696 /* Reference the session */
697 CsrReferenceNtSession(NtSession
);
698 CsrProcess
->NtSession
= NtSession
;
700 /* Setup Process Data */
701 CsrProcess
->ClientId
= *ClientId
;
702 CsrProcess
->ProcessHandle
= hProcess
;
703 CsrProcess
->ShutdownLevel
= 0x280;
705 /* Set the Priority to Background */
706 CsrSetBackgroundPriority(CsrProcess
);
708 /* Insert the Process */
709 CsrInsertProcess(NULL
, CurrentProcess
, CsrProcess
);
711 /* Release lock and return */
712 CsrReleaseProcessLock();
717 * @name CsrDebugProcess
720 * The CsrDebugProcess routine is deprecated in NT 5.1 and higher. It is
721 * exported only for compatibility with older CSR Server DLLs.
728 * @remarks Deprecated.
733 CsrDebugProcess(IN PCSR_PROCESS CsrProcess
)
735 /* CSR does not handle debugging anymore */
736 DPRINT("CSRSRV: %s(%08lx) called\n", __FUNCTION__
, CsrProcess
);
737 return STATUS_UNSUCCESSFUL
;
741 * @name CsrDebugProcessStop
744 * The CsrDebugProcessStop routine is deprecated in NT 5.1 and higher. It is
745 * exported only for compatibility with older CSR Server DLLs.
752 * @remarks Deprecated.
757 CsrDebugProcessStop(IN PCSR_PROCESS CsrProcess
)
759 /* CSR does not handle debugging anymore */
760 DPRINT("CSRSRV: %s(%08lx) called\n", __FUNCTION__
, CsrProcess
);
761 return STATUS_UNSUCCESSFUL
;
765 * @name CsrDereferenceProcess
768 * The CsrDereferenceProcess routine removes a reference from a CSR Process.
771 * Pointer to the CSR Process to dereference.
775 * @remarks If the reference count has reached zero (ie: the CSR Process has
776 * no more active references), it will be deleted.
781 CsrDereferenceProcess(IN PCSR_PROCESS CsrProcess
)
785 /* Acquire process lock */
786 CsrAcquireProcessLock();
788 /* Decrease reference count */
789 LockCount
= --CsrProcess
->ReferenceCount
;
790 ASSERT(LockCount
>= 0);
793 /* Call the generic cleanup code */
794 CsrProcessRefcountZero(CsrProcess
);
798 /* Just release the lock */
799 CsrReleaseProcessLock();
804 * @name CsrDestroyProcess
807 * The CsrDestroyProcess routine destroys the CSR Process corresponding to
811 * Pointer to the Client ID Structure corresponding to the CSR
812 * Process which is about to be destroyed.
817 * @return STATUS_SUCCESS in case of success, STATUS_THREAD_IS_TERMINATING
818 * if the CSR Process is already terminating.
825 CsrDestroyProcess(IN PCLIENT_ID Cid
,
826 IN NTSTATUS ExitStatus
)
828 PCSR_THREAD CsrThread
;
829 PCSR_PROCESS CsrProcess
;
830 CLIENT_ID ClientId
= *Cid
;
831 PLIST_ENTRY NextEntry
;
834 CsrAcquireProcessLock();
836 /* Find the thread */
837 CsrThread
= CsrLocateThreadByClientId(&CsrProcess
, &ClientId
);
839 /* Make sure we got one back, and that it's not already gone */
840 if (!(CsrThread
) || (CsrProcess
->Flags
& CsrProcessTerminating
))
842 /* Release the lock and return failure */
843 CsrReleaseProcessLock();
844 return STATUS_THREAD_IS_TERMINATING
;
847 /* Set the terminated flag */
848 CsrProcess
->Flags
|= CsrProcessTerminating
;
850 /* Get the List Pointers */
851 NextEntry
= CsrProcess
->ThreadList
.Flink
;
852 while (NextEntry
!= &CsrProcess
->ThreadList
)
854 /* Get the current thread entry */
855 CsrThread
= CONTAINING_RECORD(NextEntry
, CSR_THREAD
, Link
);
857 /* Make sure the thread isn't already dead */
858 if (CsrThread
->Flags
& CsrThreadTerminated
)
860 NextEntry
= NextEntry
->Flink
;
864 /* Set the Terminated flag */
865 CsrThread
->Flags
|= CsrThreadTerminated
;
867 /* Acquire the Wait Lock */
868 CsrAcquireWaitLock();
870 /* Do we have an active wait block? */
871 if (CsrThread
->WaitBlock
)
873 /* Notify waiters of termination */
874 CsrNotifyWaitBlock(CsrThread
->WaitBlock
,
878 CsrProcessTerminating
,
882 /* Release the Wait Lock */
883 CsrReleaseWaitLock();
885 /* Dereference the thread */
886 CsrLockedDereferenceThread(CsrThread
);
887 NextEntry
= CsrProcess
->ThreadList
.Flink
;
890 /* Release the Process Lock and return success */
891 CsrReleaseProcessLock();
892 return STATUS_SUCCESS
;
896 * @name CsrGetProcessLuid
899 * Do nothing for 500ms.
902 * Optional handle to the process whose LUID should be returned.
905 * Pointer to a LUID Pointer which will receive the CSR Process' LUID
907 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL
910 * @remarks If hProcess is not supplied, then the current thread's token will
911 * be used. If that too is missing, then the current process' token
917 CsrGetProcessLuid(IN HANDLE hProcess OPTIONAL
,
920 HANDLE hToken
= NULL
;
923 PTOKEN_STATISTICS TokenStats
;
925 /* Check if we have a handle to a CSR Process */
928 /* We don't, so try opening the Thread's Token */
929 Status
= NtOpenThreadToken(NtCurrentThread(),
934 /* Check for success */
935 if (!NT_SUCCESS(Status
))
937 /* If we got some other failure, then return and quit */
938 if (Status
!= STATUS_NO_TOKEN
) return Status
;
940 /* We don't have a Thread Token, use a Process Token */
941 hProcess
= NtCurrentProcess();
946 /* Check if we have a token by now */
949 /* No token yet, so open the Process Token */
950 Status
= NtOpenProcessToken(hProcess
,
953 if (!NT_SUCCESS(Status
))
955 /* Still no token, return the error */
960 /* Now get the size we'll need for the Token Information */
961 Status
= NtQueryInformationToken(hToken
,
967 /* Allocate memory for the Token Info */
968 if (!(TokenStats
= RtlAllocateHeap(CsrHeap
, 0, Length
)))
970 /* Fail and close the token */
972 return STATUS_NO_MEMORY
;
975 /* Now query the information */
976 Status
= NtQueryInformationToken(hToken
,
982 /* Close the handle */
985 /* Check for success */
986 if (NT_SUCCESS(Status
))
988 /* Return the LUID */
989 *Luid
= TokenStats
->AuthenticationId
;
992 /* Free the query information */
993 RtlFreeHeap(CsrHeap
, 0, TokenStats
);
995 /* Return the Status */
1000 * @name CsrImpersonateClient
1003 * The CsrImpersonateClient will impersonate the given CSR Thread.
1006 * Pointer to the CSR Thread to impersonate.
1008 * @return TRUE if impersionation suceeded, false otherwise.
1010 * @remarks Impersonation can be recursive.
1015 CsrImpersonateClient(IN PCSR_THREAD CsrThread
)
1018 PCSR_THREAD CurrentThread
= CsrGetClientThread();
1020 /* Use the current thread if none given */
1021 if (!CsrThread
) CsrThread
= CurrentThread
;
1023 /* Still no thread, something is wrong */
1031 Status
= NtImpersonateThread(NtCurrentThread(),
1032 CsrThread
->ThreadHandle
,
1035 if (!NT_SUCCESS(Status
))
1039 DPRINT1("CSRSS: Can't impersonate client thread - Status = %lx\n", Status);
1040 if (Status != STATUS_BAD_IMPERSONATION_LEVEL) DbgBreakPoint();
1045 /* Increase the impersonation count for the current thread */
1046 if (CurrentThread
) ++CurrentThread
->ImpersonationCount
;
1048 /* Return Success */
1053 * @name CsrLockProcessByClientId
1056 * The CsrLockProcessByClientId routine locks the CSR Process corresponding
1057 * to the given Process ID and optionally returns it.
1060 * Process ID corresponding to the CSR Process which will be locked.
1063 * Optional pointer to a CSR Process pointer which will hold the
1064 * CSR Process corresponding to the given Process ID.
1066 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL
1069 * @remarks Locking a CSR Process is defined as acquiring an extra
1070 * reference to it and returning with the Process Lock held.
1075 CsrLockProcessByClientId(IN HANDLE Pid
,
1076 OUT PCSR_PROCESS
*CsrProcess
)
1078 PLIST_ENTRY NextEntry
;
1079 PCSR_PROCESS CurrentProcess
= NULL
;
1082 /* Acquire the lock */
1083 CsrAcquireProcessLock();
1085 /* Assume failure */
1086 ASSERT(CsrProcess
!= NULL
);
1089 /* Setup the List Pointers */
1090 NextEntry
= &CsrRootProcess
->ListLink
;
1093 /* Get the Process */
1094 CurrentProcess
= CONTAINING_RECORD(NextEntry
, CSR_PROCESS
, ListLink
);
1096 /* Check for PID Match */
1097 if (CurrentProcess
->ClientId
.UniqueProcess
== Pid
)
1099 Status
= STATUS_SUCCESS
;
1104 NextEntry
= NextEntry
->Flink
;
1105 } while (NextEntry
!= &CsrRootProcess
->ListLink
);
1107 /* Check if we didn't find it in the list */
1108 if (!NT_SUCCESS(Status
))
1110 /* Nothing found, release the lock */
1111 CsrReleaseProcessLock();
1115 /* Lock the found process and return it */
1116 CsrLockedReferenceProcess(CurrentProcess
);
1117 *CsrProcess
= CurrentProcess
;
1120 /* Return the result */
1125 * @name CsrRevertToSelf
1128 * The CsrRevertToSelf routine will attempt to remove an active impersonation.
1132 * @return TRUE if the reversion was succesful, false otherwise.
1134 * @remarks Impersonation can be recursive; as such, the impersonation token
1135 * will only be deleted once the CSR Thread's impersonaton count
1141 CsrRevertToSelf(VOID
)
1144 PCSR_THREAD CurrentThread
= CsrGetClientThread();
1145 HANDLE ImpersonationToken
= NULL
;
1147 /* Check if we have a Current Thread */
1150 /* Make sure impersonation is on */
1151 if (!CurrentThread
->ImpersonationCount
)
1153 // DPRINT1("CSRSS: CsrRevertToSelf called while not impersonating\n");
1157 else if (--CurrentThread
->ImpersonationCount
> 0)
1159 /* Success; impersonation count decreased but still not zero */
1164 /* Impersonation has been totally removed, revert to ourselves */
1165 Status
= NtSetInformationThread(NtCurrentThread(),
1166 ThreadImpersonationToken
,
1167 &ImpersonationToken
,
1170 /* Return TRUE or FALSE */
1171 return NT_SUCCESS(Status
);
1175 * @name CsrSetBackgroundPriority
1178 * The CsrSetBackgroundPriority routine sets the priority for the given CSR
1179 * Process as a Background priority.
1182 * Pointer to the CSR Process whose priority will be modified.
1191 CsrSetBackgroundPriority(IN PCSR_PROCESS CsrProcess
)
1193 PROCESS_PRIORITY_CLASS PriorityClass
;
1195 /* Set the Foreground bit off */
1196 PriorityClass
.Foreground
= FALSE
;
1198 /* Set the new Priority */
1199 NtSetInformationProcess(CsrProcess
->ProcessHandle
,
1200 ProcessPriorityClass
,
1202 sizeof(PriorityClass
));
1206 * @name CsrSetForegroundPriority
1209 * The CsrSetForegroundPriority routine sets the priority for the given CSR
1210 * Process as a Foreground priority.
1213 * Pointer to the CSR Process whose priority will be modified.
1222 CsrSetForegroundPriority(IN PCSR_PROCESS CsrProcess
)
1224 PROCESS_PRIORITY_CLASS PriorityClass
;
1226 /* Set the Foreground bit on */
1227 PriorityClass
.Foreground
= TRUE
;
1229 /* Set the new Priority */
1230 NtSetInformationProcess(CsrProcess
->ProcessHandle
,
1231 ProcessPriorityClass
,
1233 sizeof(PriorityClass
));
1237 * @name CsrShutdownProcesses
1240 * The CsrShutdownProcesses routine shuts down every CSR Process possible
1241 * and calls each Server DLL's shutdown notification.
1244 * Pointer to the LUID of the CSR Process that is ordering the
1248 * Flags to send to the shutdown notification routine.
1250 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL
1258 CsrShutdownProcesses(IN PLUID CallerLuid
,
1261 PLIST_ENTRY NextEntry
;
1262 PCSR_PROCESS CsrProcess
;
1266 PCSR_SERVER_DLL ServerDll
;
1267 ULONG Result
= 0; /* Intentionally invalid enumeratee to silence compiler warning */
1269 /* Acquire process lock */
1270 CsrAcquireProcessLock();
1272 /* Add shutdown flag */
1273 CsrRootProcess
->ShutdownFlags
|= CsrShutdownSystem
;
1275 /* Get the list pointers */
1276 NextEntry
= CsrRootProcess
->ListLink
.Flink
;
1277 while (NextEntry
!= &CsrRootProcess
->ListLink
)
1279 /* Get the Process */
1280 CsrProcess
= CONTAINING_RECORD(NextEntry
, CSR_PROCESS
, ListLink
);
1282 /* Remove the skip flag, set shutdown flags to 0*/
1283 CsrProcess
->Flags
&= ~CsrProcessSkipShutdown
;
1284 CsrProcess
->ShutdownFlags
= 0;
1286 /* Move to the next */
1287 NextEntry
= NextEntry
->Flink
;
1290 /* Set shudown Priority */
1291 // CsrpSetToShutdownPriority();
1292 CsrSetToShutdownPriority();
1297 /* Find the next process to shutdown */
1298 CsrProcess
= FindProcessForShutdown(CallerLuid
);
1299 if (!CsrProcess
) break;
1301 /* Increase reference to process */
1302 CsrProcess
->ReferenceCount
++;
1307 /* Loop all the servers */
1308 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
1310 /* Get the current server */
1311 ServerDll
= CsrLoadedServerDll
[i
];
1313 /* Check if it's valid and if it has a Shutdown Process Callback */
1314 if (ServerDll
&& ServerDll
->ShutdownProcessCallback
)
1316 /* Release the lock, make the callback, and acquire it back */
1317 CsrReleaseProcessLock();
1318 Result
= ServerDll
->ShutdownProcessCallback(CsrProcess
,
1321 CsrAcquireProcessLock();
1323 /* Check the result */
1324 if (Result
== CsrShutdownCsrProcess
)
1326 /* The callback unlocked the process */
1329 else if (Result
== CsrShutdownCancelled
)
1331 /* Check if this was a forced shutdown */
1332 if (Flags
& EWX_FORCE
)
1334 DPRINT1("Process %x cancelled forced shutdown (Dll = %d)\n",
1335 CsrProcess
->ClientId
.UniqueProcess
, i
);
1339 /* Shutdown was cancelled, unlock and exit */
1340 CsrReleaseProcessLock();
1341 Status
= STATUS_CANCELLED
;
1347 /* No matches during the first try, so loop again */
1348 if ((FirstTry
) && (Result
== CsrShutdownNonCsrProcess
))
1354 /* Second try, break out */
1358 /* We've reached the final loop here, so dereference */
1359 if (i
== CSR_SERVER_DLL_MAX
) CsrLockedDereferenceProcess(CsrProcess
);
1363 CsrReleaseProcessLock();
1364 Status
= STATUS_SUCCESS
;
1367 /* Return to normal priority */
1368 // CsrpSetToNormalPriority();
1369 CsrSetToNormalPriority();
1374 /* FIXME: Temporary hack. This is really "CsrShutdownProcess", mostly. Used by winsrv */
1378 CsrEnumProcesses(IN CSRSS_ENUM_PROCESS_PROC EnumProc
,
1381 PVOID
* RealContext
= (PVOID
*)Context
;
1382 PLUID CallerLuid
= RealContext
[0];
1383 PCSR_PROCESS CsrProcess
= NULL
;
1384 NTSTATUS Status
= STATUS_UNSUCCESSFUL
;
1386 PLIST_ENTRY NextEntry
;
1389 /* Acquire process lock */
1390 CsrAcquireProcessLock();
1392 /* Get the list pointers */
1393 NextEntry
= CsrRootProcess
->ListLink
.Flink
;
1394 while (NextEntry
!= &CsrRootProcess
->ListLink
)
1396 /* Get the Process */
1397 CsrProcess
= CONTAINING_RECORD(NextEntry
, CSR_PROCESS
, ListLink
);
1399 /* Remove the skip flag, set shutdown flags to 0*/
1400 CsrProcess
->Flags
&= ~CsrProcessSkipShutdown
;
1401 CsrProcess
->ShutdownFlags
= 0;
1403 /* Move to the next */
1404 NextEntry
= NextEntry
->Flink
;
1407 /* Set shudown Priority */
1408 CsrSetToShutdownPriority();
1410 /* Loop all processes */
1411 //DPRINT1("Enumerating for LUID: %lx %lx\n", CallerLuid->HighPart, CallerLuid->LowPart);
1416 /* Find the next process to shutdown */
1418 if (!(CsrProcess
= FindProcessForShutdown(CallerLuid
)))
1421 CsrReleaseProcessLock();
1422 Status
= STATUS_SUCCESS
;
1427 /* Release the lock, make the callback, and acquire it back */
1428 //DPRINT1("Found process: %lx\n", CsrProcess->ClientId.UniqueProcess);
1429 CsrReleaseProcessLock();
1430 Result
= (ULONG
)EnumProc(CsrProcess
, (PVOID
)((ULONG_PTR
)Context
| FirstTry
));
1431 CsrAcquireProcessLock();
1433 /* Check the result */
1434 //DPRINT1("Result: %d\n", Result);
1435 if (Result
== CsrShutdownCsrProcess
)
1437 /* The callback unlocked the process */
1440 else if (Result
== CsrShutdownNonCsrProcess
)
1442 /* A non-CSR process, the callback didn't touch it */
1445 else if (Result
== CsrShutdownCancelled
)
1447 /* Shutdown was cancelled, unlock and exit */
1448 CsrReleaseProcessLock();
1449 Status
= STATUS_CANCELLED
;
1453 /* No matches during the first try, so loop again */
1454 if (FirstTry
&& Result
== CsrShutdownNonCsrProcess
)
1462 /* Return to normal priority */
1463 CsrSetToNormalPriority();
1469 * @name CsrUnlockProcess
1472 * The CsrUnlockProcess undoes a previous CsrLockProcessByClientId operation.
1475 * Pointer to a previously locked CSR Process.
1477 * @return STATUS_SUCCESS.
1479 * @remarks This routine must be called with the Process Lock held.
1484 CsrUnlockProcess(IN PCSR_PROCESS CsrProcess
)
1486 /* Dereference the process */
1487 CsrLockedDereferenceProcess(CsrProcess
);
1489 /* Release the lock and return */
1490 CsrReleaseProcessLock();
1491 return STATUS_SUCCESS
;