[CSRSRV]
[reactos.git] / subsystems / win32 / csrsrv / procsup.c
1 /*
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)
8 */
9
10 /* INCLUDES *******************************************************************/
11
12 #include <srv.h>
13
14 #define NDEBUG
15 #include <debug.h>
16
17 /* GLOBALS ********************************************************************/
18
19 RTL_CRITICAL_SECTION CsrProcessLock;
20 PCSR_PROCESS CsrRootProcess = NULL;
21 SECURITY_QUALITY_OF_SERVICE CsrSecurityQos =
22 {
23 sizeof(SECURITY_QUALITY_OF_SERVICE),
24 SecurityImpersonation,
25 SECURITY_STATIC_TRACKING,
26 FALSE
27 };
28 ULONG CsrProcessSequenceCount = 5;
29 extern ULONG CsrTotalPerProcessDataLength;
30
31
32 /* PRIVATE FUNCTIONS **********************************************************/
33
34 /*++
35 * @name CsrSetToNormalPriority
36 *
37 * The CsrSetToNormalPriority routine sets the current NT Process'
38 * priority to the normal priority for CSR Processes.
39 *
40 * @param None.
41 *
42 * @return None.
43 *
44 * @remarks The "Normal" Priority corresponds to the Normal Foreground
45 * Priority (9) plus a boost of 4.
46 *
47 *--*/
48 VOID
49 NTAPI
50 CsrSetToNormalPriority(VOID)
51 {
52 KPRIORITY BasePriority = (8 + 1) + 4;
53
54 /* Set the Priority */
55 NtSetInformationProcess(NtCurrentProcess(),
56 ProcessBasePriority,
57 &BasePriority,
58 sizeof(KPRIORITY));
59 }
60
61 /*++
62 * @name CsrSetToShutdownPriority
63 *
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.
67 *
68 * @param None.
69 *
70 * @return None.
71 *
72 * @remarks The "Shutdown" Priority corresponds to the Normal Foreground
73 * Priority (9) plus a boost of 6.
74 *
75 *--*/
76 VOID
77 NTAPI
78 CsrSetToShutdownPriority(VOID)
79 {
80 KPRIORITY SetBasePriority = (8 + 1) + 6;
81 BOOLEAN Old;
82
83 /* Get the shutdown privilege */
84 if (NT_SUCCESS(RtlAdjustPrivilege(SE_SHUTDOWN_PRIVILEGE,
85 TRUE,
86 FALSE,
87 &Old)))
88 {
89 /* Set the Priority */
90 NtSetInformationProcess(NtCurrentProcess(),
91 ProcessBasePriority,
92 &SetBasePriority,
93 sizeof(KPRIORITY));
94 }
95 }
96
97 /*++
98 * @name FindProcessForShutdown
99 *
100 * The FindProcessForShutdown routine returns a CSR Process which is ready
101 * to be shutdown, and sets the appropriate shutdown flags for it.
102 *
103 * @param CallerLuid
104 * Pointer to the LUID of the CSR Process calling this routine.
105 *
106 * @return Pointer to a CSR Process which is ready to be shutdown.
107 *
108 * @remarks None.
109 *
110 *--*/
111 PCSR_PROCESS
112 NTAPI
113 FindProcessForShutdown(IN PLUID CallerLuid)
114 {
115 PCSR_PROCESS CsrProcess, ReturnCsrProcess = NULL;
116 // PCSR_THREAD CsrThread;
117 NTSTATUS Status;
118 ULONG Level = 0;
119 LUID ProcessLuid;
120 LUID SystemLuid = SYSTEM_LUID;
121 // BOOLEAN IsSystemLuid = FALSE, IsOurLuid = FALSE;
122 PLIST_ENTRY NextEntry;
123
124 /* Set the List Pointers */
125 NextEntry = CsrRootProcess->ListLink.Flink;
126 while (NextEntry != &CsrRootProcess->ListLink)
127 {
128 /* Get the process */
129 CsrProcess = CONTAINING_RECORD(NextEntry, CSR_PROCESS, ListLink);
130
131 /* Move to the next entry */
132 NextEntry = NextEntry->Flink;
133
134 /* Skip this process if it's already been processed */
135 if (CsrProcess->Flags & CsrProcessSkipShutdown) continue;
136
137 /* Get the LUID of this Process */
138 Status = CsrGetProcessLuid(CsrProcess->ProcessHandle, &ProcessLuid);
139
140 /* Check if we didn't get access to the LUID */
141 if (Status == STATUS_ACCESS_DENIED)
142 {
143 /* FIXME: Check if we have any threads */
144 /*
145 /\* Check if we have any threads *\/
146 if (CsrProcess->ThreadCount)
147 {
148 /\* Impersonate one of the threads and retry *\/
149 CsrThread = CONTAINING_RECORD(CsrProcess->ThreadList.Flink,
150 CSR_THREAD,
151 Link);
152 CsrImpersonateClient(CsrThread);
153 Status = CsrGetProcessLuid(NULL, &ProcessLuid);
154 CsrRevertToSelf();
155 }
156 */
157 }
158
159 if (!NT_SUCCESS(Status))
160 {
161 /* We didn't have access, so skip it */
162 CsrProcess->Flags |= CsrProcessSkipShutdown;
163 continue;
164 }
165
166 /* Check if this is the System LUID */
167 if ((/*IsSystemLuid =*/ RtlEqualLuid(&ProcessLuid, &SystemLuid)))
168 {
169 /* Mark this process */
170 CsrProcess->ShutdownFlags |= CsrShutdownSystem;
171 }
172 else if (!(/*IsOurLuid =*/ RtlEqualLuid(&ProcessLuid, CallerLuid)))
173 {
174 /* Our LUID doesn't match with the caller's */
175 CsrProcess->ShutdownFlags |= CsrShutdownOther;
176 }
177
178 /* Check if we're past the previous level */
179 // FIXME: if ((CsrProcess->ShutdownLevel > Level) || !(ReturnCsrProcess))
180 if (CsrProcess->ShutdownLevel > Level /* || !ReturnCsrProcess */)
181 {
182 /* Update the level */
183 Level = CsrProcess->ShutdownLevel;
184
185 /* Set the final process */
186 ReturnCsrProcess = CsrProcess;
187 }
188 }
189
190 /* Check if we found a process */
191 if (ReturnCsrProcess)
192 {
193 /* Skip this one next time */
194 ReturnCsrProcess->Flags |= CsrProcessSkipShutdown;
195 }
196
197 return ReturnCsrProcess;
198 }
199
200 /*++
201 * @name CsrProcessRefcountZero
202 *
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.
205 *
206 * @param CsrProcess
207 * Pointer to the CSR Process that is to be deleted.
208 *
209 * @return None.
210 *
211 * @remarks Do not call this routine. It is reserved for the internal
212 * thread management routines when a CSR Process has lost all
213 * its references.
214 *
215 * This routine is called with the Process Lock held.
216 *
217 *--*/
218 VOID
219 NTAPI
220 CsrProcessRefcountZero(IN PCSR_PROCESS CsrProcess)
221 {
222 ASSERT(ProcessStructureListLocked());
223
224 /* Remove the Process from the list */
225 CsrRemoveProcess(CsrProcess);
226
227 /* Check if there's a session */
228 if (CsrProcess->NtSession)
229 {
230 /* Dereference the Session */
231 CsrDereferenceNtSession(CsrProcess->NtSession, 0);
232 }
233
234 /* Close the Client Port if there is one */
235 if (CsrProcess->ClientPort) NtClose(CsrProcess->ClientPort);
236
237 /* Close the process handle */
238 NtClose(CsrProcess->ProcessHandle);
239
240 /* Free the Proces Object */
241 CsrDeallocateProcess(CsrProcess);
242 }
243
244 /*++
245 * @name CsrLockedDereferenceProcess
246 *
247 * The CsrLockedDereferenceProcess dereferences a CSR Process while the
248 * Process Lock is already being held.
249 *
250 * @param CsrProcess
251 * Pointer to the CSR Process to be dereferenced.
252 *
253 * @return None.
254 *
255 * @remarks This routine will return with the Process Lock held.
256 *
257 *--*/
258 VOID
259 NTAPI
260 CsrLockedDereferenceProcess(PCSR_PROCESS CsrProcess)
261 {
262 LONG LockCount;
263
264 /* Decrease reference count */
265 LockCount = --CsrProcess->ReferenceCount;
266 ASSERT(LockCount >= 0);
267 if (LockCount == 0)
268 {
269 /* Call the generic cleanup code */
270 DPRINT1("Should kill process: %p\n", CsrProcess);
271 CsrAcquireProcessLock();
272 CsrProcessRefcountZero(CsrProcess);
273 }
274 }
275
276 /*++
277 * @name CsrAllocateProcess
278 * @implemented NT4
279 *
280 * The CsrAllocateProcess routine allocates a new CSR Process object.
281 *
282 * @return Pointer to the newly allocated CSR Process.
283 *
284 * @remarks None.
285 *
286 *--*/
287 PCSR_PROCESS
288 NTAPI
289 CsrAllocateProcess(VOID)
290 {
291 PCSR_PROCESS CsrProcess;
292 ULONG TotalSize;
293
294 /* Calculate the amount of memory this should take */
295 TotalSize = sizeof(CSR_PROCESS) +
296 (CSR_SERVER_DLL_MAX * sizeof(PVOID)) +
297 CsrTotalPerProcessDataLength;
298
299 /* Allocate a Process */
300 CsrProcess = RtlAllocateHeap(CsrHeap, HEAP_ZERO_MEMORY, TotalSize);
301 if (!CsrProcess) return NULL;
302
303 /* Handle the Sequence Number and protect against overflow */
304 CsrProcess->SequenceNumber = CsrProcessSequenceCount++;
305 if (CsrProcessSequenceCount < 5) CsrProcessSequenceCount = 5;
306
307 /* Increase the reference count */
308 CsrLockedReferenceProcess(CsrProcess);
309
310 /* Initialize the Thread List */
311 InitializeListHead(&CsrProcess->ThreadList);
312
313 /* Return the Process */
314 return CsrProcess;
315 }
316
317 /*++
318 * @name CsrLockedReferenceProcess
319 *
320 * The CsrLockedReferenceProcess references a CSR Process while the
321 * Process Lock is already being held.
322 *
323 * @param CsrProcess
324 * Pointer to the CSR Process to be referenced.
325 *
326 * @return None.
327 *
328 * @remarks This routine will return with the Process Lock held.
329 *
330 *--*/
331 VOID
332 NTAPI
333 CsrLockedReferenceProcess(IN PCSR_PROCESS CsrProcess)
334 {
335 /* Increment the reference count */
336 ++CsrProcess->ReferenceCount;
337 }
338
339 /*++
340 * @name CsrInitializeProcessStructure
341 * @implemented NT4
342 *
343 * The CsrInitializeProcessStructure routine sets up support for CSR Processes
344 * and CSR Threads by initializing our own CSR Root Process.
345 *
346 * @param None.
347 *
348 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
349 *
350 * @remarks None.
351 *
352 *--*/
353 NTSTATUS
354 NTAPI
355 CsrInitializeProcessStructure(VOID)
356 {
357 NTSTATUS Status;
358 ULONG i;
359
360 /* Initialize the Lock */
361 Status = RtlInitializeCriticalSection(&CsrProcessLock);
362 if (!NT_SUCCESS(Status)) return Status;
363
364 /* Set up the Root Process */
365 CsrRootProcess = CsrAllocateProcess();
366 if (!CsrRootProcess) return STATUS_NO_MEMORY;
367
368 /* Set up the minimal information for it */
369 InitializeListHead(&CsrRootProcess->ListLink);
370 CsrRootProcess->ProcessHandle = (HANDLE)-1;
371 CsrRootProcess->ClientId = NtCurrentTeb()->ClientId;
372
373 /* Initialize the Thread Hash List */
374 for (i = 0; i < 256; i++) InitializeListHead(&CsrThreadHashTable[i]);
375
376 /* Initialize the Wait Lock */
377 return RtlInitializeCriticalSection(&CsrWaitListsLock);
378 }
379
380 /*++
381 * @name CsrDeallocateProcess
382 *
383 * The CsrDeallocateProcess frees the memory associated with a CSR Process.
384 *
385 * @param CsrProcess
386 * Pointer to the CSR Process to be freed.
387 *
388 * @return None.
389 *
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.
393 *
394 *--*/
395 VOID
396 NTAPI
397 CsrDeallocateProcess(IN PCSR_PROCESS CsrProcess)
398 {
399 /* Free the process object from the heap */
400 RtlFreeHeap(CsrHeap, 0, CsrProcess);
401 }
402
403 /*++
404 * @name CsrRemoveProcess
405 *
406 * The CsrRemoveProcess function undoes a CsrInsertProcess operation and
407 * removes the CSR Process from the Process List and notifies Server DLLs
408 * of this removal.
409 *
410 * @param CsrProcess
411 * Pointer to the CSR Process to remove.
412 *
413 * @return None.
414 *
415 * @remarks None.
416 *
417 *--*/
418 VOID
419 NTAPI
420 CsrRemoveProcess(IN PCSR_PROCESS CsrProcess)
421 {
422 PCSR_SERVER_DLL ServerDll;
423 ULONG i;
424 ASSERT(ProcessStructureListLocked());
425
426 /* Remove us from the Process List */
427 RemoveEntryList(&CsrProcess->ListLink);
428
429 /* Release the lock */
430 CsrReleaseProcessLock();
431
432 /* Loop every Server DLL */
433 for (i = 0; i < CSR_SERVER_DLL_MAX; i++)
434 {
435 /* Get the Server DLL */
436 ServerDll = CsrLoadedServerDll[i];
437
438 /* Check if it's valid and if it has a Disconnect Callback */
439 if (ServerDll && ServerDll->DisconnectCallback)
440 {
441 /* Call it */
442 ServerDll->DisconnectCallback(CsrProcess);
443 }
444 }
445 }
446
447 /*++
448 * @name CsrInsertProcess
449 *
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.
452 *
453 * @param ParentProcess
454 * Optional pointer to the Parent Process creating this CSR Process.
455 *
456 * @param CsrProcess
457 * Pointer to the CSR Process which is to be inserted.
458 *
459 * @return None.
460 *
461 * @remarks None.
462 *
463 *--*/
464 VOID
465 NTAPI
466 CsrInsertProcess(IN PCSR_PROCESS ParentProcess OPTIONAL,
467 IN PCSR_PROCESS CsrProcess)
468 {
469 PCSR_SERVER_DLL ServerDll;
470 ULONG i;
471 ASSERT(ProcessStructureListLocked());
472
473 /* Insert it into the Root List */
474 InsertTailList(&CsrRootProcess->ListLink, &CsrProcess->ListLink);
475
476 /* Notify the Server DLLs */
477 for (i = 0; i < CSR_SERVER_DLL_MAX; i++)
478 {
479 /* Get the current Server DLL */
480 ServerDll = CsrLoadedServerDll[i];
481
482 /* Make sure it's valid and that it has callback */
483 if (ServerDll && ServerDll->NewProcessCallback)
484 {
485 ServerDll->NewProcessCallback(ParentProcess, CsrProcess);
486 }
487 }
488 }
489
490
491 /* PUBLIC FUNCTIONS ***********************************************************/
492
493 /*++
494 * @name CsrCreateProcess
495 * @implemented NT4
496 *
497 * The CsrCreateProcess routine creates a CSR Process object for an NT Process.
498 *
499 * @param hProcess
500 * Handle to an existing NT Process to which to associate this
501 * CSR Process.
502 *
503 * @param hThread
504 * Handle to an existing NT Thread to which to create its
505 * corresponding CSR Thread for this CSR Process.
506 *
507 * @param ClientId
508 * Pointer to the Client ID structure of the NT Process to associate
509 * with this CSR Process.
510 *
511 * @param NtSession
512 * @param Flags
513 * @param DebugCid
514 *
515 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
516 *
517 * @remarks None.
518 *
519 *--*/
520 NTSTATUS
521 NTAPI
522 CsrCreateProcess(IN HANDLE hProcess,
523 IN HANDLE hThread,
524 IN PCLIENT_ID ClientId,
525 IN PCSR_NT_SESSION NtSession,
526 IN ULONG Flags,
527 IN PCLIENT_ID DebugCid)
528 {
529 PCSR_THREAD CurrentThread = CsrGetClientThread();
530 CLIENT_ID CurrentCid;
531 PCSR_PROCESS CurrentProcess;
532 PCSR_SERVER_DLL ServerDll;
533 PVOID ProcessData;
534 ULONG i;
535 PCSR_PROCESS CsrProcess;
536 NTSTATUS Status;
537 PCSR_THREAD CsrThread;
538 KERNEL_USER_TIMES KernelTimes;
539
540 /* Get the current CID and lock Processes */
541 CurrentCid = CurrentThread->ClientId;
542 CsrAcquireProcessLock();
543
544 /* Get the current CSR Thread */
545 CurrentThread = CsrLocateThreadByClientId(&CurrentProcess, &CurrentCid);
546 if (!CurrentThread)
547 {
548 /* We've failed to locate the thread */
549 CsrReleaseProcessLock();
550 return STATUS_THREAD_IS_TERMINATING;
551 }
552
553 /* Allocate a new Process Object */
554 CsrProcess = CsrAllocateProcess();
555 if (!CsrProcess)
556 {
557 /* Couldn't allocate Process */
558 CsrReleaseProcessLock();
559 return STATUS_NO_MEMORY;
560 }
561
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++)
566 {
567 /* Get the current Server */
568 ServerDll = CsrLoadedServerDll[i];
569
570 /* Check if the DLL is Loaded and has Per Process Data */
571 if (ServerDll && ServerDll->SizeOfProcessData)
572 {
573 /* Set the pointer */
574 CsrProcess->ServerData[i] = ProcessData;
575
576 /* Copy the Data */
577 RtlMoveMemory(ProcessData,
578 CurrentProcess->ServerData[i],
579 ServerDll->SizeOfProcessData);
580
581 /* Update next data pointer */
582 ProcessData = (PVOID)((ULONG_PTR)ProcessData +
583 ServerDll->SizeOfProcessData);
584 }
585 else
586 {
587 /* No data for this Server */
588 CsrProcess->ServerData[i] = NULL;
589 }
590 }
591
592 /* Set the Exception port for us */
593 Status = NtSetInformationProcess(hProcess,
594 ProcessExceptionPort,
595 &CsrApiPort,
596 sizeof(HANDLE));
597 if (!NT_SUCCESS(Status))
598 {
599 /* Failed */
600 CsrDeallocateProcess(CsrProcess);
601 CsrReleaseProcessLock();
602 return STATUS_NO_MEMORY;
603 }
604
605 /* Check if CreateProcess got CREATE_NEW_PROCESS_GROUP */
606 if ((Flags & CsrProcessCreateNewGroup) == 0)
607 {
608 /* Create new data */
609 CsrProcess->ProcessGroupId = HandleToUlong(ClientId->UniqueProcess);
610 CsrProcess->ProcessGroupSequence = CsrProcess->SequenceNumber;
611 }
612 else
613 {
614 /* Copy it from the current process */
615 CsrProcess->ProcessGroupId = CurrentProcess->ProcessGroupId;
616 CsrProcess->ProcessGroupSequence = CurrentProcess->ProcessGroupSequence;
617 }
618
619 /* Check if this is a console process */
620 if (Flags & CsrProcessIsConsoleApp) CsrProcess->Flags |= CsrProcessIsConsoleApp;
621
622 /* Mask out non-debug flags */
623 Flags &= ~(CsrProcessIsConsoleApp | CsrProcessCreateNewGroup | CsrProcessPriorityFlags);
624
625 /* Check if every process will be debugged */
626 if (!(Flags) && (CurrentProcess->DebugFlags & CsrDebugProcessChildren))
627 {
628 /* Pass it on to the current process */
629 CsrProcess->DebugFlags = CsrDebugProcessChildren;
630 CsrProcess->DebugCid = CurrentProcess->DebugCid;
631 }
632
633 /* Check if Debugging was used on this process */
634 if ((Flags & (CsrDebugOnlyThisProcess | CsrDebugProcessChildren)) && (DebugCid))
635 {
636 /* Save the debug flag used */
637 CsrProcess->DebugFlags = Flags;
638
639 /* Save the CID */
640 CsrProcess->DebugCid = *DebugCid;
641 }
642
643 /* Check if Debugging is enabled */
644 if (CsrProcess->DebugFlags)
645 {
646 /* Set the Debug Port for us */
647 Status = NtSetInformationProcess(hProcess,
648 ProcessDebugPort,
649 &CsrApiPort,
650 sizeof(HANDLE));
651 ASSERT(NT_SUCCESS(Status));
652 if (!NT_SUCCESS(Status))
653 {
654 /* Failed */
655 CsrDeallocateProcess(CsrProcess);
656 CsrReleaseProcessLock();
657 return STATUS_NO_MEMORY;
658 }
659 }
660
661 /* Get the Thread Create Time */
662 Status = NtQueryInformationThread(hThread,
663 ThreadTimes,
664 (PVOID)&KernelTimes,
665 sizeof(KernelTimes),
666 NULL);
667 if (!NT_SUCCESS(Status))
668 {
669 /* Failed */
670 CsrDeallocateProcess(CsrProcess);
671 CsrReleaseProcessLock();
672 return STATUS_NO_MEMORY;
673 }
674
675 /* Allocate a CSR Thread Structure */
676 CsrThread = CsrAllocateThread(CsrProcess);
677 if (!CsrThread)
678 {
679 /* Failed */
680 CsrDeallocateProcess(CsrProcess);
681 CsrReleaseProcessLock();
682 return STATUS_NO_MEMORY;
683 }
684
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;
691
692 /* Insert the Thread into the Process */
693 CsrInsertThread(CsrProcess, CsrThread);
694
695 /* Reference the session */
696 CsrReferenceNtSession(NtSession);
697 CsrProcess->NtSession = NtSession;
698
699 /* Setup Process Data */
700 CsrProcess->ClientId = *ClientId;
701 CsrProcess->ProcessHandle = hProcess;
702 CsrProcess->ShutdownLevel = 0x280;
703
704 /* Set the Priority to Background */
705 CsrSetBackgroundPriority(CsrProcess);
706
707 /* Insert the Process */
708 CsrInsertProcess(CurrentProcess, CsrProcess);
709
710 /* Release lock and return */
711 CsrReleaseProcessLock();
712 return Status;
713 }
714
715 /*++
716 * @name CsrDebugProcess
717 * @implemented NT4
718 *
719 * The CsrDebugProcess routine is deprecated in NT 5.1 and higher. It is
720 * exported only for compatibility with older CSR Server DLLs.
721 *
722 * @param CsrProcess
723 * Deprecated.
724 *
725 * @return Deprecated
726 *
727 * @remarks Deprecated.
728 *
729 *--*/
730 NTSTATUS
731 NTAPI
732 CsrDebugProcess(IN PCSR_PROCESS CsrProcess)
733 {
734 /* CSR does not handle debugging anymore */
735 DPRINT("CSRSRV: %s(%08lx) called\n", __FUNCTION__, CsrProcess);
736 return STATUS_UNSUCCESSFUL;
737 }
738
739 /*++
740 * @name CsrDebugProcessStop
741 * @implemented NT4
742 *
743 * The CsrDebugProcessStop routine is deprecated in NT 5.1 and higher. It is
744 * exported only for compatibility with older CSR Server DLLs.
745 *
746 * @param CsrProcess
747 * Deprecated.
748 *
749 * @return Deprecated
750 *
751 * @remarks Deprecated.
752 *
753 *--*/
754 NTSTATUS
755 NTAPI
756 CsrDebugProcessStop(IN PCSR_PROCESS CsrProcess)
757 {
758 /* CSR does not handle debugging anymore */
759 DPRINT("CSRSRV: %s(%08lx) called\n", __FUNCTION__, CsrProcess);
760 return STATUS_UNSUCCESSFUL;
761 }
762
763 /*++
764 * @name CsrDereferenceProcess
765 * @implemented NT4
766 *
767 * The CsrDereferenceProcess routine removes a reference from a CSR Process.
768 *
769 * @param CsrThread
770 * Pointer to the CSR Process to dereference.
771 *
772 * @return None.
773 *
774 * @remarks If the reference count has reached zero (ie: the CSR Process has
775 * no more active references), it will be deleted.
776 *
777 *--*/
778 VOID
779 NTAPI
780 CsrDereferenceProcess(IN PCSR_PROCESS CsrProcess)
781 {
782 LONG LockCount;
783
784 /* Acquire process lock */
785 CsrAcquireProcessLock();
786
787 /* Decrease reference count */
788 LockCount = --CsrProcess->ReferenceCount;
789 ASSERT(LockCount >= 0);
790 if (LockCount == 0)
791 {
792 /* Call the generic cleanup code */
793 CsrProcessRefcountZero(CsrProcess);
794 }
795 else
796 {
797 /* Just release the lock */
798 CsrReleaseProcessLock();
799 }
800 }
801
802 /*++
803 * @name CsrDestroyProcess
804 * @implemented NT4
805 *
806 * The CsrDestroyProcess routine destroys the CSR Process corresponding to
807 * a given Client ID.
808 *
809 * @param Cid
810 * Pointer to the Client ID Structure corresponding to the CSR
811 * Process which is about to be destroyed.
812 *
813 * @param ExitStatus
814 * Unused.
815 *
816 * @return STATUS_SUCCESS in case of success, STATUS_THREAD_IS_TERMINATING
817 * if the CSR Process is already terminating.
818 *
819 * @remarks None.
820 *
821 *--*/
822 NTSTATUS
823 NTAPI
824 CsrDestroyProcess(IN PCLIENT_ID Cid,
825 IN NTSTATUS ExitStatus)
826 {
827 PCSR_THREAD CsrThread;
828 PCSR_PROCESS CsrProcess;
829 CLIENT_ID ClientId = *Cid;
830 PLIST_ENTRY NextEntry;
831
832 /* Acquire lock */
833 CsrAcquireProcessLock();
834
835 /* Find the thread */
836 CsrThread = CsrLocateThreadByClientId(&CsrProcess, &ClientId);
837
838 /* Make sure we got one back, and that it's not already gone */
839 if (!(CsrThread) || (CsrProcess->Flags & CsrProcessTerminating))
840 {
841 /* Release the lock and return failure */
842 CsrReleaseProcessLock();
843 return STATUS_THREAD_IS_TERMINATING;
844 }
845
846 /* Set the terminated flag */
847 CsrProcess->Flags |= CsrProcessTerminating;
848
849 /* Get the List Pointers */
850 NextEntry = CsrProcess->ThreadList.Flink;
851 while (NextEntry != &CsrProcess->ThreadList)
852 {
853 /* Get the current thread entry */
854 CsrThread = CONTAINING_RECORD(NextEntry, CSR_THREAD, Link);
855
856 /* Move to the next entry */
857 NextEntry = NextEntry->Flink;
858
859 /* Make sure the thread isn't already dead */
860 if (CsrThread->Flags & CsrThreadTerminated)
861 {
862 /* Go the the next thread */
863 continue;
864 }
865
866 /* Set the Terminated flag */
867 CsrThread->Flags |= CsrThreadTerminated;
868
869 /* Acquire the Wait Lock */
870 CsrAcquireWaitLock();
871
872 /* Do we have an active wait block? */
873 if (CsrThread->WaitBlock)
874 {
875 /* Notify waiters of termination */
876 CsrNotifyWaitBlock(CsrThread->WaitBlock,
877 NULL,
878 NULL,
879 NULL,
880 CsrProcessTerminating,
881 TRUE);
882 }
883
884 /* Release the Wait Lock */
885 CsrReleaseWaitLock();
886
887 /* Dereference the thread */
888 CsrLockedDereferenceThread(CsrThread);
889 }
890
891 /* Release the Process Lock and return success */
892 CsrReleaseProcessLock();
893 return STATUS_SUCCESS;
894 }
895
896 /*++
897 * @name CsrGetProcessLuid
898 * @implemented NT4
899 *
900 * The CsrGetProcessLuid routine gets the LUID of the given process.
901 *
902 * @param hProcess
903 * Optional handle to the process whose LUID should be returned.
904 *
905 * @param Luid
906 * Pointer to a LUID Pointer which will receive the CSR Process' LUID.
907 *
908 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
909 *
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
912 * will be used.
913 *
914 *--*/
915 NTSTATUS
916 NTAPI
917 CsrGetProcessLuid(IN HANDLE hProcess OPTIONAL,
918 OUT PLUID Luid)
919 {
920 HANDLE hToken = NULL;
921 NTSTATUS Status;
922 ULONG Length;
923 PTOKEN_STATISTICS TokenStats;
924
925 /* Check if we have a handle to a CSR Process */
926 if (!hProcess)
927 {
928 /* We don't, so try opening the Thread's Token */
929 Status = NtOpenThreadToken(NtCurrentThread(),
930 TOKEN_QUERY,
931 FALSE,
932 &hToken);
933
934 /* Check for success */
935 if (!NT_SUCCESS(Status))
936 {
937 /* If we got some other failure, then return and quit */
938 if (Status != STATUS_NO_TOKEN) return Status;
939
940 /* We don't have a Thread Token, use a Process Token */
941 hProcess = NtCurrentProcess();
942 hToken = NULL;
943 }
944 }
945
946 /* Check if we have a token by now */
947 if (!hToken)
948 {
949 /* No token yet, so open the Process Token */
950 Status = NtOpenProcessToken(hProcess,
951 TOKEN_QUERY,
952 &hToken);
953 if (!NT_SUCCESS(Status))
954 {
955 /* Still no token, return the error */
956 return Status;
957 }
958 }
959
960 /* Now get the size we'll need for the Token Information */
961 Status = NtQueryInformationToken(hToken,
962 TokenStatistics,
963 NULL,
964 0,
965 &Length);
966
967 /* Allocate memory for the Token Info */
968 if (!(TokenStats = RtlAllocateHeap(CsrHeap, 0, Length)))
969 {
970 /* Fail and close the token */
971 NtClose(hToken);
972 return STATUS_NO_MEMORY;
973 }
974
975 /* Now query the information */
976 Status = NtQueryInformationToken(hToken,
977 TokenStatistics,
978 TokenStats,
979 Length,
980 &Length);
981
982 /* Close the handle */
983 NtClose(hToken);
984
985 /* Check for success */
986 if (NT_SUCCESS(Status))
987 {
988 /* Return the LUID */
989 *Luid = TokenStats->AuthenticationId;
990 }
991
992 /* Free the query information */
993 RtlFreeHeap(CsrHeap, 0, TokenStats);
994
995 /* Return the Status */
996 return Status;
997 }
998
999 /*++
1000 * @name CsrImpersonateClient
1001 * @implemented NT4
1002 *
1003 * The CsrImpersonateClient will impersonate the given CSR Thread.
1004 *
1005 * @param CsrThread
1006 * Pointer to the CSR Thread to impersonate.
1007 *
1008 * @return TRUE if impersonation succeeded, FALSE otherwise.
1009 *
1010 * @remarks Impersonation can be recursive.
1011 *
1012 *--*/
1013 BOOLEAN
1014 NTAPI
1015 CsrImpersonateClient(IN PCSR_THREAD CsrThread)
1016 {
1017 NTSTATUS Status;
1018 PCSR_THREAD CurrentThread = CsrGetClientThread();
1019
1020 /* Use the current thread if none given */
1021 if (!CsrThread) CsrThread = CurrentThread;
1022
1023 /* Still no thread, something is wrong */
1024 if (!CsrThread)
1025 {
1026 /* Failure */
1027 return FALSE;
1028 }
1029
1030 /* Make the call */
1031 Status = NtImpersonateThread(NtCurrentThread(),
1032 CsrThread->ThreadHandle,
1033 &CsrSecurityQos);
1034
1035 if (!NT_SUCCESS(Status))
1036 {
1037 /* Failure */
1038 DPRINT1("CSRSS: Can't impersonate client thread - Status = %lx\n", Status);
1039 // if (Status != STATUS_BAD_IMPERSONATION_LEVEL) DbgBreakPoint();
1040 return FALSE;
1041 }
1042
1043 /* Increase the impersonation count for the current thread */
1044 if (CurrentThread) ++CurrentThread->ImpersonationCount;
1045
1046 /* Return Success */
1047 return TRUE;
1048 }
1049
1050 /*++
1051 * @name CsrLockProcessByClientId
1052 * @implemented NT4
1053 *
1054 * The CsrLockProcessByClientId routine locks the CSR Process corresponding
1055 * to the given Process ID and optionally returns it.
1056 *
1057 * @param Pid
1058 * Process ID corresponding to the CSR Process which will be locked.
1059 *
1060 * @param CsrProcess
1061 * Optional pointer to a CSR Process pointer which will hold the
1062 * CSR Process corresponding to the given Process ID.
1063 *
1064 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
1065 *
1066 * @remarks Locking a CSR Process is defined as acquiring an extra
1067 * reference to it and returning with the Process Lock held.
1068 *
1069 *--*/
1070 NTSTATUS
1071 NTAPI
1072 CsrLockProcessByClientId(IN HANDLE Pid,
1073 OUT PCSR_PROCESS *CsrProcess)
1074 {
1075 PLIST_ENTRY NextEntry;
1076 PCSR_PROCESS CurrentProcess = NULL;
1077 NTSTATUS Status = STATUS_UNSUCCESSFUL;
1078
1079 /* Acquire the lock */
1080 CsrAcquireProcessLock();
1081
1082 /* Assume failure */
1083 ASSERT(CsrProcess != NULL);
1084 *CsrProcess = NULL;
1085
1086 /* Setup the List Pointers */
1087 NextEntry = &CsrRootProcess->ListLink;
1088 do
1089 {
1090 /* Get the Process */
1091 CurrentProcess = CONTAINING_RECORD(NextEntry, CSR_PROCESS, ListLink);
1092
1093 /* Check for PID Match */
1094 if (CurrentProcess->ClientId.UniqueProcess == Pid)
1095 {
1096 Status = STATUS_SUCCESS;
1097 break;
1098 }
1099
1100 /* Move to the next entry */
1101 NextEntry = NextEntry->Flink;
1102 } while (NextEntry != &CsrRootProcess->ListLink);
1103
1104 /* Check if we didn't find it in the list */
1105 if (!NT_SUCCESS(Status))
1106 {
1107 /* Nothing found, release the lock */
1108 CsrReleaseProcessLock();
1109 }
1110 else
1111 {
1112 /* Lock the found process and return it */
1113 CsrLockedReferenceProcess(CurrentProcess);
1114 *CsrProcess = CurrentProcess;
1115 }
1116
1117 /* Return the result */
1118 return Status;
1119 }
1120
1121 /*++
1122 * @name CsrRevertToSelf
1123 * @implemented NT4
1124 *
1125 * The CsrRevertToSelf routine will attempt to remove an active impersonation.
1126 *
1127 * @param None.
1128 *
1129 * @return TRUE if the reversion was succesful, FALSE otherwise.
1130 *
1131 * @remarks Impersonation can be recursive; as such, the impersonation token
1132 * will only be deleted once the CSR Thread's impersonaton count
1133 * has reached zero.
1134 *
1135 *--*/
1136 BOOLEAN
1137 NTAPI
1138 CsrRevertToSelf(VOID)
1139 {
1140 NTSTATUS Status;
1141 PCSR_THREAD CurrentThread = CsrGetClientThread();
1142 HANDLE ImpersonationToken = NULL;
1143
1144 /* Check if we have a Current Thread */
1145 if (CurrentThread)
1146 {
1147 /* Make sure impersonation is on */
1148 if (!CurrentThread->ImpersonationCount)
1149 {
1150 DPRINT1("CSRSS: CsrRevertToSelf called while not impersonating\n");
1151 // DbgBreakPoint();
1152 return FALSE;
1153 }
1154 else if ((--CurrentThread->ImpersonationCount) > 0)
1155 {
1156 /* Success; impersonation count decreased but still not zero */
1157 return TRUE;
1158 }
1159 }
1160
1161 /* Impersonation has been totally removed, revert to ourselves */
1162 Status = NtSetInformationThread(NtCurrentThread(),
1163 ThreadImpersonationToken,
1164 &ImpersonationToken,
1165 sizeof(HANDLE));
1166
1167 /* Return TRUE or FALSE */
1168 return NT_SUCCESS(Status);
1169 }
1170
1171 /*++
1172 * @name CsrSetBackgroundPriority
1173 * @implemented NT4
1174 *
1175 * The CsrSetBackgroundPriority routine sets the priority for the given CSR
1176 * Process as a Background priority.
1177 *
1178 * @param CsrProcess
1179 * Pointer to the CSR Process whose priority will be modified.
1180 *
1181 * @return None.
1182 *
1183 * @remarks None.
1184 *
1185 *--*/
1186 VOID
1187 NTAPI
1188 CsrSetBackgroundPriority(IN PCSR_PROCESS CsrProcess)
1189 {
1190 PROCESS_PRIORITY_CLASS PriorityClass;
1191
1192 /* Set the Foreground bit off */
1193 PriorityClass.Foreground = FALSE;
1194
1195 /* Set the new Priority */
1196 NtSetInformationProcess(CsrProcess->ProcessHandle,
1197 ProcessPriorityClass,
1198 &PriorityClass,
1199 sizeof(PriorityClass));
1200 }
1201
1202 /*++
1203 * @name CsrSetForegroundPriority
1204 * @implemented NT4
1205 *
1206 * The CsrSetForegroundPriority routine sets the priority for the given CSR
1207 * Process as a Foreground priority.
1208 *
1209 * @param CsrProcess
1210 * Pointer to the CSR Process whose priority will be modified.
1211 *
1212 * @return None.
1213 *
1214 * @remarks None.
1215 *
1216 *--*/
1217 VOID
1218 NTAPI
1219 CsrSetForegroundPriority(IN PCSR_PROCESS CsrProcess)
1220 {
1221 PROCESS_PRIORITY_CLASS PriorityClass;
1222
1223 /* Set the Foreground bit on */
1224 PriorityClass.Foreground = TRUE;
1225
1226 /* Set the new Priority */
1227 NtSetInformationProcess(CsrProcess->ProcessHandle,
1228 ProcessPriorityClass,
1229 &PriorityClass,
1230 sizeof(PriorityClass));
1231 }
1232
1233 /*++
1234 * @name CsrShutdownProcesses
1235 * @implemented NT4
1236 *
1237 * The CsrShutdownProcesses routine shuts down every CSR Process possible
1238 * and calls each Server DLL's shutdown notification.
1239 *
1240 * @param CallerLuid
1241 * Pointer to the LUID of the CSR Process that is ordering the
1242 * shutdown.
1243 *
1244 * @param Flags
1245 * Flags to send to the shutdown notification routine.
1246 *
1247 * @return STATUS_SUCCESS in case of success, STATUS_UNSUCCESSFUL otherwise.
1248 *
1249 * @remarks None.
1250 *
1251 *--*/
1252 NTSTATUS
1253 NTAPI
1254 CsrShutdownProcesses(IN PLUID CallerLuid,
1255 IN ULONG Flags)
1256 {
1257 PLIST_ENTRY NextEntry;
1258 PCSR_PROCESS CsrProcess;
1259 NTSTATUS Status;
1260 BOOLEAN FirstTry;
1261 ULONG i;
1262 PCSR_SERVER_DLL ServerDll;
1263 ULONG Result = 0; /* Intentionally invalid enumeratee to silence compiler warning */
1264
1265 /* Acquire process lock */
1266 CsrAcquireProcessLock();
1267
1268 /* Add shutdown flag */
1269 CsrRootProcess->ShutdownFlags |= CsrShutdownSystem;
1270
1271 /* Get the list pointers */
1272 NextEntry = CsrRootProcess->ListLink.Flink;
1273 while (NextEntry != &CsrRootProcess->ListLink)
1274 {
1275 /* Get the Process */
1276 CsrProcess = CONTAINING_RECORD(NextEntry, CSR_PROCESS, ListLink);
1277
1278 /* Move to the next entry */
1279 NextEntry = NextEntry->Flink;
1280
1281 /* Remove the skip flag, set shutdown flags to 0 */
1282 CsrProcess->Flags &= ~CsrProcessSkipShutdown;
1283 CsrProcess->ShutdownFlags = 0;
1284 }
1285
1286 /* Set shudown Priority */
1287 CsrSetToShutdownPriority();
1288
1289 /* Start looping */
1290 while (TRUE)
1291 {
1292 /* Find the next process to shutdown */
1293 CsrProcess = FindProcessForShutdown(CallerLuid);
1294 if (!CsrProcess) break;
1295
1296 /* Increase reference to process */
1297 CsrLockedReferenceProcess(CsrProcess);
1298
1299 FirstTry = TRUE;
1300 while (TRUE)
1301 {
1302 /* Loop all the servers */
1303 for (i = 0; i < CSR_SERVER_DLL_MAX; i++)
1304 {
1305 /* Get the current server */
1306 ServerDll = CsrLoadedServerDll[i];
1307
1308 /* Check if it's valid and if it has a Shutdown Process Callback */
1309 if (ServerDll && ServerDll->ShutdownProcessCallback)
1310 {
1311 /* Release the lock, make the callback, and acquire it back */
1312 CsrReleaseProcessLock();
1313 Result = ServerDll->ShutdownProcessCallback(CsrProcess,
1314 Flags,
1315 FirstTry);
1316 CsrAcquireProcessLock();
1317
1318 /* Check the result */
1319 if (Result == CsrShutdownCsrProcess)
1320 {
1321 /* The callback unlocked the process */
1322 break;
1323 }
1324 else if (Result == CsrShutdownCancelled)
1325 {
1326 /* Check if this was a forced shutdown */
1327 if (Flags & EWX_FORCE)
1328 {
1329 DPRINT1("Process %x cancelled forced shutdown (Dll = %d)\n",
1330 CsrProcess->ClientId.UniqueProcess, i);
1331 DbgBreakPoint();
1332 }
1333
1334 /* Shutdown was cancelled, unlock and exit */
1335 CsrReleaseProcessLock();
1336 Status = STATUS_CANCELLED;
1337 goto Quickie;
1338 }
1339 }
1340 }
1341
1342 /* No matches during the first try, so loop again */
1343 if ((FirstTry) && (Result == CsrShutdownNonCsrProcess))
1344 {
1345 FirstTry = FALSE;
1346 continue;
1347 }
1348
1349 /* Second try, break out */
1350 break;
1351 }
1352
1353 /* We've reached the final loop here, so dereference */
1354 if (i == CSR_SERVER_DLL_MAX) CsrLockedDereferenceProcess(CsrProcess);
1355 }
1356
1357 /* Success path */
1358 CsrReleaseProcessLock();
1359 Status = STATUS_SUCCESS;
1360
1361 Quickie:
1362 /* Return to normal priority */
1363 CsrSetToNormalPriority();
1364
1365 return Status;
1366 }
1367
1368 /* FIXME: Temporary hack. This is really "CsrShutdownProcess", mostly. Used by winsrv */
1369 #if 0
1370 NTSTATUS
1371 WINAPI
1372 CsrEnumProcesses(IN CSRSS_ENUM_PROCESS_PROC EnumProc,
1373 IN PVOID Context)
1374 {
1375 PVOID* RealContext = (PVOID*)Context;
1376 PLUID CallerLuid = RealContext[0];
1377 PCSR_PROCESS CsrProcess = NULL;
1378 NTSTATUS Status = STATUS_UNSUCCESSFUL;
1379 BOOLEAN FirstTry;
1380 PLIST_ENTRY NextEntry;
1381 ULONG Result = 0;
1382
1383 /* Acquire process lock */
1384 CsrAcquireProcessLock();
1385
1386 /* Get the list pointers */
1387 NextEntry = CsrRootProcess->ListLink.Flink;
1388 while (NextEntry != &CsrRootProcess->ListLink)
1389 {
1390 /* Get the Process */
1391 CsrProcess = CONTAINING_RECORD(NextEntry, CSR_PROCESS, ListLink);
1392
1393 /* Move to the next entry */
1394 NextEntry = NextEntry->Flink;
1395
1396 /* Remove the skip flag, set shutdown flags to 0 */
1397 CsrProcess->Flags &= ~CsrProcessSkipShutdown;
1398 CsrProcess->ShutdownFlags = 0;
1399 }
1400
1401 /* Set shudown Priority */
1402 CsrSetToShutdownPriority();
1403
1404 /* Loop all processes */
1405 //DPRINT1("Enumerating for LUID: %lx %lx\n", CallerLuid->HighPart, CallerLuid->LowPart);
1406
1407 /* Start looping */
1408 while (TRUE)
1409 {
1410 /* Find the next process to shutdown */
1411 FirstTry = TRUE;
1412 if (!(CsrProcess = FindProcessForShutdown(CallerLuid)))
1413 {
1414 /* Done, quit */
1415 CsrReleaseProcessLock();
1416 Status = STATUS_SUCCESS;
1417 goto Quickie;
1418 }
1419
1420 LoopAgain:
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();
1426
1427 /* Check the result */
1428 //DPRINT1("Result: %d\n", Result);
1429 if (Result == CsrShutdownCsrProcess)
1430 {
1431 /* The callback unlocked the process */
1432 break;
1433 }
1434 else if (Result == CsrShutdownNonCsrProcess)
1435 {
1436 /* A non-CSR process, the callback didn't touch it */
1437 //continue;
1438 }
1439 else if (Result == CsrShutdownCancelled)
1440 {
1441 /* Shutdown was cancelled, unlock and exit */
1442 CsrReleaseProcessLock();
1443 Status = STATUS_CANCELLED;
1444 goto Quickie;
1445 }
1446
1447 /* No matches during the first try, so loop again */
1448 if (FirstTry && Result == CsrShutdownNonCsrProcess)
1449 {
1450 FirstTry = FALSE;
1451 goto LoopAgain;
1452 }
1453 }
1454
1455 Quickie:
1456 /* Return to normal priority */
1457 CsrSetToNormalPriority();
1458 return Status;
1459 }
1460 #endif
1461
1462 /*++
1463 * @name CsrUnlockProcess
1464 * @implemented NT4
1465 *
1466 * The CsrUnlockProcess undoes a previous CsrLockProcessByClientId operation.
1467 *
1468 * @param CsrProcess
1469 * Pointer to a previously locked CSR Process.
1470 *
1471 * @return STATUS_SUCCESS.
1472 *
1473 * @remarks This routine must be called with the Process Lock held.
1474 *
1475 *--*/
1476 NTSTATUS
1477 NTAPI
1478 CsrUnlockProcess(IN PCSR_PROCESS CsrProcess)
1479 {
1480 /* Dereference the process */
1481 CsrLockedDereferenceProcess(CsrProcess);
1482
1483 /* Release the lock and return */
1484 CsrReleaseProcessLock();
1485 return STATUS_SUCCESS;
1486 }
1487
1488 /* EOF */