summaryrefslogblamecommitdiffstats
path: root/private/windows/gina/winlogon/logoff.c
blob: 995a49106546f2a66b7a55fda415fde8fa50b77f (plain) (tree)
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



































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                          
/****************************** Module Header ******************************\
* Module Name: logoff.c
*
* Copyright (c) 1991, Microsoft Corporation
*
* Implements functions to allow a user to logoff the system.
*
* History:
* 12-05-91 Davidc       Created.
\***************************************************************************/

#include "precomp.h"
#pragma hdrstop

#include <ras.h>
#include <raserror.h>

//
// Private prototypes
//

HANDLE
ExecLogoffThread(
    PGLOBALS pGlobals,
    DWORD Flags
    );

DWORD
LogoffThreadProc(
    LPVOID Parameter
    );

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

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

BOOL
DeleteNetworkConnections(
    PGLOBALS    pGlobals
    );

BOOLEAN
ShutdownThread(
    VOID
    );

BOOL
DeleteRasConnections(
    PGLOBALS    pGlobals
    );

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


BOOL    ExitWindowsInProgress = FALSE ;
HMODULE hRasApi;

//
// Bugbug:  move to winlogon.h
//
#define IsShutdown(x)   ((x == WLX_SAS_ACTION_SHUTDOWN) || \
                         (x == WLX_SAS_ACTION_SHUTDOWN_REBOOT) || \
                         (x == WLX_SAS_ACTION_SHUTDOWN_POWER_OFF) )


/***************************************************************************\
* FUNCTION: InitiateLogOff
*
* PURPOSE:  Starts the procedure of logging off the user.
*
* RETURNS:  DLG_SUCCESS - logoff was initiated successfully.
*           DLG_FAILURE - failed to initiate logoff.
*
* HISTORY:
*
*   12-09-91 Davidc       Created.
*
\***************************************************************************/

int
InitiateLogoff(
    PGLOBALS pGlobals,
    LONG Flags
    )
{
    BOOL IgnoreResult;
    HANDLE ThreadHandle;
    HANDLE Handle;
    PUSER_PROCESS_DATA UserProcessData;
    DWORD   Result;

    //
    // If this is a shutdown operation, call ExitWindowsEx from
    // another thread.
    //

    if (Flags & (EWX_SHUTDOWN | EWX_REBOOT | EWX_POWEROFF)) {

        //
        // Exec a user thread to call ExitWindows
        //

        ThreadHandle = ExecLogoffThread(pGlobals, Flags);

        if (ThreadHandle == NULL) {

            DebugLog((DEB_ERROR, "Unable to create logoff thread"));
            return(DLG_FAILURE);

        } else {

            //
            // We don't need the thread handle
            //

            IgnoreResult = CloseHandle(ThreadHandle);
            ASSERT(IgnoreResult);
        }
        Result = DLG_SUCCESS;

    } else {

        //
        // Switch the thread to user context.  We don't want
        // to start another thread to perform logoffs in
        // case the system is out of memory and unable to
        // create any more threads.
        //

        UserProcessData = &pGlobals->UserProcessData;
        Handle = ImpersonateUser(UserProcessData, GetCurrentThread());

        if (Handle == NULL) {

            DebugLog((DEB_ERROR, "Failed to set user context on thread!"));

        } else {

            //
            // Let the thread run
            //

            if ((pGlobals->UserLoggedOn) &&
                (pGlobals->LastGinaRet != WLX_SAS_ACTION_FORCE_LOGOFF) )
            {
                SetActiveDesktop(&pGlobals->WindowStation, Desktop_Application);
            }
            Result = LogoffThreadProc((LPVOID)Flags);

        }

        RevertToSelf();

    }

    //
    // ExitWindowsEx will cause one or more desktop switches to occur,
    // so we must invalidate our current desktop.
    //

    if ( (Flags & EWX_WINLOGON_API_SHUTDOWN) == 0 )
    {
        pGlobals->WindowStation.PreviousDesktop = pGlobals->WindowStation.ActiveDesktop;
        pGlobals->WindowStation.ActiveDesktop = -1;
    }

    //
    // The reboot thread is off and running. We're finished.
    //

    return (Result);
}


/***************************************************************************\
* FUNCTION: ExecLogoffThread
*
* PURPOSE:  Creates a user thread that calls ExitWindowsEx with the
*           passed flags.
*
* RETURNS:  TRUE on success, FALSE on failure
*
* HISTORY:
*
*   05-05-92 Davidc       Created.
*
\***************************************************************************/

HANDLE
ExecLogoffThread(
    PGLOBALS pGlobals,
    DWORD Flags
    )
{
    HANDLE ThreadHandle;
    DWORD ThreadId;

    ThreadHandle = ExecUserThread(
                        pGlobals,
                        LogoffThreadProc,
                        (LPVOID)Flags,
                        0,          // Thread creation flags
                        &ThreadId);

    if (ThreadHandle == NULL) {
        DebugLog((DEB_ERROR, "Failed to exec a user logoff thread"));
    }

    return (ThreadHandle);
}


/***************************************************************************\
* FUNCTION: LogoffThreadProc
*
* PURPOSE:  The logoff thread procedure. Calls ExitWindowsEx with passed flags.
*
* RETURNS:  Thread termination code is result of ExitWindowsEx call.
*
* HISTORY:
*
*   05-05-92 Davidc       Created.
*
\***************************************************************************/

DWORD
LogoffThreadProc(
    LPVOID Parameter
    )
{
    DWORD LogoffFlags = (DWORD)Parameter;
    BOOL Result = FALSE;


    //
    // If this logoff is a result of the InitiateSystemShutdown API,
    //  put up a dialog warning the user.
    //

    if ( LogoffFlags & EWX_WINLOGON_API_SHUTDOWN ) {
        Result = ShutdownThread();
    } else {
        Result = TRUE;
    }


    if ( Result ) {

        //
        // Enable shutdown privilege if we need it
        //

        if (LogoffFlags & (EWX_SHUTDOWN | EWX_REBOOT | EWX_POWEROFF)) {
            Result = EnablePrivilege(SE_SHUTDOWN_PRIVILEGE, TRUE);
            if (!Result) {
                DebugLog((DEB_ERROR, "Logoff thread failed to enable shutdown privilege!\n"));
            }
        }

        //
        // Call ExitWindowsEx with the passed flags
        //

        if (Result) {

            DebugLog((DEB_TRACE, "Calling ExitWindowsEx(%#x, 0)\n", LogoffFlags));

            //
            // Set global flag indicating an ExitWindows is in progress.
            //

            ExitWindowsInProgress = TRUE ;

            Result = ExitWindowsEx(LogoffFlags, 0);

            ExitWindowsInProgress = FALSE ;

            if (!Result) {
                DebugLog((DEB_ERROR, "Logoff thread call to ExitWindowsEx failed, error = %d\n", GetLastError()));
            }
        }
    }

    return(Result ? DLG_SUCCESS : DLG_FAILURE);
}


/***************************************************************************\
* FUNCTION: RebootMachine
*
* PURPOSE:  Calls NtShutdown(Reboot) in current user's context.
*
* RETURNS:  Should never return
*
* HISTORY:
*
*   05-09-92 Davidc       Created.
*
\***************************************************************************/

VOID
RebootMachine(
    PGLOBALS pGlobals
    )
{
    NTSTATUS Status;
    BOOL EnableResult, IgnoreResult;
    HANDLE UserHandle;

    //
    // Call windows to have it clear all data from video memory
    //

    // GdiEraseMemory();

    DebugLog(( DEB_TRACE, "Rebooting machine\n" ));

    //
    // Impersonate the user for the shutdown call
    //

    UserHandle = ImpersonateUser( &pGlobals->UserProcessData, NULL );
    ASSERT(UserHandle != NULL);

    //
    // Enable the shutdown privilege
    // This should always succeed - we are either system or a user who
    // successfully passed the privilege check in ExitWindowsEx.
    //

    EnableResult = EnablePrivilege(SE_SHUTDOWN_PRIVILEGE, TRUE);
    ASSERT(EnableResult);


    //
    // Do the final system shutdown pass (reboot)
    //

    Status = NtShutdownSystem(ShutdownReboot);

    DebugLog((DEB_ERROR, "NtShutdownSystem failed, status = 0x%lx", Status));
    ASSERT(NT_SUCCESS(Status)); // Should never get here

    //
    // We may get here if system is screwed up.
    // Try and clean up so they can at least log on again.
    //

    IgnoreResult = StopImpersonating(UserHandle);
    ASSERT(IgnoreResult);
}

/***************************************************************************\
* FUNCTION: PowerdownMachine
*
* PURPOSE:  Calls NtShutdownSystem(ShutdownPowerOff) in current user's context.
*
* RETURNS:  Should never return
*
* HISTORY:
*
*   08-09-93 TakaoK       Created.
*
\***************************************************************************/

VOID
PowerdownMachine(
    PGLOBALS pGlobals
    )
{
    NTSTATUS Status;
    BOOL EnableResult, IgnoreResult;
    HANDLE UserHandle;

    DebugLog(( DEB_TRACE, "Powering down machine\n" ));
    //
    // Impersonate the user for the shutdown call
    //

    UserHandle = ImpersonateUser( &pGlobals->UserProcessData, NULL );
    ASSERT(UserHandle != NULL);

    //
    // Enable the shutdown privilege
    // This should always succeed - we are either system or a user who
    // successfully passed the privilege check in ExitWindowsEx.
    //

    EnableResult = EnablePrivilege(SE_SHUTDOWN_PRIVILEGE, TRUE);
    ASSERT(EnableResult);

    //
    // Do the final system shutdown and powerdown pass
    //

    Status = NtShutdownSystem(ShutdownPowerOff);

    DebugLog((DEB_ERROR, "NtPowerdownSystem failed, status = 0x%lx", Status));
    ASSERT(NT_SUCCESS(Status)); // Should never get here

    //
    // We may get here if system is screwed up.
    // Try and clean up so they can at least log on again.
    //

    IgnoreResult = StopImpersonating(UserHandle);
    ASSERT(IgnoreResult);
}


/***************************************************************************\
* FUNCTION: ShutdownMachine
*
* PURPOSE:  Shutsdown and optionally reboots or powers off the machine.
*
*           The shutdown is always done in the logged on user's context.
*           If no user is logged on then the shutdown happens in system context.
*
* RETURNS:  FALSE if something went wrong, otherwise it never returns.
*
* HISTORY:
*
*   05-09-92 Davidc       Created.
*   10-04-93 Johannec     Add poweroff option.
*
\***************************************************************************/

BOOL
ShutdownMachine(
    PGLOBALS pGlobals,
    int Flags
    )
{
    int Result;
    HANDLE FoundDialogHandle;
    HANDLE LoadedDialogHandle = NULL;


    //
    // Preload the shutdown dialog so we don't have to fetch it after
    // the filesystem has been shutdown
    //

    FoundDialogHandle = FindResource(NULL,
                                (LPTSTR) MAKEINTRESOURCE(IDD_SHUTDOWN),
                                (LPTSTR) MAKEINTRESOURCE(RT_DIALOG));
    if (FoundDialogHandle == NULL) {
        DebugLog((DEB_ERROR, "Failed to find shutdown dialog resource"));
    } else {
        LoadedDialogHandle = LoadResource(NULL, FoundDialogHandle);
        if (LoadedDialogHandle == NULL) {
            DebugLog((DEB_ERROR, "Ffailed to load shutdown dialog resource"));
        }
    }

    //
    // Notify the GINA of shutdown here.
    //


#if DBG
    if (TEST_FLAG(GinaBreakFlags, BREAK_SHUTDOWN))
    {
        DebugLog((DEB_TRACE, "About to call WlxShutdown(%#x)\n",
                                    pGlobals->pGina->pGinaContext));

        DebugBreak();
    }
#endif

    WlxSetTimeout(pGlobals, 120);

    (void) pGlobals->pGina->pWlxShutdown(pGlobals->pGina->pGinaContext, Flags);

    //
    // If we haven't shut down already (via the Remote shutdown path), then
    // we  start it here, and wait for it to complete.  Otherwise, skip straight
    // down to the cool stuff.
    //
    if (pGlobals->WinlogonState != Winsta_Shutdown)
    {
        //
        // Call windows to do the windows part of shutdown
        // We make this a force operation so it is guaranteed to work
        // and can not be interrupted.
        //

        DebugLog(( DEB_TRACE, "Starting shutdown\n" ));

        Result = InitiateLogoff(pGlobals, EWX_SHUTDOWN | EWX_FORCE |
                           ((Flags == WLX_SAS_ACTION_SHUTDOWN_REBOOT) ? EWX_REBOOT : 0) |
                           ((Flags == WLX_SAS_ACTION_SHUTDOWN_POWER_OFF) ? EWX_POWEROFF : 0) );

        ASSERT(Result == DLG_SUCCESS);



        //
        // Put up a dialog box to wait for the shutdown notification
        // from windows and make the first NtShutdownSystem call.
        //

        WlxSetTimeout(pGlobals, TIMEOUT_NONE);

        Result = WlxDialogBoxParam( pGlobals,
                                    pGlobals->hInstance,
                                    (LPTSTR)IDD_SHUTDOWN_WAIT,
                                    NULL,
                                    ShutdownWaitDlgProc,
                                    (LONG)pGlobals);

    }
    else
    {
        //
        // If we're here, it means that we were shut down from the remote path,
        // so user has cleaned up, now we have to call NtShutdown to flush out
        // mm, io, etc.
        //

        DebugLog(( DEB_TRACE, "Shutting down kernel\n" ));

        EnablePrivilege( SE_SHUTDOWN_PRIVILEGE, TRUE );

        NtShutdownSystem( ShutdownNoReboot );

        EnablePrivilege( SE_SHUTDOWN_PRIVILEGE, FALSE );
    }


    //
    // if machine has powerdown capability and user want to turn it off, then
    // we down the system power.
    //
    if ( Flags == WLX_SAS_ACTION_SHUTDOWN_POWER_OFF)
    {
        PowerdownMachine(pGlobals);

    }


    //
    // If this is a shutdown request, then let the user know they can turn
    // off the power. Otherwise drop straight through and reboot.
    //

    if ( Flags != WLX_SAS_ACTION_SHUTDOWN_REBOOT) {

        DialogBoxIndirectParam(
                                    pGlobals->hInstance,
                                    (LPDLGTEMPLATE)LoadedDialogHandle,
                                    NULL,
                                    ShutdownDlgProc,
                                    (LONG)pGlobals);
    }


    //
    // If they got past that dialog it means they want to reboot
    //

    RebootMachine(pGlobals);

    ASSERT(!"RebootMachine failed");  // Should never get here

    return(FALSE);
}


/***************************************************************************\
* FUNCTION: ShutdownWaitDlgProc
*
* PURPOSE:  Processes messages while we wait for windows to notify us of
*           a successful shutdown. When notification is received, do any
*           final processing and make the first call to NtShutdownSystem.
*
* RETURNS:
*   DLG_FAILURE     - the dialog could not be displayed
*   DLG_SHUTDOWN()  - the system has been shutdown, reboot wasn't requested
*
* HISTORY:
*
*   10-14-92 Davidc       Created.
*   10-04-93 Johannec     Added Power off option.
*
\***************************************************************************/

BOOL WINAPI
ShutdownWaitDlgProc(
    HWND    hDlg,
    UINT    message,
    WPARAM  wParam,
    LPARAM  lParam
    )
{
    PGLOBALS pGlobals = (PGLOBALS)GetWindowLong(hDlg, GWL_USERDATA);
    BOOL Success;
    NTSTATUS Status;
    HANDLE UserHandle;

    switch (message) {

        case WM_INITDIALOG:
            SetWindowLong(hDlg, GWL_USERDATA, lParam);
            CentreWindow(hDlg);
            return(TRUE);


        case WLX_WM_SAS:
            if (wParam != WLX_SAS_TYPE_USER_LOGOFF)
            {
                return(TRUE);
            }

            UpdateWindow(hDlg);

            //
            // Look at the public shutdown/reboot flags to determine what windows
            // has actually done. We may receive other logoff notifications here
            // but they will be only logoffs - the only place that winlogon actually
            // calls ExitWindowsEx to do a shutdown/reboot is right here. So wait
            // for the real shutdown/reboot notification.
            //

            if (pGlobals->LogoffFlags & (EWX_SHUTDOWN | EWX_REBOOT | EWX_POWEROFF)) {

            //
            // It's the notification we were waiting for.
            // Do any final processing required and make the first
            // call to NtShutdownSystem.
            //


            //
            // Do any dos-specific clean-up
            //

            ShutdownDOS();


            //
            // Impersonate the user for the shutdown call
            //

            UserHandle = ImpersonateUser( &pGlobals->UserProcessData, NULL );
            ASSERT(UserHandle != NULL);

            //
            // Enable the shutdown privilege
            // This should always succeed - we are either system or a user who
            // successfully passed the privilege check in ExitWindowsEx.
            //

            Success = EnablePrivilege(SE_SHUTDOWN_PRIVILEGE, TRUE);
            ASSERT(Success);

            //
            // Do the first pass at system shutdown (no reboot yet)
            //

            WaitForSystemProcesses(pGlobals);

            Status = NtShutdownSystem(ShutdownNoReboot);
            ASSERT(NT_SUCCESS(Status));

            //
            // Revert to ourself
            //

            Success = StopImpersonating(UserHandle);
            ASSERT(Success);

            //
            // We've finished system shutdown, we're done
            //

            EndDialog(hDlg, LogoffFlagsToWlxCode(pGlobals->LogoffFlags) );
        }

        return(TRUE);
    }

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


/***************************************************************************\
* FUNCTION: ShutdownDlgProc
*
* PURPOSE:  Processes messages for the shutdown dialog - the one that says
*           it's safe to turn off the machine.
*
* RETURNS:  DLG_SUCCESS if the user hits the restart button.
*
* HISTORY:
*
*   03-19-92 Davidc       Created.
*
\***************************************************************************/

BOOL WINAPI
ShutdownDlgProc(
    HWND    hDlg,
    UINT    message,
    WPARAM  wParam,
    LPARAM  lParam
    )
{
    PGLOBALS pGlobals = (PGLOBALS)GetWindowLong(hDlg, GWL_USERDATA);

    switch (message) {

    case WM_INITDIALOG:
        SetWindowLong(hDlg, GWL_USERDATA, lParam);
        SetupSystemMenu(hDlg);
        CentreWindow(hDlg);
        return(TRUE);

    case WM_COMMAND:
        EndDialog(hDlg, DLG_SUCCESS);
        return(TRUE);
    }

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


/***************************************************************************\
* FUNCTION: LogOff
*
* PURPOSE:  Handles the post-user-application part of user logoff. This
*           routine is called after all the user apps have been closed down
*           It saves the user's profile, deletes network connections
*           and reboots/shutsdown the machine if that was requested.
*
* RETURNS:  TRUE on success, FALSE on failure
*
* HISTORY:
*
*   12-09-91 Davidc       Created.
*
\***************************************************************************/

BOOL
Logoff(
    PGLOBALS pGlobals,
    int LoggedOnResult
    )
{
    NTSTATUS Status;
    LUID luidNone = { 0, 0 };

    DebugLog((DEB_TRACE, "In Logoff()\n"));

    //
    // We expect to be at the winlogon desktop in all cases
    //

    // ASSERT(OpenInputDesktop(0, FALSE, MAXIMUM_ALLOWED) == pGlobals->hdeskWinlogon);


    //
    // Delete the user's network connections
    // Make sure we do this before deleting the user's profile
    //

    DeleteNetworkConnections(pGlobals);



    //
    // Remove any Messages Aliases added by the user.
    //
    DeleteMsgAliases();

    //
    // Play the user's logoff sound
    //
    if (pGlobals->PlaySound || pGlobals->MigrateSoundEvents) {
        HANDLE uh;
        BOOL fBeep;

        // We AREN'T impersonating the user by default, so we MUST do so
        // otherwise we end up playing the default rather than the user
        // specified sound.

        if (OpenIniFileUserMapping(pGlobals))
        {
            uh = ImpersonateUser(&pGlobals->UserProcessData, NULL);

            //
            // Whenever a user logs out, have WINMM.DLL check if there
            // were any sound events added to the [SOUNDS] section of
            // CONTROL.INI by a non-regstry-aware app.  If there are,
            // migrate those schemes to their new home.  If there aren't,
            // this is very quick.
            //

            if (pGlobals->MigrateSoundEvents) {
                (*(pGlobals->MigrateSoundEvents))();
            }

            if (pGlobals->PlaySound) {
                if (!SystemParametersInfo(SPI_GETBEEP, 0, &fBeep, FALSE)) {
                    // Failed to get hold of beep setting.  Should we be
                    // noisy or quiet?  We have to choose one value...
                    fBeep = TRUE;
                }

                if (fBeep) {

                    //
                    // Play synchronous
                    //
                    (*(pGlobals->PlaySound))((LPCSTR)SND_ALIAS_SYSTEMEXIT, NULL, SND_ALIAS_ID | SND_SYNC | SND_NODEFAULT);
                }
            }

            StopImpersonating(uh);

            CloseIniFileUserMapping(pGlobals);
        }

    }

    //
    // Call user to close the registry key for the NLS cache.
    //

    SetWindowStationUser(pGlobals->WindowStation.hwinsta, &luidNone, NULL, 0);

    //
    // Close the IniFileMapping that happened at logon time (LogonAttempt()).
    //

    CloseIniFileUserMapping(pGlobals);

    //
    // Save the user profile, this unloads the user's key in the registry
    //

    SaveUserProfile(pGlobals);

    //
    // Delete any remaining RAS connections.  Make sure to do this after
    // the user profile gets copied up to the
    //

    DeleteRasConnections( pGlobals );

    //
    // If the user logged off themselves (rather than a system logoff)
    // and wanted to reboot then do it now.
    //

    if (IsShutdown(LoggedOnResult) && (!(pGlobals->LogoffFlags & EWX_WINLOGON_OLD_SYSTEM)))
    {
        ShutdownMachine(pGlobals, LoggedOnResult);

        ASSERT(!"ShutdownMachine failed"); // Should never return
    }


    //
    // Set up security info for new user (system) - this clears out
    // the stuff for the old user.
    //

    SecurityChangeUser(pGlobals, NULL, NULL, pGlobals->WinlogonSid, FALSE);



    return(TRUE);
}


/***************************************************************************\
* FUNCTION: DeleteNetworkConnections
*
* PURPOSE:  Calls WNetNukeConnections in the client context to delete
*           any connections they may have had.
*
* RETURNS:  TRUE on success, FALSE on failure
*
* HISTORY:
*
*   04-15-92 Davidc       Created.
*
\***************************************************************************/

BOOL
DeleteNetworkConnections(
    PGLOBALS    pGlobals
    )
{
    HANDLE ImpersonationHandle;
    DWORD WNetResult;
    BOOL Result = FALSE; // Default is failure
    TCHAR szMprDll[] = TEXT("mpr.dll");
    CHAR szWNetNukeConn[]     = "WNetClearConnections";
    CHAR szWNetOpenEnum[]     = "WNetOpenEnumW";
    CHAR szWNetEnumResource[] = "WNetEnumResourceW";
    CHAR szWNetCloseEnum[]    = "WNetCloseEnum";
    PWNETNUKECONN  lpfnWNetNukeConn        = NULL;
    PWNETOPENENUM  lpfnWNetOpenEnum        = NULL;
    PWNETENUMRESOURCE lpfnWNetEnumResource = NULL;
    PWNETCLOSEENUM lpfnWNetCloseEnum       = NULL;
    HWND  hNetDelDlg;
    HANDLE hEnum;
    BOOL bConnectionsExist = TRUE;
    NETRESOURCE NetRes;
    DWORD dwNumEntries = 1;
    DWORD dwEntrySize = sizeof (NETRESOURCE);

    //
    // Impersonate the user
    //

    ImpersonationHandle = ImpersonateUser(&pGlobals->UserProcessData, NULL);

    if (ImpersonationHandle == NULL) {
        DebugLog((DEB_ERROR, "DeleteNetworkConnections : Failed to impersonate user\n"));
        return(FALSE);
    }


    //
    // Load mpr if it wasn't already loaded.
    //

    if (!pGlobals->hMPR){
        if (!(pGlobals->hMPR = LoadLibrary(szMprDll))) {
           DebugLog((DEB_ERROR, "DeleteNetworkConnections : Failed to load mpr.dll\n"));
           goto DNCExit;
        }
    }

    //
    // Get the function pointers
    //

    lpfnWNetOpenEnum = (PWNETOPENENUM) GetProcAddress(pGlobals->hMPR,
                                                      (LPSTR)szWNetOpenEnum);
    lpfnWNetEnumResource = (PWNETENUMRESOURCE) GetProcAddress(pGlobals->hMPR,
                                                      (LPSTR)szWNetEnumResource);
    lpfnWNetCloseEnum = (PWNETCLOSEENUM) GetProcAddress(pGlobals->hMPR,
                                                      (LPSTR)szWNetCloseEnum);
    lpfnWNetNukeConn = (PWNETNUKECONN) GetProcAddress(pGlobals->hMPR,
                                                      (LPSTR)szWNetNukeConn);

    //
    // Check for NULL return values
    //

    if ( !lpfnWNetOpenEnum || !lpfnWNetEnumResource ||
         !lpfnWNetCloseEnum || !lpfnWNetNukeConn ) {
        DebugLog((DEB_ERROR, "DeleteNetworkConnections : Received a NULL pointer from GetProcAddress\n"));
        goto DNCExit;
    }

    //
    // Check for at least one network connection
    //

    if ( (*lpfnWNetOpenEnum)(RESOURCE_CONNECTED, RESOURCETYPE_ANY,
                             0, NULL, &hEnum) == NO_ERROR) {

        if ((*lpfnWNetEnumResource)(hEnum, &dwNumEntries, &NetRes,
                                    &dwEntrySize) == ERROR_NO_MORE_ITEMS) {
            bConnectionsExist = FALSE;
        }

        (*lpfnWNetCloseEnum)(hEnum);
    }

    //
    // If we don't have any connections, then we can exit.
    //

    if (!bConnectionsExist) {
        goto DNCExit;
    }


    //
    // Display the status dialog box to the user
    //

    hNetDelDlg = CreateDialog (pGlobals->hInstance,
                               MAKEINTRESOURCE(IDD_WAIT_NET_DRIVES_DISCONNECT),
                               NULL,
                               DeleteNetConnectionsDlgProc);

    //
    // Delete the network connections.
    //

    WNetResult = 0;

    WNetResult = (*lpfnWNetNukeConn)(NULL);

    if (WNetResult != 0 && WNetResult != ERROR_CAN_NOT_COMPLETE) {
        DebugLog((DEB_ERROR, "DeleteNetworkConnections : WNetNukeConnections failed, error = %d\n", WNetResult));
    }

    Result = (WNetResult == ERROR_SUCCESS);

    //
    // Close the dialog box
    //

    if (IsWindow (hNetDelDlg)) {
       DestroyWindow (hNetDelDlg);
    }


DNCExit:

    //
    // Unload mpr.dll
    //

    if ( pGlobals->hMPR ) {
        FreeLibrary(pGlobals->hMPR);
        pGlobals->hMPR = NULL;
    }

    //
    // Revert to being 'ourself'
    //

    if (!StopImpersonating(ImpersonationHandle)) {
        DebugLog((DEB_ERROR, "DeleteNetworkConnections : Failed to revert to self\n"));
    }

    return(Result);
}

/***************************************************************************\
* FUNCTION: DeleteNetConnectionsDlgProc
*
* PURPOSE:  Processes messages for the deleting net connections dialog
*
* RETURNS:  Standard dialog box return values
*
* HISTORY:
*
*   04-26-92 EricFlo       Created.
*
\***************************************************************************/

BOOL WINAPI
DeleteNetConnectionsDlgProc(
    HWND    hDlg,
    UINT    message,
    WPARAM  wParam,
    LPARAM  lParam
    )
{

    switch (message) {

    case WM_INITDIALOG:
        CentreWindow(hDlg);
        return(TRUE);

    }

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

//+---------------------------------------------------------------------------
//
//  Function:   DeleteRasConnections
//
//  Synopsis:   Delete RAS connections during logoff.
//
//  Arguments:  (none)
//
//  History:    5-10-96   RichardW   Created
//
//  Notes:
//
//----------------------------------------------------------------------------
BOOL
DeleteRasConnections(
    PGLOBALS    pGlobals
    )
{
    HANDLE  ImpersonationHandle;
    SC_HANDLE hServiceMgr, hService;
    SERVICE_STATUS status;
    RASCONN rasconn;
    LPRASCONN lprasconn = &rasconn;
    DWORD i, dwErr, dwcb, dwc;
    BOOL bRet;
    PRASENUMCONNECTIONSW pRasEnumConnectionsW;
    PRASHANGUPW pRasHangUpW;
    BOOL FreeThatRasConn = FALSE;


    if ( GetProfileInt( WINLOGON, KEEP_RAS_AFTER_LOGOFF, 0 ) )
    {
        return( TRUE );
    }

    //
    // Determine whether the rasman service is running.
    //

    hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);

    if ( hServiceMgr == NULL )
    {
        DebugLog((DEB_ERROR, "Unable to object service controller, %d\n", GetLastError()));
        return( FALSE );
    }

    hService = OpenService(
                     hServiceMgr,
                     RASMAN_SERVICE_NAME,
                     SERVICE_QUERY_STATUS);

    if (hService == NULL)
    {
        CloseServiceHandle(hServiceMgr);
        DebugLog((DEB_TRACE, "rasman not started, nothing to tear down\n"));
        return( TRUE );
    }

    bRet = QueryServiceStatus( hService, &status );

    CloseServiceHandle(hService);

    CloseServiceHandle(hServiceMgr);

    if (! bRet )
    {
        //
        // Service in bad state, get out of here...
        //

        return( TRUE );
    }

    if (status.dwCurrentState != SERVICE_RUNNING)
    {
        //
        // Service is not running
        //

        return( TRUE );

    }

    //
    // Load the RASAPI DLL so we can make it do stuff
    //

    if ( !hRasApi )
    {
        hRasApi = LoadLibrary( RASAPI32 );
        if ( !hRasApi )
        {
            return( FALSE );
        }
    }

    pRasEnumConnectionsW = (PRASENUMCONNECTIONSW) GetProcAddress(
                                hRasApi,
                                "RasEnumConnectionsW" );

    pRasHangUpW = (PRASHANGUPW) GetProcAddress(
                                hRasApi,
                                "RasHangUpW" );

    if ( (!pRasEnumConnectionsW) ||
         (!pRasHangUpW) )
    {
        return( FALSE );
    }



    //
    // Impersonate the user
    //

    ImpersonationHandle = ImpersonateUser(&pGlobals->UserProcessData, NULL);

    if (ImpersonationHandle == NULL) {
        DebugLog((DEB_ERROR, "DeleteNetworkConnections : Failed to impersonate user\n"));
        return(FALSE);
    }

    //
    // Enumerate the current RAS connections.
    //


    lprasconn->dwSize = sizeof (RASCONN);

    dwcb = sizeof (RASCONN);

    dwc = 1;

    dwErr = pRasEnumConnectionsW(lprasconn, &dwcb, &dwc);

    if (dwErr == ERROR_BUFFER_TOO_SMALL)
    {
        lprasconn = LocalAlloc(LPTR, dwcb);

        FreeThatRasConn = TRUE;

        if ( !lprasconn )
        {
            return( FALSE );
        }

        dwErr = pRasEnumConnectionsW(lprasconn, &dwcb, &dwc);
        if (dwErr)
        {
            if ( FreeThatRasConn )
            {
                LocalFree( lprasconn );
            }

            return( FALSE );
        }
    }
    else if (dwErr)
    {
        return( FALSE );
    }

    //
    // cycle through the connections, and kill them
    //


    for (i = 0; i < dwc; i++)
    {
        DebugLog((DEB_TRACE, "Hanging up connection to %ws\n",
                lprasconn[i].szEntryName));

        (VOID) pRasHangUpW( lprasconn[i].hrasconn );
    }

    if ( FreeThatRasConn )
    {
        LocalFree( lprasconn );
    }

    //
    // Revert to being 'ourself'
    //

    if (!StopImpersonating(ImpersonationHandle)) {
        DebugLog((DEB_ERROR, "DeleteNetworkConnections : Failed to revert to self\n"));
    }

    return( TRUE );
}