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
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
,
471 IN PCSR_PROCESS CurrentProcess OPTIONAL
,
472 IN PCSR_PROCESS CsrProcess
)
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
;
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
= &CurrentProcess
->ServerData
[CSR_SERVER_DLL_MAX
];
565 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
567 /* Check if the DLL is Loaded and has Per Process Data */
568 if ((CsrLoadedServerDll
[i
]) && (CsrLoadedServerDll
[i
]->SizeOfProcessData
))
570 /* Set the pointer */
571 CsrProcess
->ServerData
[i
] = ProcessData
;
574 RtlMoveMemory(ProcessData
,
575 CurrentProcess
->ServerData
[i
],
576 CsrLoadedServerDll
[i
]->SizeOfProcessData
);
578 /* Update next data pointer */
579 ProcessData
= (PVOID
)((ULONG_PTR
)ProcessData
+
580 CsrLoadedServerDll
[i
]->SizeOfProcessData
);
584 /* No data for this Server */
585 CsrProcess
->ServerData
[i
] = NULL
;
589 /* Set the Exception port for us */
590 Status
= NtSetInformationProcess(hProcess
,
591 ProcessExceptionPort
,
594 if (!NT_SUCCESS(Status
))
597 CsrDeallocateProcess(CsrProcess
);
598 CsrReleaseProcessLock();
599 return STATUS_NO_MEMORY
;
602 /* Check if CreateProcess got CREATE_NEW_PROCESS_GROUP */
603 if (!(Flags
& CsrProcessCreateNewGroup
))
605 /* Create new data */
606 CsrProcess
->ProcessGroupId
= HandleToUlong(ClientId
->UniqueProcess
);
607 CsrProcess
->ProcessGroupSequence
= CsrProcess
->SequenceNumber
;
611 /* Copy it from the current process */
612 CsrProcess
->ProcessGroupId
= CurrentProcess
->ProcessGroupId
;
613 CsrProcess
->ProcessGroupSequence
= CurrentProcess
->ProcessGroupSequence
;
616 /* Check if this is a console process */
617 if (Flags
& CsrProcessIsConsoleApp
) CsrProcess
->Flags
|= CsrProcessIsConsoleApp
;
619 /* Mask out non-debug flags */
620 Flags
&= ~(CsrProcessIsConsoleApp
| CsrProcessCreateNewGroup
| CsrProcessPriorityFlags
);
622 /* Check if every process will be debugged */
623 if (!(Flags
) && (CurrentProcess
->DebugFlags
& CsrDebugProcessChildren
))
625 /* Pass it on to the current process */
626 CsrProcess
->DebugFlags
= CsrDebugProcessChildren
;
627 CsrProcess
->DebugCid
= CurrentProcess
->DebugCid
;
630 /* Check if Debugging was used on this process */
631 if ((Flags
& (CsrDebugOnlyThisProcess
| CsrDebugProcessChildren
)) && (DebugCid
))
633 /* Save the debug flag used */
634 CsrProcess
->DebugFlags
= Flags
;
637 CsrProcess
->DebugCid
= *DebugCid
;
640 /* Check if Debugging is enabled */
641 if (CsrProcess
->DebugFlags
)
643 /* Set the Debug Port for us */
644 Status
= NtSetInformationProcess(hProcess
,
648 ASSERT(NT_SUCCESS(Status
));
649 if (!NT_SUCCESS(Status
))
652 CsrDeallocateProcess(CsrProcess
);
653 CsrReleaseProcessLock();
654 return STATUS_NO_MEMORY
;
658 /* Get the Thread Create Time */
659 Status
= NtQueryInformationThread(hThread
,
664 if (!NT_SUCCESS(Status
))
667 CsrDeallocateProcess(CsrProcess
);
668 CsrReleaseProcessLock();
669 return STATUS_NO_MEMORY
;
672 /* Allocate a CSR Thread Structure */
673 CsrThread
= CsrAllocateThread(CsrProcess
);
677 CsrDeallocateProcess(CsrProcess
);
678 CsrReleaseProcessLock();
679 return STATUS_NO_MEMORY
;
682 /* Save the data we have */
683 CsrThread
->CreateTime
= KernelTimes
.CreateTime
;
684 CsrThread
->ClientId
= *ClientId
;
685 CsrThread
->ThreadHandle
= hThread
;
686 ProtectHandle(hThread
);
687 CsrThread
->Flags
= 0;
689 /* Insert the Thread into the Process */
690 CsrInsertThread(CsrProcess
, CsrThread
);
692 /* Reference the session */
693 CsrReferenceNtSession(NtSession
);
694 CsrProcess
->NtSession
= NtSession
;
696 /* Setup Process Data */
697 CsrProcess
->ClientId
= *ClientId
;
698 CsrProcess
->ProcessHandle
= hProcess
;
699 CsrProcess
->ShutdownLevel
= 0x280;
701 /* Set the Priority to Background */
702 CsrSetBackgroundPriority(CsrProcess
);
704 /* Insert the Process */
705 CsrInsertProcess(NULL
, CurrentProcess
, CsrProcess
);
707 /* Release lock and return */
708 CsrReleaseProcessLock();
713 * @name CsrDebugProcess
716 * The CsrDebugProcess routine is deprecated in NT 5.1 and higher. It is
717 * exported only for compatibility with older CSR Server DLLs.
724 * @remarks Deprecated.
729 CsrDebugProcess(IN PCSR_PROCESS CsrProcess
)
731 /* CSR does not handle debugging anymore */
732 DPRINT("CSRSRV: %s(%08lx) called\n", __FUNCTION__
, CsrProcess
);
733 return STATUS_UNSUCCESSFUL
;
737 * @name CsrDebugProcessStop
740 * The CsrDebugProcessStop routine is deprecated in NT 5.1 and higher. It is
741 * exported only for compatibility with older CSR Server DLLs.
748 * @remarks Deprecated.
753 CsrDebugProcessStop(IN PCSR_PROCESS CsrProcess
)
755 /* CSR does not handle debugging anymore */
756 DPRINT("CSRSRV: %s(%08lx) called\n", __FUNCTION__
, CsrProcess
);
757 return STATUS_UNSUCCESSFUL
;
761 * @name CsrDereferenceProcess
764 * The CsrDereferenceProcess routine removes a reference from a CSR Process.
767 * Pointer to the CSR Process to dereference.
771 * @remarks If the reference count has reached zero (ie: the CSR Process has
772 * no more active references), it will be deleted.
777 CsrDereferenceProcess(IN PCSR_PROCESS CsrProcess
)
781 /* Acquire process lock */
782 CsrAcquireProcessLock();
784 /* Decrease reference count */
785 LockCount
= --CsrProcess
->ReferenceCount
;
786 ASSERT(LockCount
>= 0);
789 /* Call the generic cleanup code */
790 CsrProcessRefcountZero(CsrProcess
);
794 /* Just release the lock */
795 CsrReleaseProcessLock();
800 * @name CsrDestroyProcess
803 * The CsrDestroyProcess routine destroys the CSR Process corresponding to
807 * Pointer to the Client ID Structure corresponding to the CSR
808 * Process which is about to be destroyed.
813 * @return STATUS_SUCCESS in case of success, STATUS_THREAD_IS_TERMINATING
814 * if the CSR Process is already terminating.
821 CsrDestroyProcess(IN PCLIENT_ID Cid
,
822 IN NTSTATUS ExitStatus
)
824 PCSR_THREAD CsrThread
;
825 PCSR_PROCESS CsrProcess
;
826 CLIENT_ID ClientId
= *Cid
;
827 PLIST_ENTRY NextEntry
;
830 CsrAcquireProcessLock();
832 /* Find the thread */
833 CsrThread
= CsrLocateThreadByClientId(&CsrProcess
, &ClientId
);
835 /* Make sure we got one back, and that it's not already gone */
836 if (!(CsrThread
) || (CsrProcess
->Flags
& CsrProcessTerminating
))
838 /* Release the lock and return failure */
839 CsrReleaseProcessLock();
840 return STATUS_THREAD_IS_TERMINATING
;
843 /* Set the terminated flag */
844 CsrProcess
->Flags
|= CsrProcessTerminating
;
846 /* Get the List Pointers */
847 NextEntry
= CsrProcess
->ThreadList
.Flink
;
848 while (NextEntry
!= &CsrProcess
->ThreadList
)
850 /* Get the current thread entry */
851 CsrThread
= CONTAINING_RECORD(NextEntry
, CSR_THREAD
, Link
);
853 /* Make sure the thread isn't already dead */
854 if (CsrThread
->Flags
& CsrThreadTerminated
)
856 NextEntry
= NextEntry
->Flink
;
860 /* Set the Terminated flag */
861 CsrThread
->Flags
|= CsrThreadTerminated
;
863 /* Acquire the Wait Lock */
864 CsrAcquireWaitLock();
866 /* Do we have an active wait block? */
867 if (CsrThread
->WaitBlock
)
869 /* Notify waiters of termination */
870 CsrNotifyWaitBlock(CsrThread
->WaitBlock
,
874 CsrProcessTerminating
,
878 /* Release the Wait Lock */
879 CsrReleaseWaitLock();
881 /* Dereference the thread */
882 CsrLockedDereferenceThread(CsrThread
);
883 NextEntry
= CsrProcess
->ThreadList
.Flink
;
886 /* Release the Process Lock and return success */
887 CsrReleaseProcessLock();
888 return STATUS_SUCCESS
;
892 * @name CsrGetProcessLuid
895 * Do nothing for 500ms.
898 * Optional handle to the process whose LUID should be returned.
901 * Pointer to a LUID Pointer which will receive the CSR Process' LUID
903 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL
906 * @remarks If hProcess is not supplied, then the current thread's token will
907 * be used. If that too is missing, then the current process' token
913 CsrGetProcessLuid(IN HANDLE hProcess OPTIONAL
,
916 HANDLE hToken
= NULL
;
919 PTOKEN_STATISTICS TokenStats
;
921 /* Check if we have a handle to a CSR Process */
924 /* We don't, so try opening the Thread's Token */
925 Status
= NtOpenThreadToken(NtCurrentThread(),
930 /* Check for success */
931 if (!NT_SUCCESS(Status
))
933 /* If we got some other failure, then return and quit */
934 if (Status
!= STATUS_NO_TOKEN
) return Status
;
936 /* We don't have a Thread Token, use a Process Token */
937 hProcess
= NtCurrentProcess();
942 /* Check if we have a token by now */
945 /* No token yet, so open the Process Token */
946 Status
= NtOpenProcessToken(hProcess
,
949 if (!NT_SUCCESS(Status
))
951 /* Still no token, return the error */
956 /* Now get the size we'll need for the Token Information */
957 Status
= NtQueryInformationToken(hToken
,
963 /* Allocate memory for the Token Info */
964 if (!(TokenStats
= RtlAllocateHeap(CsrHeap
, 0, Length
)))
966 /* Fail and close the token */
968 return STATUS_NO_MEMORY
;
971 /* Now query the information */
972 Status
= NtQueryInformationToken(hToken
,
978 /* Close the handle */
981 /* Check for success */
982 if (NT_SUCCESS(Status
))
984 /* Return the LUID */
985 *Luid
= TokenStats
->AuthenticationId
;
988 /* Free the query information */
989 RtlFreeHeap(CsrHeap
, 0, TokenStats
);
991 /* Return the Status */
996 * @name CsrImpersonateClient
999 * The CsrImpersonateClient will impersonate the given CSR Thread.
1002 * Pointer to the CSR Thread to impersonate.
1004 * @return TRUE if impersionation suceeded, false otherwise.
1006 * @remarks Impersonation can be recursive.
1011 CsrImpersonateClient(IN PCSR_THREAD CsrThread
)
1014 PCSR_THREAD CurrentThread
= CsrGetClientThread();
1016 /* Use the current thread if none given */
1017 if (!CsrThread
) CsrThread
= CurrentThread
;
1019 /* Still no thread, something is wrong */
1027 Status
= NtImpersonateThread(NtCurrentThread(),
1028 CsrThread
->ThreadHandle
,
1031 if (!NT_SUCCESS(Status
))
1035 DPRINT1("CSRSS: Can't impersonate client thread - Status = %lx\n", Status);
1036 if (Status != STATUS_BAD_IMPERSONATION_LEVEL) DbgBreakPoint();
1041 /* Increase the impersonation count for the current thread */
1042 if (CurrentThread
) ++CurrentThread
->ImpersonationCount
;
1044 /* Return Success */
1049 * @name CsrLockProcessByClientId
1052 * The CsrLockProcessByClientId routine locks the CSR Process corresponding
1053 * to the given Process ID and optionally returns it.
1056 * Process ID corresponding to the CSR Process which will be locked.
1059 * Optional pointer to a CSR Process pointer which will hold the
1060 * CSR Process corresponding to the given Process ID.
1062 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL
1065 * @remarks Locking a CSR Process is defined as acquiring an extra
1066 * reference to it and returning with the Process Lock held.
1071 CsrLockProcessByClientId(IN HANDLE Pid
,
1072 OUT PCSR_PROCESS
*CsrProcess
)
1074 PLIST_ENTRY NextEntry
;
1075 PCSR_PROCESS CurrentProcess
= NULL
;
1078 /* Acquire the lock */
1079 CsrAcquireProcessLock();
1081 /* Assume failure */
1082 ASSERT(CsrProcess
!= NULL
);
1085 /* Setup the List Pointers */
1086 NextEntry
= &CsrRootProcess
->ListLink
;
1089 /* Get the Process */
1090 CurrentProcess
= CONTAINING_RECORD(NextEntry
, CSR_PROCESS
, ListLink
);
1092 /* Check for PID Match */
1093 if (CurrentProcess
->ClientId
.UniqueProcess
== Pid
)
1095 Status
= STATUS_SUCCESS
;
1100 NextEntry
= NextEntry
->Flink
;
1101 } while (NextEntry
!= &CsrRootProcess
->ListLink
);
1103 /* Check if we didn't find it in the list */
1104 if (!NT_SUCCESS(Status
))
1106 /* Nothing found, release the lock */
1107 CsrReleaseProcessLock();
1111 /* Lock the found process and return it */
1112 CsrLockedReferenceProcess(CurrentProcess
);
1113 *CsrProcess
= CurrentProcess
;
1116 /* Return the result */
1121 * @name CsrRevertToSelf
1124 * The CsrRevertToSelf routine will attempt to remove an active impersonation.
1128 * @return TRUE if the reversion was succesful, false otherwise.
1130 * @remarks Impersonation can be recursive; as such, the impersonation token
1131 * will only be deleted once the CSR Thread's impersonaton count
1137 CsrRevertToSelf(VOID
)
1140 PCSR_THREAD CurrentThread
= CsrGetClientThread();
1141 HANDLE ImpersonationToken
= NULL
;
1143 /* Check if we have a Current Thread */
1146 /* Make sure impersonation is on */
1147 if (!CurrentThread
->ImpersonationCount
)
1149 // DPRINT1("CSRSS: CsrRevertToSelf called while not impersonating\n");
1153 else if (--CurrentThread
->ImpersonationCount
> 0)
1155 /* Success; impersonation count decreased but still not zero */
1160 /* Impersonation has been totally removed, revert to ourselves */
1161 Status
= NtSetInformationThread(NtCurrentThread(),
1162 ThreadImpersonationToken
,
1163 &ImpersonationToken
,
1166 /* Return TRUE or FALSE */
1167 return NT_SUCCESS(Status
);
1171 * @name CsrSetBackgroundPriority
1174 * The CsrSetBackgroundPriority routine sets the priority for the given CSR
1175 * Process as a Background priority.
1178 * Pointer to the CSR Process whose priority will be modified.
1187 CsrSetBackgroundPriority(IN PCSR_PROCESS CsrProcess
)
1189 PROCESS_PRIORITY_CLASS PriorityClass
;
1191 /* Set the Foreground bit off */
1192 PriorityClass
.Foreground
= FALSE
;
1194 /* Set the new Priority */
1195 NtSetInformationProcess(CsrProcess
->ProcessHandle
,
1196 ProcessPriorityClass
,
1198 sizeof(PriorityClass
));
1202 * @name CsrSetForegroundPriority
1205 * The CsrSetForegroundPriority routine sets the priority for the given CSR
1206 * Process as a Foreground priority.
1209 * Pointer to the CSR Process whose priority will be modified.
1218 CsrSetForegroundPriority(IN PCSR_PROCESS CsrProcess
)
1220 PROCESS_PRIORITY_CLASS PriorityClass
;
1222 /* Set the Foreground bit on */
1223 PriorityClass
.Foreground
= TRUE
;
1225 /* Set the new Priority */
1226 NtSetInformationProcess(CsrProcess
->ProcessHandle
,
1227 ProcessPriorityClass
,
1229 sizeof(PriorityClass
));
1233 * @name CsrShutdownProcesses
1236 * The CsrShutdownProcesses routine shuts down every CSR Process possible
1237 * and calls each Server DLL's shutdown notification.
1240 * Pointer to the LUID of the CSR Process that is ordering the
1244 * Flags to send to the shutdown notification routine.
1246 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL
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 /* Remove the skip flag, set shutdown flags to 0*/
1279 CsrProcess
->Flags
&= ~CsrProcessSkipShutdown
;
1280 CsrProcess
->ShutdownFlags
= 0;
1282 /* Move to the next */
1283 NextEntry
= NextEntry
->Flink
;
1286 /* Set shudown Priority */
1287 // CsrpSetToShutdownPriority();
1288 CsrSetToShutdownPriority();
1293 /* Find the next process to shutdown */
1294 CsrProcess
= FindProcessForShutdown(CallerLuid
);
1295 if (!CsrProcess
) break;
1297 /* Increase reference to process */
1298 CsrProcess
->ReferenceCount
++;
1303 /* Loop all the servers */
1304 for (i
= 0; i
< CSR_SERVER_DLL_MAX
; i
++)
1306 /* Get the current server */
1307 ServerDll
= CsrLoadedServerDll
[i
];
1308 if ((ServerDll
) && (ServerDll
->ShutdownProcessCallback
))
1310 /* Release the lock, make the callback, and acquire it back */
1311 CsrReleaseProcessLock();
1312 Result
= ServerDll
->ShutdownProcessCallback(CsrProcess
,
1315 CsrAcquireProcessLock();
1317 /* Check the result */
1318 if (Result
== CsrShutdownCsrProcess
)
1320 /* The callback unlocked the process */
1323 else if (Result
== CsrShutdownCancelled
)
1325 /* Check if this was a forced shutdown */
1326 if (Flags
& EWX_FORCE
)
1328 DPRINT1("Process %x cancelled forced shutdown (Dll = %d)\n",
1329 CsrProcess
->ClientId
.UniqueProcess
, i
);
1333 /* Shutdown was cancelled, unlock and exit */
1334 CsrReleaseProcessLock();
1335 Status
= STATUS_CANCELLED
;
1341 /* No matches during the first try, so loop again */
1342 if ((FirstTry
) && (Result
== CsrShutdownNonCsrProcess
))
1348 /* Second try, break out */
1352 /* We've reached the final loop here, so dereference */
1353 if (i
== CSR_SERVER_DLL_MAX
) CsrLockedDereferenceProcess(CsrProcess
);
1357 CsrReleaseProcessLock();
1358 Status
= STATUS_SUCCESS
;
1361 /* Return to normal priority */
1362 // CsrpSetToNormalPriority();
1363 CsrSetToNormalPriority();
1368 /* FIXME: Temporary hack. This is really "CsrShutdownProcess", 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 /* Remove the skip flag, set shutdown flags to 0*/
1394 CsrProcess
->Flags
&= ~CsrProcessSkipShutdown
;
1395 CsrProcess
->ShutdownFlags
= 0;
1397 /* Move to the next */
1398 NextEntry
= NextEntry
->Flink
;
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
;