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 *******************************************************************/
19 /* GLOBALS ********************************************************************/
21 RTL_CRITICAL_SECTION CsrProcessLock
;
22 PCSR_PROCESS CsrRootProcess
= NULL
;
23 SECURITY_QUALITY_OF_SERVICE CsrSecurityQos
=
25 sizeof(SECURITY_QUALITY_OF_SERVICE
),
26 SecurityImpersonation
,
27 SECURITY_STATIC_TRACKING
,
30 ULONG CsrProcessSequenceCount
= 5;
31 extern ULONG CsrTotalPerProcessDataLength
;
34 /* PRIVATE FUNCTIONS **********************************************************/
37 * @name CsrSetToNormalPriority
39 * The CsrSetToNormalPriority routine sets the current NT Process'
40 * priority to the normal priority for CSR Processes.
46 * @remarks The "Normal" Priority corresponds to the Normal Foreground
47 * Priority (9) plus a boost of 4.
52 CsrSetToNormalPriority(VOID
)
54 KPRIORITY BasePriority
= (8 + 1) + 4;
56 /* Set the Priority */
57 NtSetInformationProcess(NtCurrentProcess(),
64 * @name CsrSetToShutdownPriority
66 * The CsrSetToShutdownPriority routine sets the current NT Process'
67 * priority to the boosted priority for CSR Processes doing shutdown.
68 * Additonally, it acquires the Shutdown Privilege required for shutdown.
74 * @remarks The "Shutdown" Priority corresponds to the Normal Foreground
75 * Priority (9) plus a boost of 6.
80 CsrSetToShutdownPriority(VOID
)
82 KPRIORITY SetBasePriority
= (8 + 1) + 6;
85 /* Get the shutdown privilege */
86 if (NT_SUCCESS(RtlAdjustPrivilege(SE_SHUTDOWN_PRIVILEGE
,
91 /* Set the Priority */
92 NtSetInformationProcess(NtCurrentProcess(),
100 * @name FindProcessForShutdown
102 * The FindProcessForShutdown routine returns a CSR Process which is ready
103 * to be shutdown, and sets the appropriate shutdown flags for it.
106 * Pointer to the LUID of the CSR Process calling this routine.
108 * @return Pointer to a CSR Process which is ready to be shutdown.
115 FindProcessForShutdown(IN PLUID CallerLuid
)
117 PCSR_PROCESS CsrProcess
, ReturnCsrProcess
= NULL
;
118 // PCSR_THREAD CsrThread;
122 LUID SystemLuid
= SYSTEM_LUID
;
123 // BOOLEAN IsSystemLuid = FALSE, IsOurLuid = FALSE;
124 PLIST_ENTRY NextEntry
;
126 /* Set the List Pointers */
127 NextEntry
= CsrRootProcess
->ListLink
.Flink
;
128 while (NextEntry
!= &CsrRootProcess
->ListLink
)
130 /* Get the process */
131 CsrProcess
= CONTAINING_RECORD(NextEntry
, CSR_PROCESS
, ListLink
);
133 /* Move to the next entry */
134 NextEntry
= NextEntry
->Flink
;
136 /* Skip this process if it's already been processed */
137 if (CsrProcess
->Flags
& CsrProcessSkipShutdown
) continue;
139 /* Get the LUID of this Process */
140 Status
= CsrGetProcessLuid(CsrProcess
->ProcessHandle
, &ProcessLuid
);
142 /* Check if we didn't get access to the LUID */
143 if (Status
== STATUS_ACCESS_DENIED
)
145 /* FIXME: Check if we have any threads */
147 /\* Check if we have any threads *\/
148 if (CsrProcess->ThreadCount)
150 /\* Impersonate one of the threads and retry *\/
151 CsrThread = CONTAINING_RECORD(CsrProcess->ThreadList.Flink,
154 CsrImpersonateClient(CsrThread);
155 Status = CsrGetProcessLuid(NULL, &ProcessLuid);
161 if (!NT_SUCCESS(Status
))
163 /* We didn't have access, so skip it */
164 CsrProcess
->Flags
|= CsrProcessSkipShutdown
;
168 /* Check if this is the System LUID */
169 if ((/*IsSystemLuid =*/ RtlEqualLuid(&ProcessLuid
, &SystemLuid
)))
171 /* Mark this process */
172 CsrProcess
->ShutdownFlags
|= CsrShutdownSystem
;
174 else if (!(/*IsOurLuid =*/ RtlEqualLuid(&ProcessLuid
, CallerLuid
)))
176 /* Our LUID doesn't match with the caller's */
177 CsrProcess
->ShutdownFlags
|= CsrShutdownOther
;
180 /* Check if we're past the previous level */
181 // FIXME: if ((CsrProcess->ShutdownLevel > Level) || !(ReturnCsrProcess))
182 if (CsrProcess
->ShutdownLevel
> Level
/* || !ReturnCsrProcess */)
184 /* Update the level */
185 Level
= CsrProcess
->ShutdownLevel
;
187 /* Set the final process */
188 ReturnCsrProcess
= CsrProcess
;
192 /* Check if we found a process */
193 if (ReturnCsrProcess
)
195 /* Skip this one next time */
196 ReturnCsrProcess
->Flags
|= CsrProcessSkipShutdown
;
199 return ReturnCsrProcess
;
203 * @name CsrProcessRefcountZero
205 * The CsrProcessRefcountZero routine is executed when a CSR Process has lost
206 * all its active references. It removes and de-allocates the CSR Process.
209 * Pointer to the CSR Process that is to be deleted.
213 * @remarks Do not call this routine. It is reserved for the internal
214 * thread management routines when a CSR Process has lost all
217 * This routine is called with the Process Lock held.
222 CsrProcessRefcountZero(IN PCSR_PROCESS CsrProcess
)
224 ASSERT(ProcessStructureListLocked());
226 /* Remove the Process from the list */
227 CsrRemoveProcess(CsrProcess
);
229 /* Check if there's a session */
230 if (CsrProcess
->NtSession
)
232 /* Dereference the Session */
233 CsrDereferenceNtSession(CsrProcess
->NtSession
, 0);
236 /* Close the Client Port if there is one */
237 if (CsrProcess
->ClientPort
) NtClose(CsrProcess
->ClientPort
);
239 /* Close the process handle */
240 NtClose(CsrProcess
->ProcessHandle
);
242 /* Free the Proces Object */
243 CsrDeallocateProcess(CsrProcess
);
247 * @name CsrLockedDereferenceProcess
249 * The CsrLockedDereferenceProcess dereferences a CSR Process while the
250 * Process Lock is already being held.
253 * Pointer to the CSR Process to be dereferenced.
257 * @remarks This routine will return with the Process Lock held.
262 CsrLockedDereferenceProcess(PCSR_PROCESS CsrProcess
)
266 /* Decrease reference count */
267 LockCount
= --CsrProcess
->ReferenceCount
;
268 ASSERT(LockCount
>= 0);
271 /* Call the generic cleanup code */
272 DPRINT1("Should kill process: %p\n", CsrProcess
);
273 CsrAcquireProcessLock();
274 CsrProcessRefcountZero(CsrProcess
);
279 * @name CsrAllocateProcess
282 * The CsrAllocateProcess routine allocates a new CSR Process object.
284 * @return Pointer to the newly allocated CSR Process.
291 CsrAllocateProcess(VOID
)
293 PCSR_PROCESS CsrProcess
;
296 /* Calculate the amount of memory this should take */
297 TotalSize
= sizeof(CSR_PROCESS
) +
298 (CSR_SERVER_DLL_MAX
* sizeof(PVOID
)) +
299 CsrTotalPerProcessDataLength
;
301 /* Allocate a Process */
302 CsrProcess
= RtlAllocateHeap(CsrHeap
, HEAP_ZERO_MEMORY
, TotalSize
);
303 if (!CsrProcess
) return NULL
;
305 /* Handle the Sequence Number and protect against overflow */
306 CsrProcess
->SequenceNumber
= CsrProcessSequenceCount
++;
307 if (CsrProcessSequenceCount
< 5) CsrProcessSequenceCount
= 5;
309 /* Increase the reference count */
310 CsrLockedReferenceProcess(CsrProcess
);
312 /* Initialize the Thread List */
313 InitializeListHead(&CsrProcess
->ThreadList
);
315 /* Return the Process */
320 * @name CsrLockedReferenceProcess
322 * The CsrLockedReferenceProcess references a CSR Process while the
323 * Process Lock is already being held.
326 * Pointer to the CSR Process to be referenced.
330 * @remarks This routine will return with the Process Lock held.
335 CsrLockedReferenceProcess(IN PCSR_PROCESS CsrProcess
)
337 /* Increment the reference count */
338 ++CsrProcess
->ReferenceCount
;
342 * @name CsrInitializeProcessStructure
345 * The CsrInitializeProcessStructure routine sets up support for CSR Processes
346 * and CSR Threads by initializing our own CSR Root Process.
350 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
357 CsrInitializeProcessStructure(VOID
)
362 /* Initialize the Lock */
363 Status
= RtlInitializeCriticalSection(&CsrProcessLock
);
364 if (!NT_SUCCESS(Status
)) return Status
;
366 /* Set up the Root Process */
367 CsrRootProcess
= CsrAllocateProcess();
368 if (!CsrRootProcess
) return STATUS_NO_MEMORY
;
370 /* Set up the minimal information for it */
371 InitializeListHead(&CsrRootProcess
->ListLink
);
372 CsrRootProcess
->ProcessHandle
= (HANDLE
)-1;
373 CsrRootProcess
->ClientId
= NtCurrentTeb()->ClientId
;
375 /* Initialize the Thread Hash List */
376 for (i
= 0; i
< NUMBER_THREAD_HASH_BUCKETS
; i
++) InitializeListHead(&CsrThreadHashTable
[i
]);
378 /* Initialize the Wait Lock */
379 return RtlInitializeCriticalSection(&CsrWaitListsLock
);
383 * @name CsrDeallocateProcess
385 * The CsrDeallocateProcess frees the memory associated with a CSR Process.
388 * Pointer to the CSR Process to be freed.
392 * @remarks Do not call this routine. It is reserved for the internal
393 * thread management routines when a CSR Process has been cleanly
394 * dereferenced and killed.
399 CsrDeallocateProcess(IN PCSR_PROCESS CsrProcess
)
401 /* Free the process object from the heap */
402 RtlFreeHeap(CsrHeap
, 0, CsrProcess
);
406 * @name CsrRemoveProcess
408 * The CsrRemoveProcess function undoes a CsrInsertProcess operation and
409 * removes the CSR Process from the Process List and notifies Server DLLs
413 * Pointer to the CSR Process to remove.
422 CsrRemoveProcess(IN PCSR_PROCESS CsrProcess
)
424 PCSR_SERVER_DLL ServerDll
;
426 ASSERT(ProcessStructureListLocked());
428 /* Remove us from the Process List */
429 RemoveEntryList(&CsrProcess
->ListLink
);
431 /* Release the lock */
432 CsrReleaseProcessLock();
434 /* Loop every Server DLL */
435 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
437 /* Get the Server DLL */
438 ServerDll
= CsrLoadedServerDll
[i
];
440 /* Check if it's valid and if it has a Disconnect Callback */
441 if (ServerDll
&& ServerDll
->DisconnectCallback
)
444 ServerDll
->DisconnectCallback(CsrProcess
);
450 * @name CsrInsertProcess
452 * The CsrInsertProcess routine inserts a CSR Process into the Process List
453 * and notifies Server DLLs of the creation of a new CSR Process.
455 * @param ParentProcess
456 * Optional pointer to the Parent Process creating this CSR Process.
459 * Pointer to the CSR Process which is to be inserted.
468 CsrInsertProcess(IN PCSR_PROCESS ParentProcess OPTIONAL
,
469 IN PCSR_PROCESS CsrProcess
)
471 PCSR_SERVER_DLL ServerDll
;
473 ASSERT(ProcessStructureListLocked());
475 /* Insert it into the Root List */
476 InsertTailList(&CsrRootProcess
->ListLink
, &CsrProcess
->ListLink
);
478 /* Notify the Server DLLs */
479 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
481 /* Get the current Server DLL */
482 ServerDll
= CsrLoadedServerDll
[i
];
484 /* Make sure it's valid and that it has callback */
485 if (ServerDll
&& ServerDll
->NewProcessCallback
)
487 ServerDll
->NewProcessCallback(ParentProcess
, CsrProcess
);
493 /* PUBLIC FUNCTIONS ***********************************************************/
496 * @name CsrCreateProcess
499 * The CsrCreateProcess routine creates a CSR Process object for an NT Process.
502 * Handle to an existing NT Process to which to associate this
506 * Handle to an existing NT Thread to which to create its
507 * corresponding CSR Thread for this CSR Process.
510 * Pointer to the Client ID structure of the NT Process to associate
511 * with this CSR Process.
517 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
524 CsrCreateProcess(IN HANDLE hProcess
,
526 IN PCLIENT_ID ClientId
,
527 IN PCSR_NT_SESSION NtSession
,
529 IN PCLIENT_ID DebugCid
)
531 PCSR_THREAD CurrentThread
= CsrGetClientThread();
532 CLIENT_ID CurrentCid
;
533 PCSR_PROCESS CurrentProcess
;
534 PCSR_SERVER_DLL ServerDll
;
537 PCSR_PROCESS CsrProcess
;
539 PCSR_THREAD CsrThread
;
540 KERNEL_USER_TIMES KernelTimes
;
542 /* Get the current CID and lock Processes */
543 CurrentCid
= CurrentThread
->ClientId
;
544 CsrAcquireProcessLock();
546 /* Get the current CSR Thread */
547 CurrentThread
= CsrLocateThreadByClientId(&CurrentProcess
, &CurrentCid
);
550 /* We've failed to locate the thread */
551 CsrReleaseProcessLock();
552 return STATUS_THREAD_IS_TERMINATING
;
555 /* Allocate a new Process Object */
556 CsrProcess
= CsrAllocateProcess();
559 /* Couldn't allocate Process */
560 CsrReleaseProcessLock();
561 return STATUS_NO_MEMORY
;
564 /* Inherit the Process Data */
565 CurrentProcess
= CurrentThread
->Process
;
566 ProcessData
= &CsrProcess
->ServerData
[CSR_SERVER_DLL_MAX
];
567 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
569 /* Get the current Server */
570 ServerDll
= CsrLoadedServerDll
[i
];
572 /* Check if the DLL is Loaded and has Per Process Data */
573 if (ServerDll
&& ServerDll
->SizeOfProcessData
)
575 /* Set the pointer */
576 CsrProcess
->ServerData
[i
] = ProcessData
;
579 RtlMoveMemory(ProcessData
,
580 CurrentProcess
->ServerData
[i
],
581 ServerDll
->SizeOfProcessData
);
583 /* Update next data pointer */
584 ProcessData
= (PVOID
)((ULONG_PTR
)ProcessData
+
585 ServerDll
->SizeOfProcessData
);
589 /* No data for this Server */
590 CsrProcess
->ServerData
[i
] = NULL
;
594 /* Set the Exception port for us */
595 Status
= NtSetInformationProcess(hProcess
,
596 ProcessExceptionPort
,
599 if (!NT_SUCCESS(Status
))
602 CsrDeallocateProcess(CsrProcess
);
603 CsrReleaseProcessLock();
604 return STATUS_NO_MEMORY
;
607 /* Check if CreateProcess got CREATE_NEW_PROCESS_GROUP */
608 if ((Flags
& CsrProcessCreateNewGroup
) == 0)
610 /* Create new data */
611 CsrProcess
->ProcessGroupId
= HandleToUlong(ClientId
->UniqueProcess
);
612 CsrProcess
->ProcessGroupSequence
= CsrProcess
->SequenceNumber
;
616 /* Copy it from the current process */
617 CsrProcess
->ProcessGroupId
= CurrentProcess
->ProcessGroupId
;
618 CsrProcess
->ProcessGroupSequence
= CurrentProcess
->ProcessGroupSequence
;
621 /* Check if this is a console process */
622 if (Flags
& CsrProcessIsConsoleApp
) CsrProcess
->Flags
|= CsrProcessIsConsoleApp
;
624 /* Mask out non-debug flags */
625 Flags
&= ~(CsrProcessIsConsoleApp
| CsrProcessCreateNewGroup
| CsrProcessPriorityFlags
);
627 /* Check if every process will be debugged */
628 if (!(Flags
) && (CurrentProcess
->DebugFlags
& CsrDebugProcessChildren
))
630 /* Pass it on to the current process */
631 CsrProcess
->DebugFlags
= CsrDebugProcessChildren
;
632 CsrProcess
->DebugCid
= CurrentProcess
->DebugCid
;
635 /* Check if Debugging was used on this process */
636 if ((Flags
& (CsrDebugOnlyThisProcess
| CsrDebugProcessChildren
)) && (DebugCid
))
638 /* Save the debug flag used */
639 CsrProcess
->DebugFlags
= Flags
;
642 CsrProcess
->DebugCid
= *DebugCid
;
645 /* Check if Debugging is enabled */
646 if (CsrProcess
->DebugFlags
)
648 /* Set the Debug Port for us */
649 Status
= NtSetInformationProcess(hProcess
,
653 ASSERT(NT_SUCCESS(Status
));
654 if (!NT_SUCCESS(Status
))
657 CsrDeallocateProcess(CsrProcess
);
658 CsrReleaseProcessLock();
659 return STATUS_NO_MEMORY
;
663 /* Get the Thread Create Time */
664 Status
= NtQueryInformationThread(hThread
,
669 if (!NT_SUCCESS(Status
))
672 CsrDeallocateProcess(CsrProcess
);
673 CsrReleaseProcessLock();
674 return STATUS_NO_MEMORY
;
677 /* Allocate a CSR Thread Structure */
678 CsrThread
= CsrAllocateThread(CsrProcess
);
682 CsrDeallocateProcess(CsrProcess
);
683 CsrReleaseProcessLock();
684 return STATUS_NO_MEMORY
;
687 /* Save the data we have */
688 CsrThread
->CreateTime
= KernelTimes
.CreateTime
;
689 CsrThread
->ClientId
= *ClientId
;
690 CsrThread
->ThreadHandle
= hThread
;
691 ProtectHandle(hThread
);
692 CsrThread
->Flags
= 0;
694 /* Insert the Thread into the Process */
695 Status
= CsrInsertThread(CsrProcess
, CsrThread
);
696 if (!NT_SUCCESS(Status
))
699 CsrDeallocateProcess(CsrProcess
);
700 CsrDeallocateThread(CsrThread
);
701 CsrReleaseProcessLock();
705 /* Reference the session */
706 CsrReferenceNtSession(NtSession
);
707 CsrProcess
->NtSession
= NtSession
;
709 /* Setup Process Data */
710 CsrProcess
->ClientId
= *ClientId
;
711 CsrProcess
->ProcessHandle
= hProcess
;
712 CsrProcess
->ShutdownLevel
= 0x280;
714 /* Set the Priority to Background */
715 CsrSetBackgroundPriority(CsrProcess
);
717 /* Insert the Process */
718 CsrInsertProcess(CurrentProcess
, CsrProcess
);
720 /* Release lock and return */
721 CsrReleaseProcessLock();
726 * @name CsrDebugProcess
729 * The CsrDebugProcess routine is deprecated in NT 5.1 and higher. It is
730 * exported only for compatibility with older CSR Server DLLs.
737 * @remarks Deprecated.
742 CsrDebugProcess(IN PCSR_PROCESS CsrProcess
)
744 /* CSR does not handle debugging anymore */
745 DPRINT("CSRSRV: %s(0x%p) called\n", __FUNCTION__
, CsrProcess
);
746 return STATUS_UNSUCCESSFUL
;
750 * @name CsrDebugProcessStop
753 * The CsrDebugProcessStop routine is deprecated in NT 5.1 and higher. It is
754 * exported only for compatibility with older CSR Server DLLs.
761 * @remarks Deprecated.
766 CsrDebugProcessStop(IN PCSR_PROCESS CsrProcess
)
768 /* CSR does not handle debugging anymore */
769 DPRINT("CSRSRV: %s(0x%p) called\n", __FUNCTION__
, CsrProcess
);
770 return STATUS_UNSUCCESSFUL
;
774 * @name CsrDereferenceProcess
777 * The CsrDereferenceProcess routine removes a reference from a CSR Process.
780 * Pointer to the CSR Process to dereference.
784 * @remarks If the reference count has reached zero (ie: the CSR Process has
785 * no more active references), it will be deleted.
790 CsrDereferenceProcess(IN PCSR_PROCESS CsrProcess
)
794 /* Acquire process lock */
795 CsrAcquireProcessLock();
797 /* Decrease reference count */
798 LockCount
= --CsrProcess
->ReferenceCount
;
799 ASSERT(LockCount
>= 0);
802 /* Call the generic cleanup code */
803 CsrProcessRefcountZero(CsrProcess
);
807 /* Just release the lock */
808 CsrReleaseProcessLock();
813 * @name CsrDestroyProcess
816 * The CsrDestroyProcess routine destroys the CSR Process corresponding to
820 * Pointer to the Client ID Structure corresponding to the CSR
821 * Process which is about to be destroyed.
826 * @return STATUS_SUCCESS in case of success, STATUS_THREAD_IS_TERMINATING
827 * if the CSR Process is already terminating.
834 CsrDestroyProcess(IN PCLIENT_ID Cid
,
835 IN NTSTATUS ExitStatus
)
837 PCSR_THREAD CsrThread
;
838 PCSR_PROCESS CsrProcess
;
839 CLIENT_ID ClientId
= *Cid
;
840 PLIST_ENTRY NextEntry
;
843 CsrAcquireProcessLock();
845 /* Find the thread */
846 CsrThread
= CsrLocateThreadByClientId(&CsrProcess
, &ClientId
);
848 /* Make sure we got one back, and that it's not already gone */
849 if (!(CsrThread
) || (CsrProcess
->Flags
& CsrProcessTerminating
))
851 /* Release the lock and return failure */
852 CsrReleaseProcessLock();
853 return STATUS_THREAD_IS_TERMINATING
;
856 /* Set the terminated flag */
857 CsrProcess
->Flags
|= CsrProcessTerminating
;
859 /* Get the List Pointers */
860 NextEntry
= CsrProcess
->ThreadList
.Flink
;
861 while (NextEntry
!= &CsrProcess
->ThreadList
)
863 /* Get the current thread entry */
864 CsrThread
= CONTAINING_RECORD(NextEntry
, CSR_THREAD
, Link
);
866 /* Move to the next entry */
867 NextEntry
= NextEntry
->Flink
;
869 /* Make sure the thread isn't already dead */
870 if (CsrThread
->Flags
& CsrThreadTerminated
)
872 /* Go the the next thread */
876 /* Set the Terminated flag */
877 CsrThread
->Flags
|= CsrThreadTerminated
;
879 /* Acquire the Wait Lock */
880 CsrAcquireWaitLock();
882 /* Do we have an active wait block? */
883 if (CsrThread
->WaitBlock
)
885 /* Notify waiters of termination */
886 CsrNotifyWaitBlock(CsrThread
->WaitBlock
,
890 CsrProcessTerminating
,
894 /* Release the Wait Lock */
895 CsrReleaseWaitLock();
897 /* Dereference the thread */
898 CsrLockedDereferenceThread(CsrThread
);
901 /* Release the Process Lock and return success */
902 CsrReleaseProcessLock();
903 return STATUS_SUCCESS
;
907 * @name CsrGetProcessLuid
910 * The CsrGetProcessLuid routine gets the LUID of the given process.
913 * Optional handle to the process whose LUID should be returned.
916 * Pointer to a LUID Pointer which will receive the CSR Process' LUID.
918 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
920 * @remarks If hProcess is not supplied, then the current thread's token will
921 * be used. If that too is missing, then the current process' token
927 CsrGetProcessLuid(IN HANDLE hProcess OPTIONAL
,
930 HANDLE hToken
= NULL
;
933 PTOKEN_STATISTICS TokenStats
;
935 /* Check if we have a handle to a CSR Process */
938 /* We don't, so try opening the Thread's Token */
939 Status
= NtOpenThreadToken(NtCurrentThread(),
944 /* Check for success */
945 if (!NT_SUCCESS(Status
))
947 /* If we got some other failure, then return and quit */
948 if (Status
!= STATUS_NO_TOKEN
) return Status
;
950 /* We don't have a Thread Token, use a Process Token */
951 hProcess
= NtCurrentProcess();
956 /* Check if we have a token by now */
959 /* No token yet, so open the Process Token */
960 Status
= NtOpenProcessToken(hProcess
,
963 if (!NT_SUCCESS(Status
))
965 /* Still no token, return the error */
970 /* Now get the size we'll need for the Token Information */
971 Status
= NtQueryInformationToken(hToken
,
977 /* Allocate memory for the Token Info */
978 if (!(TokenStats
= RtlAllocateHeap(CsrHeap
, 0, Length
)))
980 /* Fail and close the token */
982 return STATUS_NO_MEMORY
;
985 /* Now query the information */
986 Status
= NtQueryInformationToken(hToken
,
992 /* Close the handle */
995 /* Check for success */
996 if (NT_SUCCESS(Status
))
998 /* Return the LUID */
999 *Luid
= TokenStats
->AuthenticationId
;
1002 /* Free the query information */
1003 RtlFreeHeap(CsrHeap
, 0, TokenStats
);
1005 /* Return the Status */
1010 * @name CsrImpersonateClient
1013 * The CsrImpersonateClient will impersonate the given CSR Thread.
1016 * Pointer to the CSR Thread to impersonate.
1018 * @return TRUE if impersonation succeeded, FALSE otherwise.
1020 * @remarks Impersonation can be recursive.
1025 CsrImpersonateClient(IN PCSR_THREAD CsrThread
)
1028 PCSR_THREAD CurrentThread
= CsrGetClientThread();
1030 /* Use the current thread if none given */
1031 if (!CsrThread
) CsrThread
= CurrentThread
;
1033 /* Still no thread, something is wrong */
1041 Status
= NtImpersonateThread(NtCurrentThread(),
1042 CsrThread
->ThreadHandle
,
1045 if (!NT_SUCCESS(Status
))
1048 DPRINT1("CSRSS: Can't impersonate client thread - Status = %lx\n", Status
);
1049 // if (Status != STATUS_BAD_IMPERSONATION_LEVEL) DbgBreakPoint();
1053 /* Increase the impersonation count for the current thread */
1054 if (CurrentThread
) ++CurrentThread
->ImpersonationCount
;
1056 /* Return Success */
1061 * @name CsrLockProcessByClientId
1064 * The CsrLockProcessByClientId routine locks the CSR Process corresponding
1065 * to the given Process ID and optionally returns it.
1068 * Process ID corresponding to the CSR Process which will be locked.
1071 * Optional pointer to a CSR Process pointer which will hold the
1072 * CSR Process corresponding to the given Process ID.
1074 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
1076 * @remarks Locking a CSR Process is defined as acquiring an extra
1077 * reference to it and returning with the Process Lock held.
1082 CsrLockProcessByClientId(IN HANDLE Pid
,
1083 OUT PCSR_PROCESS
*CsrProcess
)
1085 PLIST_ENTRY NextEntry
;
1086 PCSR_PROCESS CurrentProcess
= NULL
;
1087 NTSTATUS Status
= STATUS_UNSUCCESSFUL
;
1089 /* Acquire the lock */
1090 CsrAcquireProcessLock();
1092 /* Assume failure */
1093 ASSERT(CsrProcess
!= NULL
);
1096 /* Setup the List Pointers */
1097 NextEntry
= &CsrRootProcess
->ListLink
;
1100 /* Get the Process */
1101 CurrentProcess
= CONTAINING_RECORD(NextEntry
, CSR_PROCESS
, ListLink
);
1103 /* Check for PID Match */
1104 if (CurrentProcess
->ClientId
.UniqueProcess
== Pid
)
1106 Status
= STATUS_SUCCESS
;
1110 /* Move to the next entry */
1111 NextEntry
= NextEntry
->Flink
;
1112 } while (NextEntry
!= &CsrRootProcess
->ListLink
);
1114 /* Check if we didn't find it in the list */
1115 if (!NT_SUCCESS(Status
))
1117 /* Nothing found, release the lock */
1118 CsrReleaseProcessLock();
1122 /* Lock the found process and return it */
1123 CsrLockedReferenceProcess(CurrentProcess
);
1124 *CsrProcess
= CurrentProcess
;
1127 /* Return the result */
1132 * @name CsrRevertToSelf
1135 * The CsrRevertToSelf routine will attempt to remove an active impersonation.
1139 * @return TRUE if the reversion was succesful, FALSE otherwise.
1141 * @remarks Impersonation can be recursive; as such, the impersonation token
1142 * will only be deleted once the CSR Thread's impersonaton count
1148 CsrRevertToSelf(VOID
)
1151 PCSR_THREAD CurrentThread
= CsrGetClientThread();
1152 HANDLE ImpersonationToken
= NULL
;
1154 /* Check if we have a Current Thread */
1157 /* Make sure impersonation is on */
1158 if (!CurrentThread
->ImpersonationCount
)
1160 DPRINT1("CSRSS: CsrRevertToSelf called while not impersonating\n");
1164 else if ((--CurrentThread
->ImpersonationCount
) > 0)
1166 /* Success; impersonation count decreased but still not zero */
1171 /* Impersonation has been totally removed, revert to ourselves */
1172 Status
= NtSetInformationThread(NtCurrentThread(),
1173 ThreadImpersonationToken
,
1174 &ImpersonationToken
,
1177 /* Return TRUE or FALSE */
1178 return NT_SUCCESS(Status
);
1182 * @name CsrSetBackgroundPriority
1185 * The CsrSetBackgroundPriority routine sets the priority for the given CSR
1186 * Process as a Background priority.
1189 * Pointer to the CSR Process whose priority will be modified.
1198 CsrSetBackgroundPriority(IN PCSR_PROCESS CsrProcess
)
1200 PROCESS_PRIORITY_CLASS PriorityClass
;
1202 /* Set the Foreground bit off */
1203 PriorityClass
.Foreground
= FALSE
;
1205 /* Set the new Priority */
1206 NtSetInformationProcess(CsrProcess
->ProcessHandle
,
1207 ProcessPriorityClass
,
1209 sizeof(PriorityClass
));
1213 * @name CsrSetForegroundPriority
1216 * The CsrSetForegroundPriority routine sets the priority for the given CSR
1217 * Process as a Foreground priority.
1220 * Pointer to the CSR Process whose priority will be modified.
1229 CsrSetForegroundPriority(IN PCSR_PROCESS CsrProcess
)
1231 PROCESS_PRIORITY_CLASS PriorityClass
;
1233 /* Set the Foreground bit on */
1234 PriorityClass
.Foreground
= TRUE
;
1236 /* Set the new Priority */
1237 NtSetInformationProcess(CsrProcess
->ProcessHandle
,
1238 ProcessPriorityClass
,
1240 sizeof(PriorityClass
));
1244 * @name CsrShutdownProcesses
1247 * The CsrShutdownProcesses routine shuts down every CSR Process possible
1248 * and calls each Server DLL's shutdown notification.
1251 * Pointer to the LUID of the CSR Process that is ordering the
1255 * Flags to send to the shutdown notification routine.
1257 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
1264 CsrShutdownProcesses(IN PLUID CallerLuid
,
1267 PLIST_ENTRY NextEntry
;
1268 PCSR_PROCESS CsrProcess
;
1272 PCSR_SERVER_DLL ServerDll
;
1273 ULONG Result
= 0; /* Intentionally invalid enumeratee to silence compiler warning */
1275 /* Acquire process lock */
1276 CsrAcquireProcessLock();
1278 /* Add shutdown flag */
1279 CsrRootProcess
->ShutdownFlags
|= CsrShutdownSystem
;
1281 /* Get the list pointers */
1282 NextEntry
= CsrRootProcess
->ListLink
.Flink
;
1283 while (NextEntry
!= &CsrRootProcess
->ListLink
)
1285 /* Get the Process */
1286 CsrProcess
= CONTAINING_RECORD(NextEntry
, CSR_PROCESS
, ListLink
);
1288 /* Move to the next entry */
1289 NextEntry
= NextEntry
->Flink
;
1291 /* Remove the skip flag, set shutdown flags to 0 */
1292 CsrProcess
->Flags
&= ~CsrProcessSkipShutdown
;
1293 CsrProcess
->ShutdownFlags
= 0;
1296 /* Set shudown Priority */
1297 CsrSetToShutdownPriority();
1302 /* Find the next process to shutdown */
1303 CsrProcess
= FindProcessForShutdown(CallerLuid
);
1304 if (!CsrProcess
) break;
1306 /* Increase reference to process */
1307 CsrLockedReferenceProcess(CsrProcess
);
1312 /* Loop all the servers */
1313 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
1315 /* Get the current server */
1316 ServerDll
= CsrLoadedServerDll
[i
];
1318 /* Check if it's valid and if it has a Shutdown Process Callback */
1319 if (ServerDll
&& ServerDll
->ShutdownProcessCallback
)
1321 /* Release the lock, make the callback, and acquire it back */
1322 CsrReleaseProcessLock();
1323 Result
= ServerDll
->ShutdownProcessCallback(CsrProcess
,
1326 CsrAcquireProcessLock();
1328 /* Check the result */
1329 if (Result
== CsrShutdownCsrProcess
)
1331 /* The callback unlocked the process */
1334 else if (Result
== CsrShutdownCancelled
)
1336 /* Check if this was a forced shutdown */
1337 if (Flags
& EWX_FORCE
)
1339 DPRINT1("Process %x cancelled forced shutdown (Dll = %d)\n",
1340 CsrProcess
->ClientId
.UniqueProcess
, i
);
1344 /* Shutdown was cancelled, unlock and exit */
1345 CsrReleaseProcessLock();
1346 Status
= STATUS_CANCELLED
;
1352 /* No matches during the first try, so loop again */
1353 if ((FirstTry
) && (Result
== CsrShutdownNonCsrProcess
))
1359 /* Second try, break out */
1363 /* We've reached the final loop here, so dereference */
1364 if (i
== CSR_SERVER_DLL_MAX
) CsrLockedDereferenceProcess(CsrProcess
);
1368 CsrReleaseProcessLock();
1369 Status
= STATUS_SUCCESS
;
1372 /* Return to normal priority */
1373 CsrSetToNormalPriority();
1378 /* HACK: Temporary hack. This is really "CsrShutdownProcesses", mostly. Used by winsrv */
1382 CsrEnumProcesses(IN CSRSS_ENUM_PROCESS_PROC EnumProc
,
1385 PVOID
* RealContext
= (PVOID
*)Context
;
1386 PLUID CallerLuid
= RealContext
[0];
1387 PCSR_PROCESS CsrProcess
= NULL
;
1388 NTSTATUS Status
= STATUS_UNSUCCESSFUL
;
1390 PLIST_ENTRY NextEntry
;
1393 /* Acquire process lock */
1394 CsrAcquireProcessLock();
1396 /* Get the list pointers */
1397 NextEntry
= CsrRootProcess
->ListLink
.Flink
;
1398 while (NextEntry
!= &CsrRootProcess
->ListLink
)
1400 /* Get the Process */
1401 CsrProcess
= CONTAINING_RECORD(NextEntry
, CSR_PROCESS
, ListLink
);
1403 /* Move to the next entry */
1404 NextEntry
= NextEntry
->Flink
;
1406 /* Remove the skip flag, set shutdown flags to 0 */
1407 CsrProcess
->Flags
&= ~CsrProcessSkipShutdown
;
1408 CsrProcess
->ShutdownFlags
= 0;
1411 /* Set shudown Priority */
1412 CsrSetToShutdownPriority();
1414 /* Loop all processes */
1415 //DPRINT1("Enumerating for LUID: %lx %lx\n", CallerLuid->HighPart, CallerLuid->LowPart);
1420 /* Find the next process to shutdown */
1422 if (!(CsrProcess
= FindProcessForShutdown(CallerLuid
)))
1425 CsrReleaseProcessLock();
1426 Status
= STATUS_SUCCESS
;
1431 /* Release the lock, make the callback, and acquire it back */
1432 //DPRINT1("Found process: %lx\n", CsrProcess->ClientId.UniqueProcess);
1433 CsrReleaseProcessLock();
1434 Result
= (ULONG
)EnumProc(CsrProcess
, (PVOID
)((ULONG_PTR
)Context
| FirstTry
));
1435 CsrAcquireProcessLock();
1437 /* Check the result */
1438 //DPRINT1("Result: %d\n", Result);
1439 if (Result
== CsrShutdownCsrProcess
)
1441 /* The callback unlocked the process */
1444 else if (Result
== CsrShutdownNonCsrProcess
)
1446 /* A non-CSR process, the callback didn't touch it */
1449 else if (Result
== CsrShutdownCancelled
)
1451 /* Shutdown was cancelled, unlock and exit */
1452 CsrReleaseProcessLock();
1453 Status
= STATUS_CANCELLED
;
1457 /* No matches during the first try, so loop again */
1458 if (FirstTry
&& Result
== CsrShutdownNonCsrProcess
)
1466 /* Return to normal priority */
1467 CsrSetToNormalPriority();
1473 * @name CsrUnlockProcess
1476 * The CsrUnlockProcess undoes a previous CsrLockProcessByClientId operation.
1479 * Pointer to a previously locked CSR Process.
1481 * @return STATUS_SUCCESS.
1483 * @remarks This routine must be called with the Process Lock held.
1488 CsrUnlockProcess(IN PCSR_PROCESS CsrProcess
)
1490 /* Dereference the process */
1491 CsrLockedDereferenceProcess(CsrProcess
);
1493 /* Release the lock and return */
1494 CsrReleaseProcessLock();
1495 return STATUS_SUCCESS
;