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 CsrSetToNormalPriority
37 * The CsrSetToNormalPriority routine sets the current NT Process'
38 * priority to the normal priority for CSR Processes.
44 * @remarks The "Normal" Priority corresponds to the Normal Foreground
45 * Priority (9) plus a boost of 4.
50 CsrSetToNormalPriority(VOID
)
52 KPRIORITY BasePriority
= (8 + 1) + 4;
54 /* Set the Priority */
55 NtSetInformationProcess(NtCurrentProcess(),
62 * @name CsrSetToShutdownPriority
64 * The CsrSetToShutdownPriority 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 Foreground
73 * Priority (9) plus a boost of 6.
78 CsrSetToShutdownPriority(VOID
)
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 CsrAcquireProcessLock();
272 CsrProcessRefcountZero(CsrProcess
);
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 CsrLockedReferenceProcess(CsrProcess
);
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 otherwise.
355 CsrInitializeProcessStructure(VOID
)
360 /* Initialize the Lock */
361 Status
= RtlInitializeCriticalSection(&CsrProcessLock
);
362 if (!NT_SUCCESS(Status
)) return Status
;
364 /* Set up the Root Process */
365 CsrRootProcess
= CsrAllocateProcess();
366 if (!CsrRootProcess
) return STATUS_NO_MEMORY
;
368 /* Set up the minimal information for it */
369 InitializeListHead(&CsrRootProcess
->ListLink
);
370 CsrRootProcess
->ProcessHandle
= (HANDLE
)-1;
371 CsrRootProcess
->ClientId
= NtCurrentTeb()->ClientId
;
373 /* Initialize the Thread Hash List */
374 for (i
= 0; i
< 256; i
++) InitializeListHead(&CsrThreadHashTable
[i
]);
376 /* Initialize the Wait Lock */
377 return RtlInitializeCriticalSection(&CsrWaitListsLock
);
381 * @name CsrDeallocateProcess
383 * The CsrDeallocateProcess frees the memory associated with a CSR Process.
386 * Pointer to the CSR Process to be freed.
390 * @remarks Do not call this routine. It is reserved for the internal
391 * thread management routines when a CSR Process has been cleanly
392 * dereferenced and killed.
397 CsrDeallocateProcess(IN PCSR_PROCESS CsrProcess
)
399 /* Free the process object from the heap */
400 RtlFreeHeap(CsrHeap
, 0, CsrProcess
);
404 * @name CsrRemoveProcess
406 * The CsrRemoveProcess function undoes a CsrInsertProcess operation and
407 * removes the CSR Process from the Process List and notifies Server DLLs
411 * Pointer to the CSR Process to remove.
420 CsrRemoveProcess(IN PCSR_PROCESS CsrProcess
)
422 PCSR_SERVER_DLL ServerDll
;
424 ASSERT(ProcessStructureListLocked());
426 /* Remove us from the Process List */
427 RemoveEntryList(&CsrProcess
->ListLink
);
429 /* Release the lock */
430 CsrReleaseProcessLock();
432 /* Loop every Server DLL */
433 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
435 /* Get the Server DLL */
436 ServerDll
= CsrLoadedServerDll
[i
];
438 /* Check if it's valid and if it has a Disconnect Callback */
439 if (ServerDll
&& ServerDll
->DisconnectCallback
)
442 ServerDll
->DisconnectCallback(CsrProcess
);
448 * @name CsrInsertProcess
450 * The CsrInsertProcess routine inserts a CSR Process into the Process List
451 * and notifies Server DLLs of the creation of a new CSR Process.
453 * @param ParentProcess
454 * Optional pointer to the Parent Process creating this CSR Process.
457 * Pointer to the CSR Process which is to be inserted.
466 CsrInsertProcess(IN PCSR_PROCESS ParentProcess OPTIONAL
,
467 IN PCSR_PROCESS CsrProcess
)
469 PCSR_SERVER_DLL ServerDll
;
471 ASSERT(ProcessStructureListLocked());
473 /* Insert it into the Root List */
474 InsertTailList(&CsrRootProcess
->ListLink
, &CsrProcess
->ListLink
);
476 /* Notify the Server DLLs */
477 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
479 /* Get the current Server DLL */
480 ServerDll
= CsrLoadedServerDll
[i
];
482 /* Make sure it's valid and that it has callback */
483 if (ServerDll
&& ServerDll
->NewProcessCallback
)
485 ServerDll
->NewProcessCallback(ParentProcess
, CsrProcess
);
491 /* PUBLIC FUNCTIONS ***********************************************************/
494 * @name CsrCreateProcess
497 * The CsrCreateProcess routine creates a CSR Process object for an NT Process.
500 * Handle to an existing NT Process to which to associate this
504 * Handle to an existing NT Thread to which to create its
505 * corresponding CSR Thread for this CSR Process.
508 * Pointer to the Client ID structure of the NT Process to associate
509 * with this CSR Process.
515 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
522 CsrCreateProcess(IN HANDLE hProcess
,
524 IN PCLIENT_ID ClientId
,
525 IN PCSR_NT_SESSION NtSession
,
527 IN PCLIENT_ID DebugCid
)
529 PCSR_THREAD CurrentThread
= CsrGetClientThread();
530 CLIENT_ID CurrentCid
;
531 PCSR_PROCESS CurrentProcess
;
532 PCSR_SERVER_DLL ServerDll
;
535 PCSR_PROCESS CsrProcess
;
537 PCSR_THREAD CsrThread
;
538 KERNEL_USER_TIMES KernelTimes
;
540 /* Get the current CID and lock Processes */
541 CurrentCid
= CurrentThread
->ClientId
;
542 CsrAcquireProcessLock();
544 /* Get the current CSR Thread */
545 CurrentThread
= CsrLocateThreadByClientId(&CurrentProcess
, &CurrentCid
);
548 /* We've failed to locate the thread */
549 CsrReleaseProcessLock();
550 return STATUS_THREAD_IS_TERMINATING
;
553 /* Allocate a new Process Object */
554 CsrProcess
= CsrAllocateProcess();
557 /* Couldn't allocate Process */
558 CsrReleaseProcessLock();
559 return STATUS_NO_MEMORY
;
562 /* Inherit the Process Data */
563 CurrentProcess
= CurrentThread
->Process
;
564 ProcessData
= &CsrProcess
->ServerData
[CSR_SERVER_DLL_MAX
];
565 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
567 /* Get the current Server */
568 ServerDll
= CsrLoadedServerDll
[i
];
570 /* Check if the DLL is Loaded and has Per Process Data */
571 if (ServerDll
&& ServerDll
->SizeOfProcessData
)
573 /* Set the pointer */
574 CsrProcess
->ServerData
[i
] = ProcessData
;
577 RtlMoveMemory(ProcessData
,
578 CurrentProcess
->ServerData
[i
],
579 ServerDll
->SizeOfProcessData
);
581 /* Update next data pointer */
582 ProcessData
= (PVOID
)((ULONG_PTR
)ProcessData
+
583 ServerDll
->SizeOfProcessData
);
587 /* No data for this Server */
588 CsrProcess
->ServerData
[i
] = NULL
;
592 /* Set the Exception port for us */
593 Status
= NtSetInformationProcess(hProcess
,
594 ProcessExceptionPort
,
597 if (!NT_SUCCESS(Status
))
600 CsrDeallocateProcess(CsrProcess
);
601 CsrReleaseProcessLock();
602 return STATUS_NO_MEMORY
;
605 /* Check if CreateProcess got CREATE_NEW_PROCESS_GROUP */
606 if ((Flags
& CsrProcessCreateNewGroup
) == 0)
608 /* Create new data */
609 CsrProcess
->ProcessGroupId
= HandleToUlong(ClientId
->UniqueProcess
);
610 CsrProcess
->ProcessGroupSequence
= CsrProcess
->SequenceNumber
;
614 /* Copy it from the current process */
615 CsrProcess
->ProcessGroupId
= CurrentProcess
->ProcessGroupId
;
616 CsrProcess
->ProcessGroupSequence
= CurrentProcess
->ProcessGroupSequence
;
619 /* Check if this is a console process */
620 if (Flags
& CsrProcessIsConsoleApp
) CsrProcess
->Flags
|= CsrProcessIsConsoleApp
;
622 /* Mask out non-debug flags */
623 Flags
&= ~(CsrProcessIsConsoleApp
| CsrProcessCreateNewGroup
| CsrProcessPriorityFlags
);
625 /* Check if every process will be debugged */
626 if (!(Flags
) && (CurrentProcess
->DebugFlags
& CsrDebugProcessChildren
))
628 /* Pass it on to the current process */
629 CsrProcess
->DebugFlags
= CsrDebugProcessChildren
;
630 CsrProcess
->DebugCid
= CurrentProcess
->DebugCid
;
633 /* Check if Debugging was used on this process */
634 if ((Flags
& (CsrDebugOnlyThisProcess
| CsrDebugProcessChildren
)) && (DebugCid
))
636 /* Save the debug flag used */
637 CsrProcess
->DebugFlags
= Flags
;
640 CsrProcess
->DebugCid
= *DebugCid
;
643 /* Check if Debugging is enabled */
644 if (CsrProcess
->DebugFlags
)
646 /* Set the Debug Port for us */
647 Status
= NtSetInformationProcess(hProcess
,
651 ASSERT(NT_SUCCESS(Status
));
652 if (!NT_SUCCESS(Status
))
655 CsrDeallocateProcess(CsrProcess
);
656 CsrReleaseProcessLock();
657 return STATUS_NO_MEMORY
;
661 /* Get the Thread Create Time */
662 Status
= NtQueryInformationThread(hThread
,
667 if (!NT_SUCCESS(Status
))
670 CsrDeallocateProcess(CsrProcess
);
671 CsrReleaseProcessLock();
672 return STATUS_NO_MEMORY
;
675 /* Allocate a CSR Thread Structure */
676 CsrThread
= CsrAllocateThread(CsrProcess
);
680 CsrDeallocateProcess(CsrProcess
);
681 CsrReleaseProcessLock();
682 return STATUS_NO_MEMORY
;
685 /* Save the data we have */
686 CsrThread
->CreateTime
= KernelTimes
.CreateTime
;
687 CsrThread
->ClientId
= *ClientId
;
688 CsrThread
->ThreadHandle
= hThread
;
689 ProtectHandle(hThread
);
690 CsrThread
->Flags
= 0;
692 /* Insert the Thread into the Process */
693 CsrInsertThread(CsrProcess
, CsrThread
);
695 /* Reference the session */
696 CsrReferenceNtSession(NtSession
);
697 CsrProcess
->NtSession
= NtSession
;
699 /* Setup Process Data */
700 CsrProcess
->ClientId
= *ClientId
;
701 CsrProcess
->ProcessHandle
= hProcess
;
702 CsrProcess
->ShutdownLevel
= 0x280;
704 /* Set the Priority to Background */
705 CsrSetBackgroundPriority(CsrProcess
);
707 /* Insert the Process */
708 CsrInsertProcess(CurrentProcess
, CsrProcess
);
710 /* Release lock and return */
711 CsrReleaseProcessLock();
716 * @name CsrDebugProcess
719 * The CsrDebugProcess routine is deprecated in NT 5.1 and higher. It is
720 * exported only for compatibility with older CSR Server DLLs.
727 * @remarks Deprecated.
732 CsrDebugProcess(IN PCSR_PROCESS CsrProcess
)
734 /* CSR does not handle debugging anymore */
735 DPRINT("CSRSRV: %s(%08lx) called\n", __FUNCTION__
, CsrProcess
);
736 return STATUS_UNSUCCESSFUL
;
740 * @name CsrDebugProcessStop
743 * The CsrDebugProcessStop routine is deprecated in NT 5.1 and higher. It is
744 * exported only for compatibility with older CSR Server DLLs.
751 * @remarks Deprecated.
756 CsrDebugProcessStop(IN PCSR_PROCESS CsrProcess
)
758 /* CSR does not handle debugging anymore */
759 DPRINT("CSRSRV: %s(%08lx) called\n", __FUNCTION__
, CsrProcess
);
760 return STATUS_UNSUCCESSFUL
;
764 * @name CsrDereferenceProcess
767 * The CsrDereferenceProcess routine removes a reference from a CSR Process.
770 * Pointer to the CSR Process to dereference.
774 * @remarks If the reference count has reached zero (ie: the CSR Process has
775 * no more active references), it will be deleted.
780 CsrDereferenceProcess(IN PCSR_PROCESS CsrProcess
)
784 /* Acquire process lock */
785 CsrAcquireProcessLock();
787 /* Decrease reference count */
788 LockCount
= --CsrProcess
->ReferenceCount
;
789 ASSERT(LockCount
>= 0);
792 /* Call the generic cleanup code */
793 CsrProcessRefcountZero(CsrProcess
);
797 /* Just release the lock */
798 CsrReleaseProcessLock();
803 * @name CsrDestroyProcess
806 * The CsrDestroyProcess routine destroys the CSR Process corresponding to
810 * Pointer to the Client ID Structure corresponding to the CSR
811 * Process which is about to be destroyed.
816 * @return STATUS_SUCCESS in case of success, STATUS_THREAD_IS_TERMINATING
817 * if the CSR Process is already terminating.
824 CsrDestroyProcess(IN PCLIENT_ID Cid
,
825 IN NTSTATUS ExitStatus
)
827 PCSR_THREAD CsrThread
;
828 PCSR_PROCESS CsrProcess
;
829 CLIENT_ID ClientId
= *Cid
;
830 PLIST_ENTRY NextEntry
;
833 CsrAcquireProcessLock();
835 /* Find the thread */
836 CsrThread
= CsrLocateThreadByClientId(&CsrProcess
, &ClientId
);
838 /* Make sure we got one back, and that it's not already gone */
839 if (!(CsrThread
) || (CsrProcess
->Flags
& CsrProcessTerminating
))
841 /* Release the lock and return failure */
842 CsrReleaseProcessLock();
843 return STATUS_THREAD_IS_TERMINATING
;
846 /* Set the terminated flag */
847 CsrProcess
->Flags
|= CsrProcessTerminating
;
849 /* Get the List Pointers */
850 NextEntry
= CsrProcess
->ThreadList
.Flink
;
851 while (NextEntry
!= &CsrProcess
->ThreadList
)
853 /* Get the current thread entry */
854 CsrThread
= CONTAINING_RECORD(NextEntry
, CSR_THREAD
, Link
);
856 /* Move to the next entry */
857 NextEntry
= NextEntry
->Flink
;
859 /* Make sure the thread isn't already dead */
860 if (CsrThread
->Flags
& CsrThreadTerminated
)
862 /* Go the the next thread */
866 /* Set the Terminated flag */
867 CsrThread
->Flags
|= CsrThreadTerminated
;
869 /* Acquire the Wait Lock */
870 CsrAcquireWaitLock();
872 /* Do we have an active wait block? */
873 if (CsrThread
->WaitBlock
)
875 /* Notify waiters of termination */
876 CsrNotifyWaitBlock(CsrThread
->WaitBlock
,
880 CsrProcessTerminating
,
884 /* Release the Wait Lock */
885 CsrReleaseWaitLock();
887 /* Dereference the thread */
888 CsrLockedDereferenceThread(CsrThread
);
891 /* Release the Process Lock and return success */
892 CsrReleaseProcessLock();
893 return STATUS_SUCCESS
;
897 * @name CsrGetProcessLuid
900 * The CsrGetProcessLuid routine gets the LUID of the given process.
903 * Optional handle to the process whose LUID should be returned.
906 * Pointer to a LUID Pointer which will receive the CSR Process' LUID.
908 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
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 impersonation succeeded, 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
))
1038 DPRINT1("CSRSS: Can't impersonate client thread - Status = %lx\n", Status
);
1039 // if (Status != STATUS_BAD_IMPERSONATION_LEVEL) DbgBreakPoint();
1043 /* Increase the impersonation count for the current thread */
1044 if (CurrentThread
) ++CurrentThread
->ImpersonationCount
;
1046 /* Return Success */
1051 * @name CsrLockProcessByClientId
1054 * The CsrLockProcessByClientId routine locks the CSR Process corresponding
1055 * to the given Process ID and optionally returns it.
1058 * Process ID corresponding to the CSR Process which will be locked.
1061 * Optional pointer to a CSR Process pointer which will hold the
1062 * CSR Process corresponding to the given Process ID.
1064 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
1066 * @remarks Locking a CSR Process is defined as acquiring an extra
1067 * reference to it and returning with the Process Lock held.
1072 CsrLockProcessByClientId(IN HANDLE Pid
,
1073 OUT PCSR_PROCESS
*CsrProcess
)
1075 PLIST_ENTRY NextEntry
;
1076 PCSR_PROCESS CurrentProcess
= NULL
;
1077 NTSTATUS Status
= STATUS_UNSUCCESSFUL
;
1079 /* Acquire the lock */
1080 CsrAcquireProcessLock();
1082 /* Assume failure */
1083 ASSERT(CsrProcess
!= NULL
);
1086 /* Setup the List Pointers */
1087 NextEntry
= &CsrRootProcess
->ListLink
;
1090 /* Get the Process */
1091 CurrentProcess
= CONTAINING_RECORD(NextEntry
, CSR_PROCESS
, ListLink
);
1093 /* Check for PID Match */
1094 if (CurrentProcess
->ClientId
.UniqueProcess
== Pid
)
1096 Status
= STATUS_SUCCESS
;
1100 /* Move to the next entry */
1101 NextEntry
= NextEntry
->Flink
;
1102 } while (NextEntry
!= &CsrRootProcess
->ListLink
);
1104 /* Check if we didn't find it in the list */
1105 if (!NT_SUCCESS(Status
))
1107 /* Nothing found, release the lock */
1108 CsrReleaseProcessLock();
1112 /* Lock the found process and return it */
1113 CsrLockedReferenceProcess(CurrentProcess
);
1114 *CsrProcess
= CurrentProcess
;
1117 /* Return the result */
1122 * @name CsrRevertToSelf
1125 * The CsrRevertToSelf routine will attempt to remove an active impersonation.
1129 * @return TRUE if the reversion was succesful, FALSE otherwise.
1131 * @remarks Impersonation can be recursive; as such, the impersonation token
1132 * will only be deleted once the CSR Thread's impersonaton count
1138 CsrRevertToSelf(VOID
)
1141 PCSR_THREAD CurrentThread
= CsrGetClientThread();
1142 HANDLE ImpersonationToken
= NULL
;
1144 /* Check if we have a Current Thread */
1147 /* Make sure impersonation is on */
1148 if (!CurrentThread
->ImpersonationCount
)
1150 DPRINT1("CSRSS: CsrRevertToSelf called while not impersonating\n");
1154 else if ((--CurrentThread
->ImpersonationCount
) > 0)
1156 /* Success; impersonation count decreased but still not zero */
1161 /* Impersonation has been totally removed, revert to ourselves */
1162 Status
= NtSetInformationThread(NtCurrentThread(),
1163 ThreadImpersonationToken
,
1164 &ImpersonationToken
,
1167 /* Return TRUE or FALSE */
1168 return NT_SUCCESS(Status
);
1172 * @name CsrSetBackgroundPriority
1175 * The CsrSetBackgroundPriority routine sets the priority for the given CSR
1176 * Process as a Background priority.
1179 * Pointer to the CSR Process whose priority will be modified.
1188 CsrSetBackgroundPriority(IN PCSR_PROCESS CsrProcess
)
1190 PROCESS_PRIORITY_CLASS PriorityClass
;
1192 /* Set the Foreground bit off */
1193 PriorityClass
.Foreground
= FALSE
;
1195 /* Set the new Priority */
1196 NtSetInformationProcess(CsrProcess
->ProcessHandle
,
1197 ProcessPriorityClass
,
1199 sizeof(PriorityClass
));
1203 * @name CsrSetForegroundPriority
1206 * The CsrSetForegroundPriority routine sets the priority for the given CSR
1207 * Process as a Foreground priority.
1210 * Pointer to the CSR Process whose priority will be modified.
1219 CsrSetForegroundPriority(IN PCSR_PROCESS CsrProcess
)
1221 PROCESS_PRIORITY_CLASS PriorityClass
;
1223 /* Set the Foreground bit on */
1224 PriorityClass
.Foreground
= TRUE
;
1226 /* Set the new Priority */
1227 NtSetInformationProcess(CsrProcess
->ProcessHandle
,
1228 ProcessPriorityClass
,
1230 sizeof(PriorityClass
));
1234 * @name CsrShutdownProcesses
1237 * The CsrShutdownProcesses routine shuts down every CSR Process possible
1238 * and calls each Server DLL's shutdown notification.
1241 * Pointer to the LUID of the CSR Process that is ordering the
1245 * Flags to send to the shutdown notification routine.
1247 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
1254 CsrShutdownProcesses(IN PLUID CallerLuid
,
1257 PLIST_ENTRY NextEntry
;
1258 PCSR_PROCESS CsrProcess
;
1262 PCSR_SERVER_DLL ServerDll
;
1263 ULONG Result
= 0; /* Intentionally invalid enumeratee to silence compiler warning */
1265 /* Acquire process lock */
1266 CsrAcquireProcessLock();
1268 /* Add shutdown flag */
1269 CsrRootProcess
->ShutdownFlags
|= CsrShutdownSystem
;
1271 /* Get the list pointers */
1272 NextEntry
= CsrRootProcess
->ListLink
.Flink
;
1273 while (NextEntry
!= &CsrRootProcess
->ListLink
)
1275 /* Get the Process */
1276 CsrProcess
= CONTAINING_RECORD(NextEntry
, CSR_PROCESS
, ListLink
);
1278 /* Move to the next entry */
1279 NextEntry
= NextEntry
->Flink
;
1281 /* Remove the skip flag, set shutdown flags to 0 */
1282 CsrProcess
->Flags
&= ~CsrProcessSkipShutdown
;
1283 CsrProcess
->ShutdownFlags
= 0;
1286 /* Set shudown Priority */
1287 CsrSetToShutdownPriority();
1292 /* Find the next process to shutdown */
1293 CsrProcess
= FindProcessForShutdown(CallerLuid
);
1294 if (!CsrProcess
) break;
1296 /* Increase reference to process */
1297 CsrLockedReferenceProcess(CsrProcess
);
1302 /* Loop all the servers */
1303 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
1305 /* Get the current server */
1306 ServerDll
= CsrLoadedServerDll
[i
];
1308 /* Check if it's valid and if it has a Shutdown Process Callback */
1309 if (ServerDll
&& ServerDll
->ShutdownProcessCallback
)
1311 /* Release the lock, make the callback, and acquire it back */
1312 CsrReleaseProcessLock();
1313 Result
= ServerDll
->ShutdownProcessCallback(CsrProcess
,
1316 CsrAcquireProcessLock();
1318 /* Check the result */
1319 if (Result
== CsrShutdownCsrProcess
)
1321 /* The callback unlocked the process */
1324 else if (Result
== CsrShutdownCancelled
)
1326 /* Check if this was a forced shutdown */
1327 if (Flags
& EWX_FORCE
)
1329 DPRINT1("Process %x cancelled forced shutdown (Dll = %d)\n",
1330 CsrProcess
->ClientId
.UniqueProcess
, i
);
1334 /* Shutdown was cancelled, unlock and exit */
1335 CsrReleaseProcessLock();
1336 Status
= STATUS_CANCELLED
;
1342 /* No matches during the first try, so loop again */
1343 if ((FirstTry
) && (Result
== CsrShutdownNonCsrProcess
))
1349 /* Second try, break out */
1353 /* We've reached the final loop here, so dereference */
1354 if (i
== CSR_SERVER_DLL_MAX
) CsrLockedDereferenceProcess(CsrProcess
);
1358 CsrReleaseProcessLock();
1359 Status
= STATUS_SUCCESS
;
1362 /* Return to normal priority */
1363 CsrSetToNormalPriority();
1368 /* HACK: Temporary hack. This is really "CsrShutdownProcesses", mostly. Used by winsrv */
1372 CsrEnumProcesses(IN CSRSS_ENUM_PROCESS_PROC EnumProc
,
1375 PVOID
* RealContext
= (PVOID
*)Context
;
1376 PLUID CallerLuid
= RealContext
[0];
1377 PCSR_PROCESS CsrProcess
= NULL
;
1378 NTSTATUS Status
= STATUS_UNSUCCESSFUL
;
1380 PLIST_ENTRY NextEntry
;
1383 /* Acquire process lock */
1384 CsrAcquireProcessLock();
1386 /* Get the list pointers */
1387 NextEntry
= CsrRootProcess
->ListLink
.Flink
;
1388 while (NextEntry
!= &CsrRootProcess
->ListLink
)
1390 /* Get the Process */
1391 CsrProcess
= CONTAINING_RECORD(NextEntry
, CSR_PROCESS
, ListLink
);
1393 /* Move to the next entry */
1394 NextEntry
= NextEntry
->Flink
;
1396 /* Remove the skip flag, set shutdown flags to 0 */
1397 CsrProcess
->Flags
&= ~CsrProcessSkipShutdown
;
1398 CsrProcess
->ShutdownFlags
= 0;
1401 /* Set shudown Priority */
1402 CsrSetToShutdownPriority();
1404 /* Loop all processes */
1405 //DPRINT1("Enumerating for LUID: %lx %lx\n", CallerLuid->HighPart, CallerLuid->LowPart);
1410 /* Find the next process to shutdown */
1412 if (!(CsrProcess
= FindProcessForShutdown(CallerLuid
)))
1415 CsrReleaseProcessLock();
1416 Status
= STATUS_SUCCESS
;
1421 /* Release the lock, make the callback, and acquire it back */
1422 //DPRINT1("Found process: %lx\n", CsrProcess->ClientId.UniqueProcess);
1423 CsrReleaseProcessLock();
1424 Result
= (ULONG
)EnumProc(CsrProcess
, (PVOID
)((ULONG_PTR
)Context
| FirstTry
));
1425 CsrAcquireProcessLock();
1427 /* Check the result */
1428 //DPRINT1("Result: %d\n", Result);
1429 if (Result
== CsrShutdownCsrProcess
)
1431 /* The callback unlocked the process */
1434 else if (Result
== CsrShutdownNonCsrProcess
)
1436 /* A non-CSR process, the callback didn't touch it */
1439 else if (Result
== CsrShutdownCancelled
)
1441 /* Shutdown was cancelled, unlock and exit */
1442 CsrReleaseProcessLock();
1443 Status
= STATUS_CANCELLED
;
1447 /* No matches during the first try, so loop again */
1448 if (FirstTry
&& Result
== CsrShutdownNonCsrProcess
)
1456 /* Return to normal priority */
1457 CsrSetToNormalPriority();
1463 * @name CsrUnlockProcess
1466 * The CsrUnlockProcess undoes a previous CsrLockProcessByClientId operation.
1469 * Pointer to a previously locked CSR Process.
1471 * @return STATUS_SUCCESS.
1473 * @remarks This routine must be called with the Process Lock held.
1478 CsrUnlockProcess(IN PCSR_PROCESS CsrProcess
)
1480 /* Dereference the process */
1481 CsrLockedDereferenceProcess(CsrProcess
);
1483 /* Release the lock and return */
1484 CsrReleaseProcessLock();
1485 return STATUS_SUCCESS
;