summaryrefslogtreecommitdiffstats
path: root/private/windows/gina/winlogon/sysshut.c
blob: 65ff4c55fa318171c4bc46fbd8203bf4db89ad89 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
/*++

Copyright (c) 1992  Microsoft Corporation

Module Name:

    Shutdown.c

Abstract:

    This module contains the server side implementation for the Win32 remote
    shutdown APIs, that is:

        - BaseInitiateSystemShutdown
        - BaseAbortSystemShutdown

Author:

    Dave Chalmers (davidc) 29-Apr-1992

Notes:


Revision History:

    19-Oct-1993     Danl
        Removed HackExtraThread which was only here to work around a bug in
        the UserSrv.  The text describing the reason for this workaround is
        as follows:
        HACKHACK - Work around bug in UserSrv that causes ExitWindowsEx to
            fail (error 5) when called by a process which doesn't
            have any threads which have called User APIs.  Remove
            after UserSrv is fixed.  See NTBUG 11601.
            Workaround is to create a thread which will make one
            API call then sleep forever.

--*/


#include "precomp.h"
#pragma hdrstop

#define RPC_NO_WINDOWS_H
#include "regrpc.h"
#include "ntrpcp.h"
#include <rpc.h>

// // // // // //

//
// Shutdown Dialog Return Codes:
//

#define SHUTDOWN_SUCCESS        0
#define SHUTDOWN_USER_LOGOFF    1
#define SHUTDOWN_DESKTOP_SWITCH 2
#define SHUTDOWN_CANCELLED      3

//
// System Shutdown globals
//

RTL_CRITICAL_SECTION ShutdownCriticalSection; // Protect global shutdown data

//
// Set when a thread has a shutdown 'in progress'
// (Protected by critical section)
//

BOOL ShutdownInProgress;

//
// Set when a thread wants to interrupt the shutdown
// (Protected by critical section)
//

BOOL AbortShutdown;


//
// Data for shutdown UI - this is protected by the ShutdownInProgress flag.
// i.e. only the current shutdown thread manipulates this data.
//

LARGE_INTEGER ShutdownTime;
DWORD ShutdownDelayInSeconds;
PTCH ShutdownMessage;
DWORD ExitWindowsFlags;
DWORD GinaCode;
PTSTR UserName;
PTSTR UserDomain;
BOOL AllowLogonDuringShutdown = TRUE ;
ActiveDesktops  ShutdownDesktop;
WINDOWPLACEMENT ShutdownWindowPlacement;
BOOL ShutdownGetPlacement = FALSE;
BOOL ShutdownHasBegun = FALSE;

//
// Data captured during initialization
//

PGLOBALS GlobalWinMainData;





//
// Private prototypes
//


DWORD
InitializeShutdownData(
    PUNICODE_STRING lpMessage,
    DWORD dwTimeout,
    BOOL bForceAppsClosed,
    BOOL bRebootAfterShutdown
    );

VOID
FreeShutdownData(
    VOID
    );

BOOL WINAPI
ShutdownApiDlgProc(
    HWND    hDlg,
    UINT    message,
    WPARAM  wParam,
    LPARAM  lParam
    );

BOOL
UpdateTimeToShutdown(
    HWND    hDlg
    );

VOID
CentreWindow(
    HWND    hwnd
    );

DWORD
TestClientPrivilege(
    VOID
    );

DWORD
GetClientId(
    PTSTR *UserName,
    PTSTR *UserDomain
    );

VOID
DeleteClientId(
    PTSTR UserName,
    PTSTR UserDomain
    );

BOOL
InsertClientId(
    HWND hDlg,
    int ControlId,
    PTSTR UserName,
    PTSTR UserDomain
    );





BOOL
InitializeShutdownModule(
    PGLOBALS pGlobals
    )
/*++

Routine Description:

    Does any initializtion required for this module.

Arguments:

    pGlobals - Pointer to global data defined in WinMain

Return Value:

    Returns TRUE on success, FALSE on failure.

--*/
{
    NTSTATUS Status;

    //
    // Initialize global variables
    //

    ShutdownInProgress = FALSE;

    //
    // Initialize critical section to protect globals
    //

    Status = RtlInitializeCriticalSection(&ShutdownCriticalSection);

#if DBG
    if (!NT_SUCCESS(Status)) {
        DbgPrint("Registry Server : Shutdown : Failed to initialize critical section\n");
    }
#endif

    GlobalWinMainData = pGlobals;
    return(NT_SUCCESS(Status));
}

ULONG
BaseInitiateSystemShutdown(
    IN PREGISTRY_SERVER_NAME ServerName,
    IN PUNICODE_STRING lpMessage OPTIONAL,
    IN DWORD dwTimeout,
    IN BOOLEAN bForceAppsClosed,
    IN BOOLEAN bRebootAfterShutdown
    )
/*++

Routine Description:

    Initiates the shutdown of this machine.

Arguments:

    ServerName - Name of machine this server code is running on. (Ignored)

    lpMessage - message to display during shutdown timeout period.

    dwTimeout - number of seconds to delay before shutting down

    bForceAppsClosed - Normally applications may prevent system shutdown.
              - If this true, all applications are terminated unconditionally.

    bRebootAfterShutdown - TRUE if the system should reboot. FALSE if it should
              - be left in a shutdown state.

Return Value:

    Returns ERROR_SUCCESS (0) for success; error-code for failure.

--*/

{
    NTSTATUS Status;
    DWORD Error;

    //
    // Check the caller has the appropriate privilege
    //

    Error = TestClientPrivilege();
    if (Error != ERROR_SUCCESS) {
        return(Error);
    }

    //
    // Enter the critical section so we can look at our globals
    //

    Status = RtlEnterCriticalSection(&ShutdownCriticalSection);
    if (!NT_SUCCESS(Status)) {
        return(RtlNtStatusToDosError(Status));
    }

    //
    // Set up our global shutdown data.
    // Fail if a shutdown is already in progress
    //

    if (ShutdownInProgress) {
        Error = ERROR_SHUTDOWN_IN_PROGRESS;
    } else {

        //
        // Set up our globals for the shutdown thread to use.
        //

        Error = InitializeShutdownData(lpMessage,
                                       dwTimeout,
                                       bForceAppsClosed,
                                       bRebootAfterShutdown
                                      );
        if (Error == ERROR_SUCCESS) {
            ShutdownInProgress = TRUE;
            AbortShutdown = FALSE;
        }
    }

    //
    // Leave the critical section
    //

    Status = RtlLeaveCriticalSection(&ShutdownCriticalSection);
    if (Error == ERROR_SUCCESS) {
        if (!NT_SUCCESS(Status)) {
            Error = RtlNtStatusToDosError(Status);
        }
    } else {
        ASSERT(NT_SUCCESS(Status));
    }



    //
    // Create a thread to handle the shutdown (UI and calling ExitWindows)
    // The thread will handle resetting our shutdown data and globals.
    //

    if (Error == ERROR_SUCCESS) {
        int Result;

        //
        // Have winlogon create us a thread running on the user's desktop.
        //
        // The thread will do a call back to ShutdownThread()
        //

        GlobalWinMainData->LogoffFlags = EWX_WINLOGON_API_SHUTDOWN | ExitWindowsFlags;
        Result = InitiateLogoff( GlobalWinMainData,
                                 EWX_WINLOGON_API_SHUTDOWN | ExitWindowsFlags );


        if (Result != DLG_SUCCESS ) {
            Error = GetLastError();
            KdPrint(("InitiateSystemShutdown : Failed to create shutdown thread. Error = %d\n", Error));
            FreeShutdownData();
            ShutdownInProgress = FALSE; // Atomic operation
        }
    }

    return(Error);

    UNREFERENCED_PARAMETER(ServerName);
}



DWORD
InitializeShutdownData(
    PUNICODE_STRING lpMessage,
    DWORD dwTimeout,
    BOOL bForceAppsClosed,
    BOOL bRebootAfterShutdown
    )
/*++

Routine Description:

    Stores the passed shutdown parameters in our global data.

Return Value:

    Returns ERROR_SUCCESS (0) for success; error-code for failure.

--*/

{
    NTSTATUS Status;
    LARGE_INTEGER TimeNow;
    LARGE_INTEGER Delay;
    DWORD Error;

    //
    // Set the shutdown time
    //

    ShutdownDelayInSeconds = dwTimeout;

    Status = NtQuerySystemTime(&TimeNow);
    if (!NT_SUCCESS(Status)) {
        return(RtlNtStatusToDosError(Status));
    }

    Delay = RtlEnlargedUnsignedMultiply(dwTimeout, 10000000);   // Delay in 100ns

    ShutdownTime.QuadPart = TimeNow.QuadPart + Delay.QuadPart;


    //
    // Set the shutdown flags
    //
    // We set the EWX_WINLOGON_OLD_xxx and EWX_xxx both since this message
    // originates from the winlogon process.  When these flags actually bubble
    // back to the active dialog box, winlogon expects the EWX_WINLOGON_OLD_xxx
    // to indicate the 'real' request.
    //

    ExitWindowsFlags = EWX_LOGOFF | EWX_SHUTDOWN | EWX_WINLOGON_OLD_SHUTDOWN;
    ExitWindowsFlags |= bForceAppsClosed ? EWX_FORCE : 0;
    ExitWindowsFlags |= bRebootAfterShutdown ?
                        (EWX_REBOOT | EWX_WINLOGON_OLD_REBOOT) : 0;

    if (bRebootAfterShutdown)
    {
        GinaCode = WLX_SAS_ACTION_SHUTDOWN_REBOOT;
    }
    else
    {
        GinaCode = WLX_SAS_ACTION_SHUTDOWN;
    }


    //
    // Store the caller's username and domain.
    //

    Error = GetClientId(&UserName, &UserDomain);
    if (Error != ERROR_SUCCESS) {
        return(Error);
    }


    //
    // Set the shutdown message
    //

    if (lpMessage != NULL) {

        //
        // Copy the message into a global buffer
        //

        USHORT Bytes = lpMessage->Length + (USHORT)sizeof(UNICODE_NULL);

        ShutdownMessage = (PTCH)LocalAlloc(LPTR, Bytes);
        if (ShutdownMessage == NULL) {
            DeleteClientId(UserName, UserDomain);
            return(ERROR_NOT_ENOUGH_MEMORY);
        }

        RtlMoveMemory(ShutdownMessage, lpMessage->Buffer, lpMessage->Length);
        ShutdownMessage[lpMessage->Length / sizeof(WCHAR)] = 0; // Null terminate

    } else {
        ShutdownMessage = NULL;
    }


    return(ERROR_SUCCESS);
}



VOID
FreeShutdownData(
    VOID
    )
/*++

Routine Description:

    Frees up any memory allocated to store the shutdown data

Return Value:

    None.

--*/

{
    if (ShutdownMessage != NULL) {
        LocalFree(ShutdownMessage);
        ShutdownMessage = NULL;
    }

    DeleteClientId(UserName, UserDomain);
    UserName = NULL;
    UserDomain = NULL;
}



BOOLEAN
ShutdownThread(
    VOID
    )
/*++

Routine Description:

    Handles the display of a shutdown dialog and coordinating with the
    AbortShutdown API.

Arguments:

    None

Return Value:

    TRUE - system should be shut down
    FALSE - shutdown was aborted

--*/
{
    NTSTATUS Status;
    DWORD Error;
    BOOL DoShutdown = TRUE;
    HDESK hdesk;
    BOOL CloseDesktopHandle;
    DWORD Result;
    BOOL Locked;
    BOOL Success;

    //
    // Quick check so we don't get into thorny race conditions.
    //

    if ( ShutdownDelayInSeconds == 0 )
    {

        FreeShutdownData();

        RtlEnterCriticalSection( &ShutdownCriticalSection );

        ShutdownInProgress = FALSE ;

        RtlLeaveCriticalSection( &ShutdownCriticalSection );

        GlobalWinMainData->LastGinaRet = GinaCode;

        ShutdownHasBegun = TRUE;

        return( TRUE );

    }


    hdesk = GetActiveDesktop(&GlobalWinMainData->WindowStation,
                             &CloseDesktopHandle,
                             &Locked);

    while (hdesk != NULL)
    {
        DebugLog((DEB_TRACE, "Starting shutdown dialog on desktop %x\n", hdesk));

        if (Locked)
        {
            UnlockWindowStation(GlobalWinMainData->WindowStation.hwinsta);
        }

        Success = SetThreadDesktop(hdesk);
        if (!Success)
        {
            DebugLog((DEB_TRACE, "Unable to set desktop, %d\n", GetLastError()));
        }

        if (Locked)
        {
            LockWindowStation(GlobalWinMainData->WindowStation.hwinsta);
        }

        ShutdownDesktop = GlobalWinMainData->WindowStation.ActiveDesktop;


        //
        // Push the timeout past the shutdown delay, so that we can
        // catch the messages we want, without stomping on the timeout
        // structures.
        //
        Result = DialogBoxParam( GetModuleHandle(NULL),
                                 MAKEINTRESOURCE( IDD_SYSTEM_SHUTDOWN ),
                                 NULL,
                                 ShutdownApiDlgProc,
                                 (LPARAM) 0 );

        DebugLog((DEB_TRACE, "Shutdown Dialog Returned %d\n", Result ));



        if (CloseDesktopHandle)
        {
            CloseDesktop( hdesk );
        }

        if ((Result == SHUTDOWN_SUCCESS) ||
            (Result == SHUTDOWN_CANCELLED) )
        {
            break;
        }

        //
        // Trickier ones:
        //

        if (Result == SHUTDOWN_USER_LOGOFF)
        {
            if (!AllowLogonDuringShutdown)
            {
                break;
            }

        }

        ShutdownGetPlacement = TRUE;

        hdesk = GetActiveDesktop(&GlobalWinMainData->WindowStation,
                                 &CloseDesktopHandle,
                                 &Locked);

        DebugLog((DEB_TRACE, "Switching to current desktop and restarting dialog\n"));

    }

    //
    // The shutdown has either completed or been cancelled
    // Reset our globals.
    //
    // Note we need to reset the shutdown-in-progress flag before
    // entering the non-abortable part of shutdown so that anyone
    // trying to abort from here on in will get a failure return code.
    //

    FreeShutdownData();


    Status = RtlEnterCriticalSection(&ShutdownCriticalSection);
    Error = RtlNtStatusToDosError(Status);

    if (Error == ERROR_SUCCESS) {

        //
        // Reset the global shutdown-in-progress flag
        // and check for an abort request.
        //

        if (AbortShutdown) {
            DoShutdown = FALSE;
        }

        ShutdownInProgress = FALSE;

        //
        // Leave the critical section
        //

        Status = RtlLeaveCriticalSection(&ShutdownCriticalSection);
        if (!NT_SUCCESS(Status)) {
            Error = RtlNtStatusToDosError(Status);
        }
    }

    //
    // If DoShutdown, update the last gina ret so that
    // the shutdown code will know what to do:
    //

    if ( DoShutdown )
    {
        GlobalWinMainData->LastGinaRet = GinaCode;

        ShutdownHasBegun = TRUE;
    }



    //
    // Tell the caller if he should shut down.
    //

    return DoShutdown;

}



BOOL WINAPI
ShutdownApiDlgProc(
    HWND    hDlg,
    UINT    message,
    WPARAM  wParam,
    LPARAM  lParam
    )
/*++

Routine Description:

    Processes messages for the shutdown dialog

    Dialog returns ERROR_SUCCESS if shutdown should proceed,
    ERROR_OPERATION_ABORTED if shutdown should be cancelled.

--*/
{
    HMENU hMenu;

    switch (message) {

    case WM_INITDIALOG:

        //
        // Add the caller's id to the main message text
        //

        InsertClientId(hDlg, IDD_SYSTEM_MESSAGE, UserName, UserDomain);

        //
        // Setup the client's message
        //

        SetDlgItemText(hDlg, IDD_MESSAGE, ShutdownMessage);

        //
        // Remove the close item from the system menu
        //

        hMenu = GetSystemMenu(hDlg, FALSE);
        DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);

        //
        // Position ourselves
        //

        if ( ShutdownGetPlacement )
        {
            SetWindowPlacement( hDlg, &ShutdownWindowPlacement );
        }
        else
        {
            CentreWindow(hDlg);
        }

        SetWindowPos( hDlg, HWND_TOPMOST, 0, 0, 0, 0,
                        SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW );


        //
        // Start the timer
        //

        SetTimer(hDlg, 0, 1000, NULL);  // 1 second timer

        //
        // Check if it's over before we've even started
        //

        if (UpdateTimeToShutdown(hDlg)) {

            // It's already time to shutdown
            EndDialog(hDlg, SHUTDOWN_SUCCESS);
        }

        //
        // Let everyone know what state we're in
        //

        GlobalWinMainData->PreviousWinlogonState = GlobalWinMainData->WinlogonState;
        GlobalWinMainData->WinlogonState = Winsta_InShutdownDlg;

//        GlobalWinMainData->ShutdownStarted = TRUE;

        return(TRUE);


    case WM_TIMER:

        //
        // Check for abort flag
        //

        if (AbortShutdown) {
            if (GlobalWinMainData->WinlogonState == Winsta_InShutdownDlg) {
                GlobalWinMainData->WinlogonState = GlobalWinMainData->PreviousWinlogonState;
            }
//            GlobalWinMainData->ShutdownStarted = FALSE;
            EndDialog(hDlg, SHUTDOWN_CANCELLED);
            return(TRUE);
        }

        if ( GlobalWinMainData->WindowStation.ActiveDesktop != ShutdownDesktop )
        {
            GetWindowPlacement( hDlg, &ShutdownWindowPlacement );
            EndDialog( hDlg, SHUTDOWN_DESKTOP_SWITCH );
            return( TRUE );
        }

        //
        // Update the time delay and check if our time's up
        //

        if (!UpdateTimeToShutdown(hDlg)) {

            //
            // Keep waiting
            //

            return(TRUE);
        }

        //
        // Shutdown time has arrived. Drop through...
        //

    case WLX_WM_SAS:


        DebugLog((DEB_TRACE, "Sas message received?  wParam = %d\n", wParam ));
        if ((wParam == WLX_SAS_TYPE_SCRNSVR_TIMEOUT) &&
            (message == WLX_WM_SAS)) {

           //
           // Don't end the dialog if it's just a screen saver timeout
           //

           return(TRUE);

        } else if ((wParam == WLX_SAS_TYPE_CTRL_ALT_DEL) &&
                   (message == WLX_WM_SAS)) {

           //
           // Also don't end the dialog if it's a Ctrl-Alt-Del
           //

           Sleep (1000);
           return(TRUE);

        } else {

           //
           // If the user logs off, preempt the timeout, restore the state
           //

           if (GlobalWinMainData->WinlogonState == Winsta_InShutdownDlg) {
               GlobalWinMainData->WinlogonState = GlobalWinMainData->PreviousWinlogonState;
           }

           EndDialog(hDlg, SHUTDOWN_SUCCESS);

           return(TRUE);

        }

    }

    // We didn't process this message
    return FALSE;

    UNREFERENCED_PARAMETER(lParam);
}




BOOL
UpdateTimeToShutdown(
    HWND    hDlg
    )
/*++

Routine Description:

    Updates the display of the time to system shutdown.

Returns:

    TRUE if shutdown time has arrived, otherwise FALSE

--*/
{
    NTSTATUS Status;
    BOOLEAN Success;
    LARGE_INTEGER TimeNow;
    ULONG ElapsedSecondsNow;
    ULONG ElapsedSecondsAtShutdown;
    ULONG SecondsRemaining;
    ULONG DaysRemaining;
    ULONG HoursRemaining;
    ULONG MinutesRemaining;
    TCHAR Message[40];

    //
    // Set the shutdown time
    //

    Status = NtQuerySystemTime(&TimeNow);
    ASSERT(NT_SUCCESS(Status));

    if (TimeNow.QuadPart >= ShutdownTime.QuadPart)
    {
        return(TRUE);
    }

    Success = RtlTimeToSecondsSince1980(&TimeNow, &ElapsedSecondsNow);
    ASSERT(Success);

    Success = RtlTimeToSecondsSince1980(&ShutdownTime, &ElapsedSecondsAtShutdown);
    ASSERT(Success);

    SecondsRemaining = ElapsedSecondsAtShutdown - ElapsedSecondsNow;

    //
    // Convert the seconds remaining to a string
    //

    MinutesRemaining = SecondsRemaining / 60;
    HoursRemaining = MinutesRemaining / 60;
    DaysRemaining = HoursRemaining / 24;

    SecondsRemaining = SecondsRemaining % 60;
    MinutesRemaining = MinutesRemaining % 60;
    HoursRemaining = HoursRemaining % 24;

    if (DaysRemaining > 0) {
        wsprintf(Message, TEXT("%d days"), DaysRemaining);
    } else {
        wsprintf(Message, TEXT("%02d:%02d:%02d"), HoursRemaining, MinutesRemaining, SecondsRemaining);
    }

    SetDlgItemText(hDlg, IDD_TIMER, Message);

    return(FALSE);
}



ULONG
BaseAbortSystemShutdown(
    IN PREGISTRY_SERVER_NAME ServerName
    )
/*++

Routine Description:

    Aborts a pending shutdown of this machine.

Arguments:

    ServerName - Name of machine this server code is running on. (Ignored)

Return Value:

    Returns ERROR_SUCCESS (0) for success; error-code for failure.

--*/

{
    NTSTATUS Status;
    DWORD Error;

    //
    // Check the caller has the appropriate privilege
    //

    Error = TestClientPrivilege();
    if (Error != ERROR_SUCCESS) {
        return(Error);
    }

    //
    // Enter the critical section so we can look at our globals
    //

    Status = RtlEnterCriticalSection(&ShutdownCriticalSection);
    if (!NT_SUCCESS(Status)) {
        return(RtlNtStatusToDosError(Status));
    }


    //
    // If a shutdown is in progress, set the abort flag
    //

    if (ShutdownInProgress) {
        AbortShutdown = TRUE;
        Error = ERROR_SUCCESS;
    } else
    {
        if ( ShutdownHasBegun )
        {
            Error = ERROR_SHUTDOWN_IN_PROGRESS;
        }
        else
        {
            Error = ERROR_NO_SHUTDOWN_IN_PROGRESS;
        }
    }

    //
    // Leave the critical section
    //

    Status = RtlLeaveCriticalSection(&ShutdownCriticalSection);
    if (Error == ERROR_SUCCESS) {
        if (!NT_SUCCESS(Status)) {
            Error = RtlNtStatusToDosError(Status);
        }
    } else {
        ASSERT(NT_SUCCESS(Status));
    }

    return(Error);

    UNREFERENCED_PARAMETER(ServerName);
}



DWORD
TestClientPrivilege(
    VOID
    )
/*++

Routine Description:

    Checks if the client has the privilege to perform the requested shutdown.

Arguments:

    None

Return Value:

    ERROR_SUCCESS if the client has the appropriate privilege.

    ERROR_ACCESS_DENIED - client does not have the required privilege

--*/
{
    NTSTATUS Status, IgnoreStatus;
    BOOL LocalConnection;
    LUID PrivilegeRequired;
    PRIVILEGE_SET PrivilegeSet;
    BOOLEAN Privileged;
    USER_SESSION_KEY SessionKey;
    HANDLE Token;

    UNICODE_STRING SubSystemName;   // LATER this should be global
    RtlInitUnicodeString(&SubSystemName, L"Win32 Registry/SystemShutdown module");

    //
    // Find out if this is a local connection
    //

    Status = RtlGetUserSessionKeyServer(NULL, &SessionKey);
    if (NT_SUCCESS(Status)) {

        LocalConnection = (Status == STATUS_LOCAL_USER_SESSION_KEY);

        if (LocalConnection) {
            PrivilegeRequired = RtlConvertLongToLuid(SE_SHUTDOWN_PRIVILEGE);
        } else {
            PrivilegeRequired = RtlConvertLongToLuid(SE_REMOTE_SHUTDOWN_PRIVILEGE);
        }


        //
        // See if the client has the required privilege
        //

        Status = I_RpcMapWin32Status(RpcImpersonateClient( NULL ));
        if (NT_SUCCESS(Status)) {

            PrivilegeSet.PrivilegeCount = 1;
            PrivilegeSet.Control = PRIVILEGE_SET_ALL_NECESSARY;
            PrivilegeSet.Privilege[0].Luid = PrivilegeRequired;
            PrivilegeSet.Privilege[0].Attributes = 0;

            Status = NtOpenThreadToken( NtCurrentThread(),
                                        TOKEN_QUERY,
                                        TRUE,
                                        &Token);
            if (NT_SUCCESS(Status)) {

                Status = NtPrivilegeCheck(Token,
                                          &PrivilegeSet,
                                          &Privileged);

                if (NT_SUCCESS(Status) || (Status == STATUS_PRIVILEGE_NOT_HELD)) {

                    Status = NtPrivilegeObjectAuditAlarm(
                                            &SubSystemName,
                                            NULL,
                                            Token,
                                            0,
                                            &PrivilegeSet,
                                            Privileged);
                }

                IgnoreStatus = NtClose(Token);
                ASSERT(NT_SUCCESS(IgnoreStatus));
            }

        }

        IgnoreStatus = I_RpcMapWin32Status(RpcRevertToSelf());
        ASSERT( NT_SUCCESS(IgnoreStatus) );
    }


    //
    // Handle unexpected errors
    //

    if (!NT_SUCCESS(Status)) {
        return(RtlNtStatusToDosError(Status));
    }


    //
    // If they failed the privilege check, return an error
    //

    if (!Privileged) {
        return(ERROR_ACCESS_DENIED);
    }

    //
    // They passed muster
    //

    return(ERROR_SUCCESS);
}




DWORD
GetClientId(
    PTSTR *UserName,
    PTSTR *UserDomain
    )
/*++

Routine Description:

    Gets the name and domain of the caller, allocates and returns pointers
    to the information.

    Note we have RPC impersonate the client to discover their ID.

Arguments:

    UserName - a pointer to a NULL terminated string containing the client's
               user name is returned here.

    DomainName - a pointer to a NULL terminated string containing the client's
               domain name is returned here.

    The caller should free UserName and DomainName by calling DeleteClientId

Return Value:

    ERROR_SUCCESS - UserName and UserDomain contain valid pointers

    Other - UserName and UserDomain are invalid

--*/
{
    HANDLE  TokenHandle;
    DWORD   cbNeeded;
    PTOKEN_USER pUserToken;
    BOOL    ReturnValue=FALSE;
    DWORD   cbDomain;
    DWORD   cbName;
    SID_NAME_USE SidNameUse;
    DWORD Error;
    DWORD IgnoreError;

    //
    // Prepare for failure
    //

    *UserName = NULL;
    *UserDomain = NULL;


    Error = RpcImpersonateClient(NULL);
    if (Error != ERROR_SUCCESS) {
        return(Error);
    }

    if (OpenThreadToken(GetCurrentThread(),
                         TOKEN_QUERY,
                         FALSE,
                         &TokenHandle)) {
        //
        // Get the user Sid
        //

        if (!GetTokenInformation(TokenHandle, TokenUser,  (PVOID)NULL, 0, &cbNeeded)) {

            if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {

                pUserToken = (PTOKEN_USER)LocalAlloc(LPTR, cbNeeded);

                if (pUserToken != NULL) {

                    if (GetTokenInformation(TokenHandle, TokenUser,  pUserToken,
                                            cbNeeded, &cbNeeded)) {

                        //
                        // Convert User Sid to name/domain
                        //

                        cbName = 0;
                        cbDomain = 0;

                        if (!LookupAccountSid(NULL,
                                              pUserToken->User.Sid,
                                              NULL, &cbName,
                                              NULL, &cbDomain,
                                              &SidNameUse)) {

                            if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {

                                *UserDomain = (PTSTR)LocalAlloc(LPTR, cbDomain*sizeof(TCHAR));
                                *UserName = (PTSTR)LocalAlloc(LPTR, cbName*sizeof(TCHAR));

                                if ((*UserDomain != NULL) && (*UserName != NULL)) {

                                    ReturnValue = LookupAccountSid(
                                                      NULL,
                                                      pUserToken->User.Sid,
                                                      *UserName, &cbName,
                                                      *UserDomain, &cbDomain,
                                                      &SidNameUse);
                                }
                            }

                        }
                    }

                    LocalFree(pUserToken);
                }
            }
        }

        CloseHandle(TokenHandle);
    }


    IgnoreError = RpcRevertToSelf();
    ASSERT(IgnoreError == ERROR_SUCCESS);


    //
    // Clean up on failure
    //

    if (ReturnValue) {
        Error = ERROR_SUCCESS;
    } else {

        Error = GetLastError();

        DeleteClientId(*UserName, *UserDomain);

        *UserName = NULL;
        *UserDomain = NULL;
    }


    return(Error);
}




VOID
DeleteClientId(
    PTSTR UserName,
    PTSTR UserDomain
    )
/*++

Routine Description:

    Frees the client id returned previously by GetClientId

Arguments:

    UserName - a pointer to the username returned by GetClientId.

    DomainName - a pointer to the domain name eturned by GetClientId

Return Value:

    None

--*/
{
    if (UserName != NULL) {
        LocalFree(UserName);
    }

    if (UserDomain != NULL) {
        LocalFree(UserDomain);
    }

}




BOOL
InsertClientId(
    HWND hDlg,
    int ControlId,
    PTSTR UserName,
    PTSTR UserDomain
    )
/*++

Routine Description:

    Takes the text from the specified dialog control, treats it as a printf
    formatting string and inserts the user name and domain as the first 2
    string identifiers (%s)

Arguments:

    UserName - a pointer to the username returned by GetClientId.

    DomainName - a pointer to the domain name eturned by GetClientId

Return Value:

    TRUE on success, FALSE on failure

--*/
{
    DWORD   StringLength;
    DWORD   StringBytes;
    PTSTR   FormatBuffer;
    PTSTR   Buffer;

    //
    // Allocate space for the formatting string out of the control
    //

    StringLength = (DWORD)SendMessage(GetDlgItem(hDlg, ControlId), WM_GETTEXTLENGTH, 0, 0);
    StringBytes = (StringLength + 1) * sizeof(TCHAR); // Allow for terminator

    FormatBuffer = (PTSTR)LocalAlloc(LPTR, StringBytes);
    if (FormatBuffer == NULL) {
        return(FALSE);
    }

    //
    // Read the format string into the buffer
    //

    GetDlgItemText(hDlg, ControlId, FormatBuffer, StringLength);

    //
    // Calculate the maximum size of the string we'll create
    // i.e. Formatting string + username + userdomain
    //

    StringLength += lstrlen(UserName);
    StringLength += lstrlen(UserDomain);

    //
    // Allocate space for formatted string
    //

    StringBytes = (StringLength + 1) * sizeof(TCHAR); // Allow for terminator

    Buffer = (PTSTR)LocalAlloc(LPTR, StringBytes);
    if (Buffer == NULL) {
        LocalFree(FormatBuffer);
        return(FALSE);
    }

    //
    // Insert the user id into the format string
    //

    wsprintf(Buffer, FormatBuffer, UserDomain, UserName);
    ASSERT((lstrlen(Buffer) * sizeof(TCHAR)) < StringBytes);

    //
    // Replace the control text with our formatted result
    //

    SetDlgItemText(hDlg, ControlId, Buffer);

    //
    // Tidy up
    //

    LocalFree(FormatBuffer);
    LocalFree(Buffer);


    return(TRUE);
}