summaryrefslogtreecommitdiffstats
path: root/private/net/svcdlls/srvsvc/server/scavengr.c
blob: 87bb309d60a52cc442d5dcff3a692c8d18cb5de5 (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
/*++

Copyright (c) 1991-1992 Microsoft Corporation

Module Name:

    Scavengr.c

Abstract:

    This module contains the code for the server service scavenger
    thread.  This thread handles announcements and configuration
    changes.  (Although originally written to run in a separate thread,
    this code now runs in the initial thread of the server service.

Author:

    David Treadwell (davidtr)    17-Apr-1991

Revision History:

--*/

#include "srvsvcp.h"
#include "ssdata.h"
#include "ssreg.h"

#include <netlibnt.h>
#include <tstr.h>

#define INCLUDE_SMB_TRANSACTION
#undef NT_PIPE_PREFIX
#include <smbtypes.h>
#include <smb.h>
#include <smbtrans.h>
#include <smbgtpt.h>

#include <hostannc.h>
#include <ntddbrow.h>
#include <lmerr.h>

#define TERMINATION_SIGNALED 0
#define ANNOUNCE_SIGNALED 1
#define STATUS_CHANGED 2
#define REGISTRY_CHANGED 3        // Must be the last one!

#define NUMBER_OF_EVENTS 4


//
// Bias request announcements by SERVER_REQUEST_ANNOUNCE_DELTA SECONDS
//

#define SERVER_REQUEST_ANNOUNCE_DELTA   30

//
// Forward declarations.
//

VOID
Announce (
    IN BOOL DoNtAnnouncement,
    IN DWORD NtInterval,
    IN BOOL DoLmAnnouncement,
    IN BOOL TerminationAnnouncement
    );

NET_API_STATUS
SendSecondClassMailslot (
    IN LPTSTR Transport OPTIONAL,
    IN PVOID Message,
    IN DWORD MessageLength,
    IN LPTSTR Domain,
    IN LPSTR MailslotNameText,
    IN UCHAR SignatureByte
    );

NET_API_STATUS
SsBrowserIoControl (
    IN DWORD IoControlCode,
    IN PVOID Buffer,
    IN DWORD BufferLength,
    IN PLMDR_REQUEST_PACKET Packet,
    IN DWORD PacketLength
    );


DWORD
ComputeAnnounceTime (
    IN DWORD LastAnnouncementTime,
    IN DWORD Interval
    )

/*++

Routine Description:

    Compute the time to wait (in milliseconds) until the next announcement should
    be made.

Arguments:

    LastAnnouncementTime - Time (in milliseconds since reboot) when the last
        announcement was made.

    Interval - Interval (in seconds) between announcements

Return Value:

    Timeout period (in milliseconds)

--*/

{
    DWORD AnnounceDelta;
    DWORD Timeout;
    DWORD CurrentTime;

    //
    // Get the current time.
    //

    CurrentTime = GetTickCount();

    //
    // If the clock has gone backward,
    //  send an announcement now.
    //

    if ( LastAnnouncementTime > CurrentTime ) {
        return 0;
    }

    //
    // Convert the announcement period from seconds to milliseconds.
    //

    Timeout = Interval * 1000;

    //
    // Add in the random announce delta which helps prevent lots of
    // servers from announcing at the same time.
    //

    AnnounceDelta = SsData.ServerInfo102.sv102_anndelta;

    Timeout += ((rand( ) * AnnounceDelta * 2) / RAND_MAX) -
                   AnnounceDelta;

    //
    // If our time has expired,
    //  send an announcement now.
    //

    if ( (CurrentTime - LastAnnouncementTime) >= Timeout ) {
        return 0;
    }

    //
    // Adjust our timeout period for time already elapsed.
    //

    return Timeout - (CurrentTime - LastAnnouncementTime);

}


DWORD
SsScavengerThread (
    IN LPVOID lpThreadParameter
    )

/*++

Routine Description:

    This routine implements the server service scavenger thread.

Arguments:

    lpThreadParameter - ignored.

Return Value:

    NET_API_STATUS - thread termination result.

--*/

{
    HANDLE events[ NUMBER_OF_EVENTS ];
    ULONG numEvents = NUMBER_OF_EVENTS-1;
    UNICODE_STRING unicodeEventName;
    OBJECT_ATTRIBUTES obja;
    DWORD waitStatus;
    DWORD timeout;

    DWORD LmTimeout;
    BOOL DoLmAnnouncement;
    DWORD LmLastAnnouncementTime;

    DWORD NtTimeout;
    BOOL DoNtAnnouncement;
    DWORD NtLastAnnouncementTime;
    DWORD NtInterval;

    NTSTATUS status;
    BOOL hidden = TRUE;
    HKEY hParameters = INVALID_HANDLE_VALUE;

    lpThreadParameter;

    //
    // Use the scavenger termination event to know when we're supposed
    // to wake up and kill ourselves.
    //

    events[TERMINATION_SIGNALED] = SsTerminationEvent;

    //
    // Initialize the NT announcement interval to the LM announcement interval
    //

    NtInterval = SsData.ServerInfo102.sv102_announce;
    DoLmAnnouncement = TRUE;
    DoNtAnnouncement = TRUE;

    //
    // Create the announce event.  When this gets signaled, we wake up
    // and do an announcement.  We use a synchronization event rather
    // than a notification event so that we don't have to worry about
    // resetting the event after we wake up.
    //

    //
    // Please note that we create this event with OBJ_OPENIF.  We do this
    // to allow the browser to signal the server to force an announcement.
    //
    // The bowser will create this event as a part of the bowser
    // initialization, and will set it to the signalled state when it needs
    // to have the server announce.
    //


    RtlInitUnicodeString( &unicodeEventName, SERVER_ANNOUNCE_EVENT_W );
    InitializeObjectAttributes( &obja, &unicodeEventName, OBJ_OPENIF, NULL, NULL );

    status = NtCreateEvent(
                 &SsAnnouncementEvent,
                 SYNCHRONIZE | EVENT_QUERY_STATE | EVENT_MODIFY_STATE,
                 &obja,
                 SynchronizationEvent,
                 FALSE
                 );

    if ( !NT_SUCCESS(status) ) {
        SS_PRINT(( "SsScavengerThread: NtCreateEvent failed: %X\n",
                    status ));
        return NetpNtStatusToApiStatus( status );
    }

    events[ANNOUNCE_SIGNALED] = SsAnnouncementEvent;

    //
    // Create an unnamed event to be set to the signalled state when the
    // service status changes (or a local application requests an
    // announcement)
    //

    InitializeObjectAttributes( &obja, NULL, OBJ_OPENIF, NULL, NULL );

    status = NtCreateEvent(
                 &SsStatusChangedEvent,
                 SYNCHRONIZE | EVENT_QUERY_STATE | EVENT_MODIFY_STATE,
                 &obja,
                 SynchronizationEvent,
                 FALSE
                 );

    if ( !NT_SUCCESS(status) ) {
        SS_PRINT(( "SsScavengerThread: NtCreateEvent failed: %X\n",
                    status ));

        NtClose( SsAnnouncementEvent );
        SsAnnouncementEvent = NULL;

        return NetpNtStatusToApiStatus( status );
    }

    events[STATUS_CHANGED] = SsStatusChangedEvent;

    //
    // Put a watch on the registry for any changes that happen in the
    //   null session share or pipe list.  Don't bail out if this fails,
    //   because we've done this as a convenience in adding new null
    //   session-reliant servers.  It doesn't really affect the normal
    //   operation of the server if this doesn't work.
    //
    events[ REGISTRY_CHANGED ] = INVALID_HANDLE_VALUE;
    status = NtCreateEvent(
                            &events[ REGISTRY_CHANGED ],
                            SYNCHRONIZE | EVENT_QUERY_STATE | EVENT_MODIFY_STATE,
                            NULL,
                            SynchronizationEvent,
                            FALSE
                          );

    if ( NT_SUCCESS(status) ) {
        status = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
                               FULL_PARAMETERS_REGISTRY_PATH,
                               0,
                               KEY_NOTIFY,
                               &hParameters
                             );

        if( status == ERROR_SUCCESS ) {
            (void)RegNotifyChangeKeyValue( hParameters,
                                           TRUE,
                                           REG_NOTIFY_CHANGE_LAST_SET,
                                           events[ REGISTRY_CHANGED ],
                                           TRUE
                                         );
            //
            // Add this event to the list of events we're waiting for
            //
            ++numEvents;
        }
    }

    //
    // Seed the random number generator.  We use it to generate random
    // announce deltas.
    //

    srand( (int)SsAnnouncementEvent );

    //
    // Do an announcement immediately for startup, then loop announcing
    // based on the announce interval.
    //

    waitStatus = WAIT_TIMEOUT;

    do {



        //
        // Act according to whether the termination event, the announce
        // event, or the timeout caused us to wake up.
        //
        // !!! Or the configuration event indicating a configuration
        //     change notification.

        if ( waitStatus == WAIT_OBJECT_0 + TERMINATION_SIGNALED ) {

            SS_PRINT(( "Scavenger: termination event signaled\n" ));

            //
            // The scavenger termination event was signaled, so we have
            // to gracefully kill this thread.  If this is not a hidden
            // server, announce the fact that we're going down.
            //

            if ( !hidden ) {
                Announce( TRUE, NtInterval, TRUE, TRUE );
            }

            //
            // Close the announcement event.
            //

            NtClose( SsAnnouncementEvent );

            SsAnnouncementEvent = NULL;

            //
            // Close the Registry watch event.
            //
            if( events[ REGISTRY_CHANGED ] != INVALID_HANDLE_VALUE )
                NtClose( events[ REGISTRY_CHANGED ] );

            //
            // Close the Registry handle
            //
            if( hParameters != INVALID_HANDLE_VALUE )
                RegCloseKey( hParameters );

            //
            // Return to caller.
            //

            return NO_ERROR;

        } else if( waitStatus == WAIT_OBJECT_0 + REGISTRY_CHANGED ) {
            //
            // Somebody changed some server parameters.  Tell the driver
            //
            SS_PRINT(( "SsScavengerThread: Server parameters changed\n" ));

            //
            // Tell the server FSD to look for a change in the registry
            //
            (void)SsServerFsControl( NULL, FSCTL_SRV_REGISTRY_CHANGE, NULL, NULL, 0 );

            //
            // Turn it back on so we get future changes, too
            //
            (void)RegNotifyChangeKeyValue( hParameters,
                                           TRUE,
                                           REG_NOTIFY_CHANGE_LAST_SET,
                                           events[ REGISTRY_CHANGED ],
                                           TRUE
                                         );

        } else {

            SS_ASSERT( waitStatus == WAIT_TIMEOUT ||
                    waitStatus == WAIT_OBJECT_0 + ANNOUNCE_SIGNALED ||
                    waitStatus == WAIT_OBJECT_0 + STATUS_CHANGED );

            //
            // If we've timed out,
            //  we've already set the flags indicating whether to announce
            //  on to lanman to NT browsers
            //

            if ( waitStatus != WAIT_TIMEOUT ) {
                DoLmAnnouncement = TRUE;
                DoNtAnnouncement = TRUE;
            }

            //
            // If we're not a hidden server, announce ourselves.
            //

            // Hold the database resource while we do the announcement so
            // that we get a consistent view of the database.
            //

            (VOID)RtlAcquireResourceShared( &SsServerInfoResource, TRUE );

            if ( !SsData.ServerInfo102.sv102_hidden ) {

                hidden = FALSE;

                Announce( DoNtAnnouncement, NtInterval, DoLmAnnouncement, FALSE );



            //
            // If we were not hidden last time through the loop but
            // we're hidden now, we've changed to hidden, so announce
            // that we're going down.  This causes clients in the domain
            // to take us out of their server enumerations.
            //

            } else if ( !hidden ) {

                hidden = TRUE;
                Announce( TRUE, NtInterval, TRUE, TRUE );

            }

            //
            // If the server is hidden, the wait timeout is infinite.  We'll
            // be woken up by the announce event if the server becomes
            // unhidden.
            //

            if ( SsData.ServerInfo102.sv102_hidden ) {

                timeout = 0xffffffff;

            } else {

                //
                // Remember when the last announcement was.
                //

                if ( DoNtAnnouncement ) {
                    NtLastAnnouncementTime = GetTickCount();
                }

                if ( DoLmAnnouncement ) {
                    LmLastAnnouncementTime = GetTickCount();
                }

                //
                // Compute the time delta to the next announcement
                //
                // For NtInterval,
                //  use a local copy of the interval since we compute the correct
                //  value.
                //
                // For the Lanman interval,
                //  use the global copy to allow the interval to be changed.
                //

                NtTimeout = ComputeAnnounceTime(
                                NtLastAnnouncementTime,
                                NtInterval );

                if (SsData.ServerInfo599.sv599_lmannounce) {
                    LmTimeout = ComputeAnnounceTime(
                                    LmLastAnnouncementTime,
                                    SsData.ServerInfo102.sv102_announce );
                } else {
                    // Don't awaken this thread to do nothing.
                    LmTimeout = 0xffffffff;
                }


                //
                // If our NT announcement frequency is less than 12 minutes,
                // increase our announcement frequency by 4 minutes.
                //

                if ( NtInterval < 12 * 60 ) {

                    NtInterval += 4 * 60;

                    if ( NtInterval > 12 * 60) {
                        NtInterval = 12 * 60;
                    }
                }

                //
                // Determine which timeout we're actually going to use.
                //

                if ( NtTimeout == LmTimeout ) {
                    timeout = NtTimeout;
                    DoLmAnnouncement = TRUE;
                    DoNtAnnouncement = TRUE;
                } else if ( NtTimeout < LmTimeout ) {
                    timeout = NtTimeout;
                    DoLmAnnouncement = FALSE;
                    DoNtAnnouncement = TRUE;
                } else {
                    timeout = LmTimeout;
                    DoLmAnnouncement = TRUE;
                    DoNtAnnouncement = FALSE;
                }

            }

            RtlReleaseResource( &SsServerInfoResource );
        }


        //
        // Wait for one of the events to be signaled or for the timeout
        // to elapse.
        //

        waitStatus = WaitForMultipleObjects(  numEvents , events, FALSE, timeout );

        if ( waitStatus == WAIT_OBJECT_0 + ANNOUNCE_SIGNALED ) {

            //
            // We were awakened because an announce was signalled.
            // Unless we are a master browser on at least one transport,
            // delay for a random delta to stagger announcements a bit
            // to prevent lots of servers from announcing
            // simultaneously.
            //

            BOOL isMasterBrowser = FALSE;
            PNAME_LIST_ENTRY service = SsServerNameList;
            PTRANSPORT_LIST_ENTRY transport;

            for( service = SsServerNameList;
                 isMasterBrowser == FALSE && service != NULL;
                 service = service->Next ) {

                if( service->ServiceBits & SV_TYPE_MASTER_BROWSER ) {
                    isMasterBrowser = TRUE;
                    break;
                }

                for( transport=service->Transports; transport != NULL; transport=transport->Next ) {
                    if( transport->ServiceBits & SV_TYPE_MASTER_BROWSER ) {
                        isMasterBrowser = TRUE;
                        break;
                    }
                }
            }

            if ( !isMasterBrowser ) {
                Sleep( ((rand( ) * (SERVER_REQUEST_ANNOUNCE_DELTA * 1000)) / RAND_MAX) );
            }

        }

    } while ( TRUE );

    return NO_ERROR;

} // SsScavengerThread


VOID
SsAnnounce (
    IN POEM_STRING OemAnnounceName,
    IN LPWSTR EmulatedDomainName,
    IN BOOL DoNtAnnouncement,
    IN DWORD NtInterval,
    IN BOOL DoLmAnnouncement,
    IN BOOL TerminationAnnouncement,
    IN LPTSTR Transport,
    IN DWORD serviceType
    )

/*++

Routine Description:

    This routine sends a broadcast datagram as a second-class mailslot
    that announces the presence of this server on the network.

Arguments:

    OemAnnounceName - The name we're announcing to the network

    EmulatedDomainName - The name of the domain this announcement is happening for.

    DoNtAnnouncement - Do an Nt-style announcement.

    NtInterval - NT announcement interval (in seconds)

    DoLmAnnouncement - Do an Lm-style announcement.

    TerminationAnnouncement - if TRUE, send the announcement that
        indicates that this server is going away.  Otherwise, send
        the normal message that tells clients that we're here.

    Transport - Ssupplies the transport to issue the announcement
        on.

    serviceType - Service bits being announced

Return Value:

    None.

--*/

{
    DWORD messageSize;
    PHOST_ANNOUNCE_PACKET packet;
    PBROWSE_ANNOUNCE_PACKET browsePacket;

    LPSTR serverName;
    DWORD oemServerNameLength;      // includes the null terminator

    LPSTR serverComment;
    DWORD serverCommentLength;      // includes the null terminator
    OEM_STRING oemCommentString;

    UNICODE_STRING unicodeCommentString;

    NET_API_STATUS status;

    //
    // Fill in the necessary information.
    //

    if( TerminationAnnouncement ) {
        serviceType &= ~SV_TYPE_SERVER;         // since the server is going away!
    }

    SS_PRINT(( "SsScavengerThread: Announcing for transport %s, Bits: %lx\n",
               Transport, serviceType ));

    //
    //  Get the length of the oem equivalent of the server name
    //

    oemServerNameLength = OemAnnounceName->Length + 1;

    //
    // Convert server comment to a unicode string
    //

    if ( *SsData.ServerCommentBuffer == '\0' ) {
        serverCommentLength = 1;
    } else {
        unicodeCommentString.Length =
            (USHORT)(STRLEN( SsData.ServerCommentBuffer ) * sizeof(WCHAR));
        unicodeCommentString.MaximumLength =
                    (USHORT)(unicodeCommentString.Length + sizeof(WCHAR));
        unicodeCommentString.Buffer = SsData.ServerCommentBuffer;
        serverCommentLength =
                    RtlUnicodeStringToOemSize( &unicodeCommentString );
    }

    oemCommentString.MaximumLength = (USHORT)serverCommentLength;

    messageSize = max(sizeof(HOST_ANNOUNCE_PACKET) + oemServerNameLength +
                            serverCommentLength,
                      sizeof(BROWSE_ANNOUNCE_PACKET) + serverCommentLength);

    //
    // Get memory to hold the message.  If we can't allocate enough
    // memory, don't send an announcement.
    //

    packet = MIDL_user_allocate( messageSize );
    if ( packet == NULL ) {
        return;
    }

    //
    //  If we are announcing as a Lan Manager server, broadcast the
    //  announcement.
    //

    if (SsData.ServerInfo599.sv599_lmannounce && DoLmAnnouncement ) {

        packet->AnnounceType = HostAnnouncement ;

        SmbPutUlong( &packet->HostAnnouncement.Type, serviceType );

        packet->HostAnnouncement.CompatibilityPad = 0;

        packet->HostAnnouncement.VersionMajor =
            (BYTE)SsData.ServerInfo102.sv102_version_major;
        packet->HostAnnouncement.VersionMinor =
            (BYTE)SsData.ServerInfo102.sv102_version_minor;

        SmbPutUshort(
            &packet->HostAnnouncement.Periodicity,
            (WORD)SsData.ServerInfo102.sv102_announce
            );

        //
        // Convert the server name from unicode to oem
        //

        serverName = (LPSTR)( &packet->HostAnnouncement.NameComment );

        RtlCopyMemory( serverName, OemAnnounceName->Buffer, OemAnnounceName->Length );
        serverName[OemAnnounceName->Length] = '\0';

        serverComment = serverName + oemServerNameLength;

        if ( serverCommentLength == 1 ) {
            *serverComment = '\0';
        } else {

            oemCommentString.Buffer = serverComment;
            (VOID) RtlUnicodeStringToOemString(
                        &oemCommentString,
                        &unicodeCommentString,
                        FALSE
                        );
        }

        SendSecondClassMailslot(
            Transport,
            packet,
            FIELD_OFFSET(HOST_ANNOUNCE_PACKET, HostAnnouncement.NameComment) +
                oemServerNameLength + serverCommentLength,
            EmulatedDomainName,
            "\\MAILSLOT\\LANMAN",
            0x00
            );
    }

    //
    //  Now announce the server as a Winball server.
    //

    if ( DoNtAnnouncement ) {
        browsePacket = (PBROWSE_ANNOUNCE_PACKET)packet;

        browsePacket->BrowseType = ( serviceType & SV_TYPE_MASTER_BROWSER ?
                                        LocalMasterAnnouncement :
                                        HostAnnouncement );

        browsePacket->BrowseAnnouncement.UpdateCount = 0;

        SmbPutUlong( &browsePacket->BrowseAnnouncement.CommentPointer, (ULONG)((0xaa55 << 16) + (BROWSER_VERSION_MAJOR << 8) + BROWSER_VERSION_MINOR));

        SmbPutUlong( &browsePacket->BrowseAnnouncement.Periodicity, NtInterval * 1000 );

        SmbPutUlong( &browsePacket->BrowseAnnouncement.Type, serviceType );

        browsePacket->BrowseAnnouncement.VersionMajor =
                (BYTE)SsData.ServerInfo102.sv102_version_major;
        browsePacket->BrowseAnnouncement.VersionMinor =
                (BYTE)SsData.ServerInfo102.sv102_version_minor;

        RtlCopyMemory( &browsePacket->BrowseAnnouncement.ServerName,
                       OemAnnounceName->Buffer,
                       OemAnnounceName->Length );
        browsePacket->BrowseAnnouncement.ServerName[OemAnnounceName->Length] = '\0';

        serverComment = (LPSTR)&browsePacket->BrowseAnnouncement.Comment;

        if ( serverCommentLength == 1 ) {
            *serverComment = '\0';
        } else {

            oemCommentString.Buffer = serverComment;
            (VOID) RtlUnicodeStringToOemString(
                                &oemCommentString,
                                &unicodeCommentString,
                                FALSE
                                );
        }

#ifdef KLUDGE_NOT_NEEDED // BUGBUG: SendSecondClassMailslot always sends "from" primary computername
        status = SendSecondClassMailslot(
            Transport,
            packet,
            FIELD_OFFSET(BROWSE_ANNOUNCE_PACKET, BrowseAnnouncement.Comment) +
                    serverCommentLength,
            EmulatedDomainName,
            "\\MAILSLOT\\BROWSE",
            (UCHAR)(serviceType & SV_TYPE_MASTER_BROWSER ?
                    BROWSER_ELECTION_SIGNATURE :
                    MASTER_BROWSER_SIGNATURE)
            );
#else
        status = ERROR_NOT_SUPPORTED;
#endif // KLUDGE_NOT_NEEDED

        if ( status != NERR_Success ) {
            UCHAR packetBuffer[sizeof(LMDR_REQUEST_PACKET)+(MAX_PATH)*sizeof(WCHAR)];
            PLMDR_REQUEST_PACKET requestPacket = (PLMDR_REQUEST_PACKET)packetBuffer;
            UNICODE_STRING TransportString;

            RtlInitUnicodeString(&TransportString, Transport);

            requestPacket->Version = LMDR_REQUEST_PACKET_VERSION;

            requestPacket->TransportName = TransportString;
#ifdef _CAIRO_
            RtlInitUnicodeString( &requestPacket->EmulatedDomainName, EmulatedDomainName );
#endif // _CAIRO_

            requestPacket->Type = Datagram;

            requestPacket->Parameters.SendDatagram.DestinationNameType = (serviceType & SV_TYPE_MASTER_BROWSER ? BrowserElection : MasterBrowser);

            requestPacket->Parameters.SendDatagram.MailslotNameLength = 0;

            //
            //  The domain announcement name is special, so we don't have to specify
            //  a destination name for it.
            //

            requestPacket->Parameters.SendDatagram.NameLength = STRLEN(EmulatedDomainName)*sizeof(TCHAR);

            STRCPY(requestPacket->Parameters.SendDatagram.Name, EmulatedDomainName);

            //
            //  This is a simple IoControl - It just sends the datagram.
            //

            status = SsBrowserIoControl(IOCTL_LMDR_WRITE_MAILSLOT,
                                        packet,
                                        FIELD_OFFSET(BROWSE_ANNOUNCE_PACKET, BrowseAnnouncement.Comment) +
                                            serverCommentLength,
                                        requestPacket,
                                        FIELD_OFFSET(LMDR_REQUEST_PACKET, Parameters.SendDatagram.Name)+
                                            requestPacket->Parameters.SendDatagram.NameLength);
        }
    }

    MIDL_user_free( packet );

} // SsAnnounce


ULONG
ComputeTransportAddressClippedLength(
    IN PCHAR TransportAddress,
    IN ULONG TransportAddressLength
    )

/*++

Routine Description:

    This routine returns the length of the transport address with the trailing
    blanks removed.

Arguments:

    TransportAddress - Transport address with potentially trailing blanks

    TransportAddressLength - Length of the Transport Address including trailing
        blanks

Return Value:

    Length of the Transport Address excluding trailing blanks.

--*/

{
    PCHAR p;

    //
    // Cut off any trailing spaces
    //
    p = &TransportAddress[ TransportAddressLength ];
    for( ; p > TransportAddress && *(p-1) == ' '; p-- )
        ;

    return p - TransportAddress;
}



VOID
Announce (
    IN BOOL DoNtAnnouncement,
    IN DWORD NtInterval,
    IN BOOL DoLmAnnouncement,
    IN BOOL TerminationAnnouncement
    )

/*++

Routine Description:

    This routine sends a broadcast datagram as a second-class mailslot
    that announces the presence of this server using all
    of the configured server names and all networks.

Arguments:

    DoNtAnnouncement - Do an Nt-style announcement.

    NtInterval - NT announcement interval (in seconds)

    DoLmAnnouncement - Do an Lm-style announcement.

    TerminationAnnouncement - if TRUE, send the announcement that
        indicates that this server is going away.  Otherwise, send
        the normal message that tells clients that we're here.


Return Value:

    None.

--*/

{
    PNAME_LIST_ENTRY Service;
    PTRANSPORT_LIST_ENTRY Transport;
    NTSTATUS status;
    OEM_STRING OemAnnounceName;

    (VOID)RtlAcquireResourceShared( &SsServerInfoResource, TRUE );

    //
    // Loop through each emulated server name announcing on each.
    //

    for( Service = SsServerNameList; Service != NULL; Service = Service->Next ) {

        //
        // Save the AnnounceName without trailing blanks.
        //

        OemAnnounceName.Length = (USHORT) ComputeTransportAddressClippedLength(
                                    Service->TransportAddress,
                                    Service->TransportAddressLength );

        OemAnnounceName.MaximumLength = OemAnnounceName.Length;
        OemAnnounceName.Buffer = Service->TransportAddress;

        if( OemAnnounceName.Length == 0 ) {
            //
            // A blank name???
            //
            continue;
        }


        //
        // Loop through each transport announcing on each.
        //

        for( Transport = Service->Transports; Transport != NULL; Transport = Transport->Next ) {


            //
            // Do the actual announcement
            //

            SsAnnounce( &OemAnnounceName,
                         Service->DomainName,
                         DoNtAnnouncement,
                         NtInterval,
                         DoLmAnnouncement,
                         TerminationAnnouncement,
                         Transport->TransportName,
                         Service->ServiceBits | Transport->ServiceBits );

        }
    }

    RtlReleaseResource( &SsServerInfoResource );
}



NET_API_STATUS
SendSecondClassMailslot (
    IN LPTSTR Transport OPTIONAL,
    IN PVOID Message,
    IN DWORD MessageLength,
    IN LPTSTR Domain,
    IN LPSTR MailslotNameText,
    IN UCHAR SignatureByte
    )
{
    NET_API_STATUS status;
    DWORD dataSize;
    DWORD smbSize;
    PSMB_HEADER header;
    PSMB_TRANSACT_MAILSLOT parameters;
    LPSTR mailslotName;
    DWORD mailslotNameLength;
    PVOID message;
    DWORD domainLength;
    CHAR domainName[NETBIOS_NAME_LEN];
    PCHAR domainNamePointer;
    PSERVER_REQUEST_PACKET srp;

    UNICODE_STRING domainString;
    OEM_STRING oemDomainString;

    srp = SsAllocateSrp();

    if ( srp == NULL ) {
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    RtlInitUnicodeString(&domainString, Domain);

    oemDomainString.Buffer = domainName;
    oemDomainString.MaximumLength = sizeof(domainName);

    status = RtlUpcaseUnicodeStringToOemString(
                                    &oemDomainString,
                                    &domainString,
                                    FALSE
                                    );

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

    domainLength = oemDomainString.Length;

    domainNamePointer = &domainName[domainLength];

    for ( ; domainLength < NETBIOS_NAME_LEN - 1 ; domainLength++ ) {
        *domainNamePointer++ = ' ';
    }

    //
    // Append the signature byte to the end of the name.
    //

    *domainNamePointer = SignatureByte;

    domainLength += 1;

    srp->Name1.Buffer = (PWSTR)domainName;
    srp->Name1.Length = (USHORT)domainLength;
    srp->Name1.MaximumLength = (USHORT)domainLength;

    if ( ARGUMENT_PRESENT ( Transport ) ) {
        RtlInitUnicodeString( &srp->Name2, Transport );

    } else {

        srp->Name2.Buffer = NULL;
        srp->Name2.Length = 0;
        srp->Name2.MaximumLength = 0;
    }

    //
    // Determine the sizes of various fields that will go in the SMB
    // and the total size of the SMB.
    //

    mailslotNameLength = strlen( MailslotNameText );

    dataSize = mailslotNameLength + 1 + MessageLength;
    smbSize = sizeof(SMB_HEADER) + sizeof(SMB_TRANSACT_MAILSLOT) - 1 + dataSize;

    //
    // Allocate enough memory to hold the SMB.  If we can't allocate the
    // memory, don't do an announcement.
    //

    header = MIDL_user_allocate( smbSize );
    if ( header == NULL ) {

        SsFreeSrp( srp );

        return ERROR_NOT_ENOUGH_MEMORY;
    }

    //
    // Fill in the header.  Most of the fields don't matter and are
    // zeroed.
    //

    RtlZeroMemory( header, smbSize );

    header->Protocol[0] = 0xFF;
    header->Protocol[1] = 'S';
    header->Protocol[2] = 'M';
    header->Protocol[3] = 'B';
    header->Command = SMB_COM_TRANSACTION;

    //
    // Get the pointer to the params and fill them in.
    //

    parameters = (PSMB_TRANSACT_MAILSLOT)( header + 1 );
    mailslotName = (LPSTR)( parameters + 1 ) - 1;
    message = mailslotName + mailslotNameLength + 1;

    parameters->WordCount = 0x11;
    SmbPutUshort( &parameters->TotalDataCount, (WORD)MessageLength );
    SmbPutUlong( &parameters->Timeout, 0x3E8 );                // !!! fix
    SmbPutUshort( &parameters->DataCount, (WORD)MessageLength );
    SmbPutUshort(
        &parameters->DataOffset,
        (WORD)( (DWORD)message - (DWORD)header )
        );
    parameters->SetupWordCount = 3;
    SmbPutUshort( &parameters->Opcode, MS_WRITE_OPCODE );
    SmbPutUshort( &parameters->Class, 2 );
    SmbPutUshort( &parameters->ByteCount, (WORD)dataSize );

    RtlCopyMemory( mailslotName, MailslotNameText, mailslotNameLength + 1 );

    RtlCopyMemory( message, Message, MessageLength );

    status = SsServerFsControl(
                 NULL,
                 FSCTL_SRV_SEND_DATAGRAM,
                 srp,
                 header,
                 smbSize
                 );

    if ( status != NERR_Success ) {
        SS_PRINT(( "SendSecondClassMailslot: NtFsControlFile failed: %X\n",
                    status ));
    }

    MIDL_user_free( header );

    SsFreeSrp( srp );

    return status;

} // SendSecondClassMailslot

NTSTATUS
OpenBrowser(
    OUT PHANDLE BrowserHandle
    )
/*++

Routine Description:

    This function opens a handle to the bowser device driver.

Arguments:

    OUT PHANDLE BrowserHandle - Returns the handle to the browser.

Return Value:

    NET_API_STATUS - NERR_Success or reason for failure.

--*/
{
    NTSTATUS ntstatus;

    UNICODE_STRING deviceName;

    IO_STATUS_BLOCK ioStatusBlock;
    OBJECT_ATTRIBUTES objectAttributes;


    //
    // Open the redirector device.
    //
    RtlInitUnicodeString(&deviceName, DD_BROWSER_DEVICE_NAME_U);

    InitializeObjectAttributes(
        &objectAttributes,
        &deviceName,
        OBJ_CASE_INSENSITIVE,
        NULL,
        NULL
        );

    ntstatus = NtOpenFile(
                   BrowserHandle,
                   SYNCHRONIZE | GENERIC_READ | GENERIC_WRITE,
                   &objectAttributes,
                   &ioStatusBlock,
                   FILE_SHARE_READ | FILE_SHARE_WRITE,
                   FILE_SYNCHRONOUS_IO_NONALERT
                   );

    if (NT_SUCCESS(ntstatus)) {
        ntstatus = ioStatusBlock.Status;
    }

    return ntstatus;

}

NET_API_STATUS
SsBrowserIoControl (
    IN DWORD IoControlCode,
    IN PVOID Buffer,
    IN DWORD BufferLength,
    IN PLMDR_REQUEST_PACKET Packet,
    IN DWORD PacketLength
    )
{
    HANDLE browserHandle;
    NTSTATUS status;
    PLMDR_REQUEST_PACKET realPacket;
    DWORD RealPacketSize;
    DWORD bytesReturned;
    LPBYTE Where;

    //
    //  Open the browser device driver.
    //

    if ( !NT_SUCCESS(status = OpenBrowser(&browserHandle)) ) {
        return RtlNtStatusToDosError(status);
    }

    //
    //  Now copy the request packet to a new buffer to allow us to pack the
    //  transport name to the end of the buffer we pass to the driver.
    //

    RealPacketSize = PacketLength+Packet->TransportName.MaximumLength;
#ifdef _CAIRO_
    RealPacketSize += Packet->EmulatedDomainName.MaximumLength;
#endif // _CAIRO_
    realPacket = MIDL_user_allocate( RealPacketSize );
    if (realPacket == NULL) {
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    RtlCopyMemory(realPacket, Packet, PacketLength);
    Where = ((LPBYTE)realPacket)+PacketLength;

    if (Packet->TransportName.Length != 0) {

        realPacket->TransportName.Buffer = (LPWSTR) Where;

        realPacket->TransportName.MaximumLength = Packet->TransportName.MaximumLength;

        RtlCopyUnicodeString(&realPacket->TransportName, &Packet->TransportName);

        Where += Packet->TransportName.MaximumLength;
    }

#ifdef _CAIRO_
    if (Packet->EmulatedDomainName.Length != 0) {

        realPacket->EmulatedDomainName.Buffer = (LPWSTR) Where;

        realPacket->EmulatedDomainName.MaximumLength = Packet->EmulatedDomainName.MaximumLength;

        RtlCopyUnicodeString(&realPacket->EmulatedDomainName, &Packet->EmulatedDomainName);

        Where += Packet->EmulatedDomainName.MaximumLength;
    }
#endif // _CAIRO_

    //
    // Send the request to the Datagram Receiver DD.
    //

    if (!DeviceIoControl(
                   browserHandle,
                   IoControlCode,
                   realPacket,
                   RealPacketSize,
                   Buffer,
                   BufferLength,
                   &bytesReturned,
                   NULL
                   )) {
        status = GetLastError();
    }

    MIDL_user_free(realPacket);

    CloseHandle(browserHandle);

    return status;

}