[WINSRV]
[reactos.git] / reactos / win32ss / user / winsrv / shutdown.c
1 /*
2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS User API Server DLL
4 * FILE: win32ss/user/winsrv/shutdown.c
5 * PURPOSE: Logout/shutdown
6 * PROGRAMMERS:
7 *
8 * NOTE: The shutdown code must be rewritten completely. (hbelusca)
9 */
10
11 /* INCLUDES *******************************************************************/
12
13 #include "winsrv.h"
14 #include <sddl.h>
15
16 #define NDEBUG
17 #include <debug.h>
18
19 /* GLOBALS ********************************************************************/
20
21 typedef struct tagSHUTDOWN_SETTINGS
22 {
23 BOOL AutoEndTasks;
24 DWORD HungAppTimeout;
25 DWORD WaitToKillAppTimeout;
26 } SHUTDOWN_SETTINGS, *PSHUTDOWN_SETTINGS;
27
28 #define DEFAULT_AUTO_END_TASKS FALSE
29 #define DEFAULT_HUNG_APP_TIMEOUT 5000
30 #define DEFAULT_WAIT_TO_KILL_APP_TIMEOUT 20000
31
32 typedef struct tagNOTIFY_CONTEXT
33 {
34 DWORD ProcessId;
35 UINT Msg;
36 WPARAM wParam;
37 LPARAM lParam;
38 HDESK Desktop;
39 HDESK OldDesktop;
40 DWORD StartTime;
41 DWORD QueryResult;
42 HWND Dlg;
43 DWORD EndNowResult;
44 BOOL ShowUI;
45 HANDLE UIThread;
46 HWND WndClient;
47 PSHUTDOWN_SETTINGS ShutdownSettings;
48 LPTHREAD_START_ROUTINE SendMessageProc;
49 } NOTIFY_CONTEXT, *PNOTIFY_CONTEXT;
50
51 #define QUERY_RESULT_ABORT 0
52 #define QUERY_RESULT_CONTINUE 1
53 #define QUERY_RESULT_TIMEOUT 2
54 #define QUERY_RESULT_ERROR 3
55 #define QUERY_RESULT_FORCE 4
56
57 typedef void (WINAPI *INITCOMMONCONTROLS_PROC)(void);
58
59 typedef struct tagMESSAGE_CONTEXT
60 {
61 HWND Wnd;
62 UINT Msg;
63 WPARAM wParam;
64 LPARAM lParam;
65 DWORD Timeout;
66 } MESSAGE_CONTEXT, *PMESSAGE_CONTEXT;
67
68 typedef struct tagPROCESS_ENUM_CONTEXT
69 {
70 UINT ProcessCount;
71 PCSR_PROCESS *ProcessData;
72 TOKEN_ORIGIN TokenOrigin;
73 DWORD ShellProcess;
74 DWORD CsrssProcess;
75 } PROCESS_ENUM_CONTEXT, *PPROCESS_ENUM_CONTEXT;
76
77
78 /* FUNCTIONS ******************************************************************/
79
80 /*
81 NTSTATUS FASTCALL
82 Win32CsrEnumProcesses(CSRSS_ENUM_PROCESS_PROC EnumProc,
83 PVOID Context)
84 {
85 return CsrEnumProcesses(EnumProc, Context);
86 }
87 */
88
89 static void FASTCALL
90 UpdateProgressBar(HWND ProgressBar, PNOTIFY_CONTEXT NotifyContext)
91 {
92 DWORD Passed;
93
94 Passed = GetTickCount() - NotifyContext->StartTime;
95 Passed -= NotifyContext->ShutdownSettings->HungAppTimeout;
96 if (NotifyContext->ShutdownSettings->WaitToKillAppTimeout < Passed)
97 {
98 Passed = NotifyContext->ShutdownSettings->WaitToKillAppTimeout;
99 }
100 SendMessageW(ProgressBar, PBM_SETPOS, Passed / 2, 0);
101 }
102
103 static INT_PTR CALLBACK
104 EndNowDlgProc(HWND Dlg, UINT Msg, WPARAM wParam, LPARAM lParam)
105 {
106 INT_PTR Result;
107 PNOTIFY_CONTEXT NotifyContext;
108 HWND ProgressBar;
109 DWORD TitleLength;
110 int Len;
111 LPWSTR Title;
112
113 switch(Msg)
114 {
115 case WM_INITDIALOG:
116 NotifyContext = (PNOTIFY_CONTEXT) lParam;
117 NotifyContext->EndNowResult = QUERY_RESULT_ABORT;
118 SetWindowLongPtrW(Dlg, DWLP_USER, (LONG_PTR) lParam);
119 TitleLength = SendMessageW(NotifyContext->WndClient, WM_GETTEXTLENGTH,
120 0, 0) +
121 GetWindowTextLengthW(Dlg);
122 Title = HeapAlloc(UserServerHeap, 0, (TitleLength + 1) * sizeof(WCHAR));
123 if (NULL != Title)
124 {
125 Len = GetWindowTextW(Dlg, Title, TitleLength + 1);
126 SendMessageW(NotifyContext->WndClient, WM_GETTEXT,
127 TitleLength + 1 - Len, (LPARAM) (Title + Len));
128 SetWindowTextW(Dlg, Title);
129 HeapFree(UserServerHeap, 0, Title);
130 }
131 ProgressBar = GetDlgItem(Dlg, IDC_PROGRESS);
132 SendMessageW(ProgressBar, PBM_SETRANGE32, 0,
133 NotifyContext->ShutdownSettings->WaitToKillAppTimeout / 2);
134 UpdateProgressBar(ProgressBar, NotifyContext);
135 SetTimer(Dlg, 0, 200, NULL);
136 Result = FALSE;
137 break;
138
139 case WM_TIMER:
140 NotifyContext = (PNOTIFY_CONTEXT) GetWindowLongPtrW(Dlg, DWLP_USER);
141 ProgressBar = GetDlgItem(Dlg, IDC_PROGRESS);
142 UpdateProgressBar(ProgressBar, NotifyContext);
143 Result = TRUE;
144 break;
145
146 case WM_COMMAND:
147 if (BN_CLICKED == HIWORD(wParam) && IDC_END_NOW == LOWORD(wParam))
148 {
149 NotifyContext = (PNOTIFY_CONTEXT) GetWindowLongPtrW(Dlg, DWLP_USER);
150 NotifyContext->EndNowResult = QUERY_RESULT_FORCE;
151 SendMessageW(Dlg, WM_CLOSE, 0, 0);
152 Result = TRUE;
153 }
154 else
155 {
156 Result = FALSE;
157 }
158 break;
159
160 case WM_CLOSE:
161 DestroyWindow(Dlg);
162 Result = TRUE;
163 break;
164
165 case WM_DESTROY:
166 NotifyContext = (PNOTIFY_CONTEXT) GetWindowLongPtrW(Dlg, DWLP_USER);
167 NotifyContext->Dlg = NULL;
168 KillTimer(Dlg, 0);
169 PostQuitMessage(NotifyContext->EndNowResult);
170 Result = TRUE;
171 break;
172
173 default:
174 Result = FALSE;
175 break;
176 }
177
178 return Result;
179 }
180
181 static void
182 CallInitCommonControls()
183 {
184 static BOOL Initialized = FALSE;
185 HMODULE Lib;
186 INITCOMMONCONTROLS_PROC InitProc;
187
188 if (Initialized) return;
189
190 Lib = LoadLibraryW(L"COMCTL32.DLL");
191 if (NULL == Lib) return;
192
193 InitProc = (INITCOMMONCONTROLS_PROC) GetProcAddress(Lib, "InitCommonControls");
194 if (NULL == InitProc) return;
195
196 (*InitProc)();
197
198 Initialized = TRUE;
199 }
200
201 static DWORD WINAPI
202 EndNowThreadProc(LPVOID Parameter)
203 {
204 PNOTIFY_CONTEXT NotifyContext = (PNOTIFY_CONTEXT) Parameter;
205 MSG Msg;
206
207 SetThreadDesktop(NotifyContext->Desktop);
208 SwitchDesktop(NotifyContext->Desktop);
209 CallInitCommonControls();
210 NotifyContext->Dlg = CreateDialogParam(UserServerDllInstance,
211 MAKEINTRESOURCE(IDD_END_NOW), NULL,
212 EndNowDlgProc, (LPARAM) NotifyContext);
213 if (NULL == NotifyContext->Dlg)
214 {
215 return 0;
216 }
217 ShowWindow(NotifyContext->Dlg, SW_SHOWNORMAL);
218
219 while (GetMessageW(&Msg, NULL, 0, 0))
220 {
221 if (! IsDialogMessage(NotifyContext->Dlg, &Msg))
222 {
223 TranslateMessage(&Msg);
224 DispatchMessageW(&Msg);
225 }
226 }
227
228 return Msg.wParam;
229 }
230
231 static DWORD WINAPI
232 SendQueryEndSession(LPVOID Parameter)
233 {
234 PMESSAGE_CONTEXT Context = (PMESSAGE_CONTEXT) Parameter;
235 DWORD_PTR Result;
236
237 if (SendMessageTimeoutW(Context->Wnd, WM_QUERYENDSESSION, Context->wParam,
238 Context->lParam, SMTO_NORMAL, Context->Timeout,
239 &Result))
240 {
241 return Result ? QUERY_RESULT_CONTINUE : QUERY_RESULT_ABORT;
242 }
243
244 return 0 == GetLastError() ? QUERY_RESULT_TIMEOUT : QUERY_RESULT_ERROR;
245 }
246
247 static DWORD WINAPI
248 SendEndSession(LPVOID Parameter)
249 {
250 PMESSAGE_CONTEXT Context = (PMESSAGE_CONTEXT) Parameter;
251 DWORD_PTR Result;
252
253 if (Context->wParam)
254 {
255 if (SendMessageTimeoutW(Context->Wnd, WM_ENDSESSION, Context->wParam,
256 Context->lParam, SMTO_NORMAL, Context->Timeout,
257 &Result))
258 {
259 return QUERY_RESULT_CONTINUE;
260 }
261 return 0 == GetLastError() ? QUERY_RESULT_TIMEOUT : QUERY_RESULT_ERROR;
262 }
263 else
264 {
265 SendMessage(Context->Wnd, WM_ENDSESSION, Context->wParam,
266 Context->lParam);
267 return QUERY_RESULT_CONTINUE;
268 }
269 }
270
271 static BOOL CALLBACK
272 NotifyTopLevelEnum(HWND Wnd, LPARAM lParam)
273 {
274 PNOTIFY_CONTEXT NotifyContext = (PNOTIFY_CONTEXT) lParam;
275 MESSAGE_CONTEXT MessageContext;
276 DWORD Now, Passed;
277 DWORD Timeout, WaitStatus;
278 DWORD ProcessId;
279 HANDLE MessageThread;
280 HANDLE Threads[2];
281
282 if (0 == GetWindowThreadProcessId(Wnd, &ProcessId))
283 {
284 NotifyContext->QueryResult = QUERY_RESULT_ERROR;
285 return FALSE;
286 }
287
288 if (ProcessId == NotifyContext->ProcessId)
289 {
290 Now = GetTickCount();
291 if (0 == NotifyContext->StartTime)
292 {
293 NotifyContext->StartTime = Now;
294 }
295 /* Note: Passed is computed correctly even when GetTickCount() wraps due
296 to unsigned arithmetic */
297 Passed = Now - NotifyContext->StartTime;
298 MessageContext.Wnd = Wnd;
299 MessageContext.Msg = NotifyContext->Msg;
300 MessageContext.wParam = NotifyContext->wParam;
301 MessageContext.lParam = NotifyContext->lParam;
302 MessageContext.Timeout = NotifyContext->ShutdownSettings->HungAppTimeout;
303 if (! NotifyContext->ShutdownSettings->AutoEndTasks)
304 {
305 MessageContext.Timeout += NotifyContext->ShutdownSettings->WaitToKillAppTimeout;
306 }
307 if (Passed < MessageContext.Timeout)
308 {
309 MessageContext.Timeout -= Passed;
310 MessageThread = CreateThread(NULL, 0, NotifyContext->SendMessageProc,
311 (LPVOID) &MessageContext, 0, NULL);
312 if (NULL == MessageThread)
313 {
314 NotifyContext->QueryResult = QUERY_RESULT_ERROR;
315 return FALSE;
316 }
317 Timeout = NotifyContext->ShutdownSettings->HungAppTimeout;
318 if (Passed < Timeout)
319 {
320 Timeout -= Passed;
321 WaitStatus = WaitForSingleObjectEx(MessageThread, Timeout, FALSE);
322 }
323 else
324 {
325 WaitStatus = WAIT_TIMEOUT;
326 }
327 if (WAIT_TIMEOUT == WaitStatus)
328 {
329 NotifyContext->WndClient = Wnd;
330 if (NULL == NotifyContext->UIThread && NotifyContext->ShowUI)
331 {
332 NotifyContext->UIThread = CreateThread(NULL, 0,
333 EndNowThreadProc,
334 (LPVOID) NotifyContext,
335 0, NULL);
336 }
337 Threads[0] = MessageThread;
338 Threads[1] = NotifyContext->UIThread;
339 WaitStatus = WaitForMultipleObjectsEx(NULL == NotifyContext->UIThread ?
340 1 : 2,
341 Threads, FALSE, INFINITE,
342 FALSE);
343 if (WAIT_OBJECT_0 == WaitStatus)
344 {
345 if (! GetExitCodeThread(MessageThread, &NotifyContext->QueryResult))
346 {
347 NotifyContext->QueryResult = QUERY_RESULT_ERROR;
348 }
349 }
350 else if (WAIT_OBJECT_0 + 1 == WaitStatus)
351 {
352 if (! GetExitCodeThread(NotifyContext->UIThread,
353 &NotifyContext->QueryResult))
354 {
355 NotifyContext->QueryResult = QUERY_RESULT_ERROR;
356 }
357 }
358 else
359 {
360 NotifyContext->QueryResult = QUERY_RESULT_ERROR;
361 }
362 if (WAIT_OBJECT_0 != WaitStatus)
363 {
364 TerminateThread(MessageThread, QUERY_RESULT_TIMEOUT);
365 }
366 }
367 else if (WAIT_OBJECT_0 == WaitStatus)
368 {
369 if (! GetExitCodeThread(MessageThread,
370 &NotifyContext->QueryResult))
371 {
372 NotifyContext->QueryResult = QUERY_RESULT_ERROR;
373 }
374 }
375 else
376 {
377 NotifyContext->QueryResult = QUERY_RESULT_ERROR;
378 }
379 CloseHandle(MessageThread);
380 }
381 else
382 {
383 NotifyContext->QueryResult = QUERY_RESULT_TIMEOUT;
384 }
385 }
386
387 return QUERY_RESULT_CONTINUE == NotifyContext->QueryResult;
388 }
389
390 static BOOL CALLBACK
391 NotifyDesktopEnum(LPWSTR DesktopName, LPARAM lParam)
392 {
393 PNOTIFY_CONTEXT Context = (PNOTIFY_CONTEXT) lParam;
394
395 Context->Desktop = OpenDesktopW(DesktopName, 0, FALSE,
396 DESKTOP_ENUMERATE | DESKTOP_SWITCHDESKTOP);
397 if (NULL == Context->Desktop)
398 {
399 DPRINT1("OpenDesktop failed with error %d\n", GetLastError());
400 Context->QueryResult = QUERY_RESULT_ERROR;
401 return FALSE;
402 }
403
404 Context->OldDesktop = GetThreadDesktop(GetCurrentThreadId());
405 SwitchDesktop(Context->Desktop);
406
407 EnumDesktopWindows(Context->Desktop, NotifyTopLevelEnum, lParam);
408
409 SwitchDesktop(Context->OldDesktop);
410
411 CloseDesktop(Context->Desktop);
412
413 return QUERY_RESULT_CONTINUE == Context->QueryResult;
414 }
415
416 static BOOL FASTCALL
417 NotifyTopLevelWindows(PNOTIFY_CONTEXT Context)
418 {
419 HWINSTA WindowStation;
420
421 WindowStation = GetProcessWindowStation();
422 if (NULL == WindowStation)
423 {
424 DPRINT1("GetProcessWindowStation failed with error %d\n", GetLastError());
425 return TRUE;
426 }
427
428 EnumDesktopsW(WindowStation, NotifyDesktopEnum, (LPARAM) Context);
429
430 return TRUE;
431 }
432
433 /*** Taken from win32ss/user/consrv/console.c ***/
434 static BOOL
435 DtbgIsDesktopVisible(VOID)
436 {
437 return !((BOOL)NtUserCallNoParam(NOPARAM_ROUTINE_ISCONSOLEMODE));
438 }
439
440 /* TODO: Find an other way to do it. */
441 #if 0
442 VOID FASTCALL
443 ConioConsoleCtrlEventTimeout(DWORD Event, PCSR_PROCESS ProcessData, DWORD Timeout)
444 {
445 HANDLE Thread;
446
447 DPRINT("ConioConsoleCtrlEvent Parent ProcessId = %x\n", ProcessData->ClientId.UniqueProcess);
448
449 if (ProcessData->CtrlDispatcher)
450 {
451
452 Thread = CreateRemoteThread(ProcessData->ProcessHandle, NULL, 0,
453 (LPTHREAD_START_ROUTINE) ProcessData->CtrlDispatcher,
454 UlongToPtr(Event), 0, NULL);
455 if (NULL == Thread)
456 {
457 DPRINT1("Failed thread creation (Error: 0x%x)\n", GetLastError());
458 return;
459 }
460 WaitForSingleObject(Thread, Timeout);
461 CloseHandle(Thread);
462 }
463 }
464 #endif
465 /************************************************/
466
467 static BOOL FASTCALL
468 NotifyAndTerminateProcess(PCSR_PROCESS ProcessData,
469 PSHUTDOWN_SETTINGS ShutdownSettings,
470 UINT Flags)
471 {
472 NOTIFY_CONTEXT Context;
473 HANDLE Process;
474 DWORD QueryResult = QUERY_RESULT_CONTINUE;
475
476 Context.QueryResult = QUERY_RESULT_CONTINUE;
477
478 if (0 == (Flags & EWX_FORCE))
479 {
480 // TODO: Find an other way whether or not the process has a console.
481 #if 0
482 if (NULL != ProcessData->Console)
483 {
484 ConioConsoleCtrlEventTimeout(CTRL_LOGOFF_EVENT, ProcessData,
485 ShutdownSettings->WaitToKillAppTimeout);
486 }
487 else
488 #endif
489 {
490 Context.ProcessId = (DWORD_PTR) ProcessData->ClientId.UniqueProcess;
491 Context.wParam = 0;
492 Context.lParam = (0 != (Flags & EWX_INTERNAL_FLAG_LOGOFF) ?
493 ENDSESSION_LOGOFF : 0);
494 Context.StartTime = 0;
495 Context.UIThread = NULL;
496 Context.ShowUI = DtbgIsDesktopVisible();
497 Context.Dlg = NULL;
498 Context.ShutdownSettings = ShutdownSettings;
499 Context.SendMessageProc = SendQueryEndSession;
500
501 NotifyTopLevelWindows(&Context);
502
503 Context.wParam = (QUERY_RESULT_ABORT != Context.QueryResult);
504 Context.lParam = (0 != (Flags & EWX_INTERNAL_FLAG_LOGOFF) ?
505 ENDSESSION_LOGOFF : 0);
506 Context.SendMessageProc = SendEndSession;
507 Context.ShowUI = DtbgIsDesktopVisible() &&
508 (QUERY_RESULT_ABORT != Context.QueryResult);
509 QueryResult = Context.QueryResult;
510 Context.QueryResult = QUERY_RESULT_CONTINUE;
511
512 NotifyTopLevelWindows(&Context);
513
514 if (NULL != Context.UIThread)
515 {
516 if (NULL != Context.Dlg)
517 {
518 SendMessageW(Context.Dlg, WM_CLOSE, 0, 0);
519 }
520 else
521 {
522 TerminateThread(Context.UIThread, QUERY_RESULT_ERROR);
523 }
524 CloseHandle(Context.UIThread);
525 }
526 }
527
528 if (QUERY_RESULT_ABORT == QueryResult)
529 {
530 return FALSE;
531 }
532 }
533
534 /* Terminate this process */
535 Process = OpenProcess(PROCESS_TERMINATE, FALSE,
536 (DWORD_PTR) ProcessData->ClientId.UniqueProcess);
537 if (NULL == Process)
538 {
539 DPRINT1("Unable to open process %d, error %d\n", ProcessData->ClientId.UniqueProcess,
540 GetLastError());
541 return TRUE;
542 }
543 TerminateProcess(Process, 0);
544 CloseHandle(Process);
545
546 return TRUE;
547 }
548
549 #if 0
550 static NTSTATUS WINAPI
551 ExitReactosProcessEnum(PCSR_PROCESS ProcessData, PVOID Data)
552 {
553 HANDLE Process;
554 HANDLE Token;
555 TOKEN_ORIGIN Origin;
556 DWORD ReturnLength;
557 PPROCESS_ENUM_CONTEXT Context = (PPROCESS_ENUM_CONTEXT) Data;
558 PCSR_PROCESS *NewData;
559
560 /* Do not kill winlogon or csrss */
561 if ((DWORD_PTR) ProcessData->ClientId.UniqueProcess == Context->CsrssProcess ||
562 ProcessData->ClientId.UniqueProcess == LogonProcessId)
563 {
564 return STATUS_SUCCESS;
565 }
566
567 /* Get the login session of this process */
568 Process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE,
569 (DWORD_PTR) ProcessData->ClientId.UniqueProcess);
570 if (NULL == Process)
571 {
572 DPRINT1("Unable to open process %d, error %d\n", ProcessData->ClientId.UniqueProcess,
573 GetLastError());
574 return STATUS_UNSUCCESSFUL;
575 }
576
577 if (! OpenProcessToken(Process, TOKEN_QUERY, &Token))
578 {
579 DPRINT1("Unable to open token for process %d, error %d\n",
580 ProcessData->ClientId.UniqueProcess, GetLastError());
581 CloseHandle(Process);
582 return STATUS_UNSUCCESSFUL;
583 }
584 CloseHandle(Process);
585
586 if (! GetTokenInformation(Token, TokenOrigin, &Origin,
587 sizeof(TOKEN_ORIGIN), &ReturnLength))
588 {
589 DPRINT1("GetTokenInformation failed for process %d with error %d\n",
590 ProcessData->ClientId.UniqueProcess, GetLastError());
591 CloseHandle(Token);
592 return STATUS_UNSUCCESSFUL;
593 }
594 CloseHandle(Token);
595
596 /* This process will be killed if it's in the correct logon session */
597 if (RtlEqualLuid(&(Context->TokenOrigin.OriginatingLogonSession),
598 &(Origin.OriginatingLogonSession)))
599 {
600 /* Kill the shell process last */
601 if ((DWORD_PTR) ProcessData->ClientId.UniqueProcess == Context->ShellProcess)
602 {
603 ProcessData->ShutdownLevel = 0;
604 }
605 NewData = HeapAlloc(UserServerHeap, 0, (Context->ProcessCount + 1)
606 * sizeof(PCSR_PROCESS));
607 if (NULL == NewData)
608 {
609 return STATUS_NO_MEMORY;
610 }
611 if (0 != Context->ProcessCount)
612 {
613 memcpy(NewData, Context->ProcessData,
614 Context->ProcessCount * sizeof(PCSR_PROCESS));
615 HeapFree(UserServerHeap, 0, Context->ProcessData);
616 }
617 Context->ProcessData = NewData;
618 Context->ProcessData[Context->ProcessCount] = ProcessData;
619 Context->ProcessCount++;
620 }
621
622 return STATUS_SUCCESS;
623 }
624 #endif
625
626 static int
627 ProcessDataCompare(const void *Elem1, const void *Elem2)
628 {
629 const PCSR_PROCESS *ProcessData1 = (PCSR_PROCESS *) Elem1;
630 const PCSR_PROCESS *ProcessData2 = (PCSR_PROCESS *) Elem2;
631
632 if ((*ProcessData1)->ShutdownLevel < (*ProcessData2)->ShutdownLevel)
633 {
634 return +1;
635 }
636 else if ((*ProcessData2)->ShutdownLevel < (*ProcessData1)->ShutdownLevel)
637 {
638 return -1;
639 }
640 else if ((*ProcessData1)->ClientId.UniqueProcess < (*ProcessData2)->ClientId.UniqueProcess)
641 {
642 return +1;
643 }
644 else if ((*ProcessData2)->ClientId.UniqueProcess < (*ProcessData1)->ClientId.UniqueProcess)
645 {
646 return -1;
647 }
648
649 return 0;
650 }
651
652 static DWORD FASTCALL
653 GetShutdownSettings(HKEY DesktopKey, LPCWSTR ValueName, DWORD DefaultValue)
654 {
655 BYTE ValueBuffer[16];
656 LONG ErrCode;
657 DWORD Type;
658 DWORD ValueSize;
659 UNICODE_STRING StringValue;
660 ULONG Value;
661
662 ValueSize = sizeof(ValueBuffer);
663 ErrCode = RegQueryValueExW(DesktopKey, ValueName, NULL, &Type, ValueBuffer,
664 &ValueSize);
665 if (ERROR_SUCCESS != ErrCode)
666 {
667 DPRINT("GetShutdownSettings for %S failed with error code %ld\n",
668 ValueName, ErrCode);
669 return DefaultValue;
670 }
671
672 if (REG_SZ == Type)
673 {
674 RtlInitUnicodeString(&StringValue, (LPCWSTR) ValueBuffer);
675 if (! NT_SUCCESS(RtlUnicodeStringToInteger(&StringValue, 10, &Value)))
676 {
677 DPRINT1("Unable to convert value %S for setting %S\n",
678 StringValue.Buffer, ValueName);
679 return DefaultValue;
680 }
681 return (DWORD) Value;
682 }
683 else if (REG_DWORD == Type)
684 {
685 return *((DWORD *) ValueBuffer);
686 }
687
688 DPRINT1("Unexpected registry type %d for setting %S\n", Type, ValueName);
689 return DefaultValue;
690 }
691
692 static void FASTCALL
693 LoadShutdownSettings(PSID Sid, PSHUTDOWN_SETTINGS ShutdownSettings)
694 {
695 static WCHAR Subkey[] = L"\\Control Panel\\Desktop";
696 LPWSTR StringSid;
697 WCHAR InitialKeyName[128];
698 LPWSTR KeyName;
699 HKEY DesktopKey;
700 LONG ErrCode;
701
702 ShutdownSettings->AutoEndTasks = DEFAULT_AUTO_END_TASKS;
703 ShutdownSettings->HungAppTimeout = DEFAULT_HUNG_APP_TIMEOUT;
704 ShutdownSettings->WaitToKillAppTimeout = DEFAULT_WAIT_TO_KILL_APP_TIMEOUT;
705
706 if (! ConvertSidToStringSidW(Sid, &StringSid))
707 {
708 DPRINT1("ConvertSidToStringSid failed with error %d, using default shutdown settings\n",
709 GetLastError());
710 return;
711 }
712 if (wcslen(StringSid) + wcslen(Subkey) + 1 <=
713 sizeof(InitialKeyName) / sizeof(WCHAR))
714 {
715 KeyName = InitialKeyName;
716 }
717 else
718 {
719 KeyName = HeapAlloc(UserServerHeap, 0,
720 (wcslen(StringSid) + wcslen(Subkey) + 1) *
721 sizeof(WCHAR));
722 if (NULL == KeyName)
723 {
724 DPRINT1("Failed to allocate memory, using default shutdown settings\n");
725 LocalFree(StringSid);
726 return;
727 }
728 }
729 wcscat(wcscpy(KeyName, StringSid), Subkey);
730 LocalFree(StringSid);
731
732 ErrCode = RegOpenKeyExW(HKEY_USERS, KeyName, 0, KEY_QUERY_VALUE, &DesktopKey);
733 if (KeyName != InitialKeyName)
734 {
735 HeapFree(UserServerHeap, 0, KeyName);
736 }
737 if (ERROR_SUCCESS != ErrCode)
738 {
739 DPRINT1("RegOpenKeyEx failed with error %ld, using default shutdown settings\n", ErrCode);
740 return;
741 }
742
743 ShutdownSettings->AutoEndTasks = (BOOL) GetShutdownSettings(DesktopKey, L"AutoEndTasks",
744 (DWORD) DEFAULT_AUTO_END_TASKS);
745 ShutdownSettings->HungAppTimeout = GetShutdownSettings(DesktopKey,
746 L"HungAppTimeout",
747 DEFAULT_HUNG_APP_TIMEOUT);
748 ShutdownSettings->WaitToKillAppTimeout = GetShutdownSettings(DesktopKey,
749 L"WaitToKillAppTimeout",
750 DEFAULT_WAIT_TO_KILL_APP_TIMEOUT);
751
752 RegCloseKey(DesktopKey);
753 }
754
755 static NTSTATUS FASTCALL
756 InternalExitReactos(DWORD ProcessId, DWORD ThreadId, UINT Flags)
757 {
758 HANDLE CallerThread;
759 HANDLE CallerToken;
760 NTSTATUS Status;
761 PROCESS_ENUM_CONTEXT Context;
762 DWORD ReturnLength;
763 HWND ShellWnd;
764 UINT ProcessIndex;
765 char FixedUserInfo[64];
766 TOKEN_USER *UserInfo;
767 SHUTDOWN_SETTINGS ShutdownSettings;
768
769 if (ProcessId != (DWORD_PTR) LogonProcessId)
770 {
771 DPRINT1("Internal ExitWindowsEx call not from winlogon\n");
772 return STATUS_ACCESS_DENIED;
773 }
774
775 DPRINT1("FIXME: Need to close all user processes!\n");
776 return STATUS_SUCCESS;
777
778 CallerThread = OpenThread(THREAD_QUERY_INFORMATION, FALSE, ThreadId);
779 if (NULL == CallerThread)
780 {
781 DPRINT1("OpenThread failed with error %d\n", GetLastError());
782 return STATUS_UNSUCCESSFUL;
783 }
784 if (! OpenThreadToken(CallerThread, TOKEN_QUERY, FALSE, &CallerToken))
785 {
786 DPRINT1("OpenThreadToken failed with error %d\n", GetLastError());
787 CloseHandle(CallerThread);
788 return STATUS_UNSUCCESSFUL;
789 }
790 CloseHandle(CallerThread);
791
792 Context.ProcessCount = 0;
793 Context.ProcessData = NULL;
794 if (! GetTokenInformation(CallerToken, TokenOrigin, &Context.TokenOrigin,
795 sizeof(TOKEN_ORIGIN), &ReturnLength))
796 {
797 DPRINT1("GetTokenInformation failed with error %d\n", GetLastError());
798 CloseHandle(CallerToken);
799 return STATUS_UNSUCCESSFUL;
800 }
801 if (! GetTokenInformation(CallerToken, TokenUser, FixedUserInfo,
802 sizeof(FixedUserInfo), &ReturnLength))
803 {
804 if (sizeof(FixedUserInfo) < ReturnLength)
805 {
806 UserInfo = HeapAlloc(UserServerHeap, 0, ReturnLength);
807 if (NULL == UserInfo)
808 {
809 DPRINT1("Unable to allocate %u bytes for user info\n",
810 (unsigned) ReturnLength);
811 CloseHandle(CallerToken);
812 return STATUS_NO_MEMORY;
813 }
814 if (! GetTokenInformation(CallerToken, TokenUser, UserInfo,
815 ReturnLength, &ReturnLength))
816 {
817 DPRINT1("GetTokenInformation failed with error %d\n",
818 GetLastError());
819 HeapFree(UserServerHeap, 0, UserInfo);
820 CloseHandle(CallerToken);
821 return STATUS_UNSUCCESSFUL;
822 }
823 }
824 else
825 {
826 DPRINT1("GetTokenInformation failed with error %d\n", GetLastError());
827 CloseHandle(CallerToken);
828 return STATUS_UNSUCCESSFUL;
829 }
830 }
831 else
832 {
833 UserInfo = (TOKEN_USER *) FixedUserInfo;
834 }
835 CloseHandle(CallerToken);
836 LoadShutdownSettings(UserInfo->User.Sid, &ShutdownSettings);
837 if (UserInfo != (TOKEN_USER *) FixedUserInfo)
838 {
839 HeapFree(UserServerHeap, 0, UserInfo);
840 }
841 Context.CsrssProcess = GetCurrentProcessId();
842 ShellWnd = GetShellWindow();
843 if (NULL == ShellWnd)
844 {
845 DPRINT("No shell present\n");
846 Context.ShellProcess = 0;
847 }
848 else if (0 == GetWindowThreadProcessId(ShellWnd, &Context.ShellProcess))
849 {
850 DPRINT1("Can't get process id of shell window\n");
851 Context.ShellProcess = 0;
852 }
853
854 // Status = Win32CsrEnumProcesses(ExitReactosProcessEnum, &Context);
855 if (! NT_SUCCESS(Status))
856 {
857 DPRINT1("Failed to enumerate registered processes, status 0x%x\n",
858 Status);
859 if (NULL != Context.ProcessData)
860 {
861 HeapFree(UserServerHeap, 0, Context.ProcessData);
862 }
863 return Status;
864 }
865
866 qsort(Context.ProcessData, Context.ProcessCount, sizeof(PCSR_PROCESS),
867 ProcessDataCompare);
868
869 /* Terminate processes, stop if we find one kicking and screaming it doesn't
870 want to die */
871 Status = STATUS_SUCCESS;
872 for (ProcessIndex = 0;
873 ProcessIndex < Context.ProcessCount && NT_SUCCESS(Status);
874 ProcessIndex++)
875 {
876 if (! NotifyAndTerminateProcess(Context.ProcessData[ProcessIndex],
877 &ShutdownSettings, Flags))
878 {
879 Status = STATUS_REQUEST_ABORTED;
880 }
881 }
882
883 /* Cleanup */
884 if (NULL != Context.ProcessData)
885 {
886 HeapFree(UserServerHeap, 0, Context.ProcessData);
887 }
888
889 return Status;
890 }
891
892 static NTSTATUS FASTCALL
893 UserExitReactos(DWORD UserProcessId, UINT Flags)
894 {
895 NTSTATUS Status;
896
897 /* FIXME Inside 2000 says we should impersonate the caller here */
898 Status = NtUserCallTwoParam(UserProcessId, Flags, TWOPARAM_ROUTINE_EXITREACTOS);
899
900 /* If the message isn't handled, the return value is 0, so 0 doesn't indicate
901 success. Success is indicated by a 1 return value, if anything besides 0
902 or 1 it's a NTSTATUS value */
903 if (1 == Status)
904 {
905 Status = STATUS_SUCCESS;
906 }
907 else if (0 == Status)
908 {
909 Status = STATUS_NOT_IMPLEMENTED;
910 }
911
912 return Status;
913 }
914
915
916 /* PUBLIC SERVER APIS *********************************************************/
917
918 CSR_API(SrvExitWindowsEx)
919 {
920 PUSER_EXIT_REACTOS ExitReactosRequest = &((PUSER_API_MESSAGE)ApiMessage)->Data.ExitReactosRequest;
921
922 if (0 == (ExitReactosRequest->Flags & EWX_INTERNAL_FLAG))
923 {
924 return UserExitReactos((DWORD_PTR) ApiMessage->Header.ClientId.UniqueProcess,
925 ExitReactosRequest->Flags);
926 }
927 else
928 {
929 return InternalExitReactos((DWORD_PTR) ApiMessage->Header.ClientId.UniqueProcess,
930 (DWORD_PTR) ApiMessage->Header.ClientId.UniqueThread,
931 ExitReactosRequest->Flags);
932 }
933 }
934
935 /* EOF */