summaryrefslogtreecommitdiffstats
path: root/private/net/svcdlls/nwsap/server/saplpc.c
blob: 94dc585bfb732991fb208fee8925d60e8ad6bb80 (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
/*++

Copyright (c) 1994  Microsoft Corporation
Copyright (c) 1993  Micro Computer Systems, Inc.

Module Name:

    net\svcdlls\nwsap\server\saplpc.c

Abstract:

    This routine handles the LPC interface that other programs use
    to send requests to me for information.

Author:

    Brian Walker (MCS) 06-15-1993

Revision History:

--*/

#include "precomp.h"
#pragma hdrstop

/**
    Structure used to keep track of each LPC client
    that attaches to our port.
**/

typedef struct {
    HANDLE Handle;              /* Port handle for the client   */
    PVOID  Context;             /* Context for the client       */
    LIST_ENTRY ListEntry;       /* Used to link entries         */
} SAP_LPC_CLIENT, *PSAP_LPC_CLIENT;

/** **/

PHANDLE SapLpcWorkerHandles;

/** Internal Function Prototypes **/

DWORD WINAPI
SapXsWorkerThread(
    LPVOID Threadparm);

VOID
SapXsHandleConnect(
    PPORT_MESSAGE Request);


/*++
*******************************************************************
        S a p X s I n i t i a l i z e

Routine Description:

        This routine initializes the LPC interface used by NWSAP
        clients to send requests to be handled.

Arguments:

        None

Return Value:

        0 = OK
        Else = Error code on return
               The error is logged to the event log before returning
*******************************************************************
--*/

DWORD
SapXsInitialize(
    VOID)
{
    NTSTATUS Status;
    HANDLE Handle;
    ULONG i;
    DWORD Threadid;
    UNICODE_STRING UnicodeName;
    OBJECT_ATTRIBUTES ObjectAttributes;

    /** Get a buffer to hold worker thread handles **/

    SapLpcWorkerHandles = SAP_MALLOC(SapLpcMaxWorkers * sizeof(HANDLE), "SapXsInit: Alloc worker handle buffer");
    if (SapLpcWorkerHandles == NULL) {
        SapError = 0;
        SapEventId = NWSAP_EVENT_LPCHANDLEMEMORY_ERROR;
        return ERROR_NOT_ENOUGH_MEMORY;
    }
    memset(SapLpcWorkerHandles, 0, SapLpcMaxWorkers * sizeof(HANDLE));

    /** Create a event that will be set by the last thread to exit. **/

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: XsInit: Creating XS Thread Event\n"));
    }

    Status = NtCreateEvent(
                 &SapLpcThreadEvent,
                 EVENT_ALL_ACCESS,
                 NULL,
                 NotificationEvent,
                 FALSE);

    if (!NT_SUCCESS(Status)) {
        IF_DEBUG(INITIALIZATION_ERRORS) {
            SS_PRINT(("NWSAP: XsInit: NtCreateEvent failed: %X\n", Status));
        }

        /** Setup the error so it is reported **/

        SapError   = Status;
        SapEventId = NWSAP_EVENT_CREATELPCEVENT_ERROR;

        /** Return error **/

        SapLpcThreadEvent = NULL;
        return Status;
    }

    /**
        Create the LPC Port here.  This is the port that everyone else
        uses to send requests to us.
    **/

    RtlInitUnicodeString(&UnicodeName, NWSAP_BIND_PORT_NAME_W);

    InitializeObjectAttributes(
        &ObjectAttributes,
        &UnicodeName,
        0,
        NULL,
        NULL);

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: XsInit: Creating XS Port\n"));
    }

    Status = NtCreatePort(
                 &SapXsLpcPortHandle,
                 &ObjectAttributes,
                 0,
                 NWSAP_BS_PORT_MAX_MESSAGE_LENGTH,
                 NWSAP_BS_PORT_MAX_MESSAGE_LENGTH * 32);

    /** If create port fails - return error **/

    if (!NT_SUCCESS(Status)) {

        IF_DEBUG(INITIALIZATION_ERRORS) {
            if (Status == STATUS_OBJECT_NAME_COLLISION) {
                SS_PRINT(("NWSAP: XsInit: The LPC port already exists\n"));
            }
            else {
                SS_PRINT(("NWSAP: XsInit: Failed to create port: %X\n", Status));
            }
        }
        SapXsLpcPortHandle = NULL;

        /** Setup to report the error **/

        SapError   = Status;
        SapEventId = NWSAP_EVENT_CREATELPCPORT_ERROR;

        /** Return error **/

        return Status;
    }

    /**
        Start the thread that listens for connections to
        our port.  If does not matter if someone did a
        NtConnectPort before our NtListenPort, they will
        just block.
    **/

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: Creating XS Worker Threads\n"));
    }
    for (i = 0 ; i < SapLpcMaxWorkers ; i++) {

        /** Count this new thread **/

        SAP_INC_LPC_THREAD_COUNT("SapStartLpcWorkers");

        /** Start the new thread **/

        Handle = CreateThread(
    	    	NULL,			        /* Security Ptr		*/
        		0,			            /* Initial stack size	*/
        		SapXsWorkerThread,	    /* Thread Function	*/
        		(LPVOID)NULL,	        /* Parm for the thread	*/
        		0,			            /* Creation Flags	*/
        		&Threadid);	            /* Ptr to thread id	*/

        /** If create fails - report error and return it **/

        if (Handle == NULL) {

            /** Set the error codes for return **/

            SapError = GetLastError();
            SapEventId = NWSAP_EVENT_STARTLPCWORKER_ERROR;

            /** Uncount the thread **/

            SAP_DEC_LPC_THREAD_COUNT("SapStartWorker Error");

            IF_DEBUG(INITIALIZATION_ERRORS) {
                SS_PRINT(("NWSAP: Error starting LPC Worker thread = %d\n", SapError));
            }

            /** Return Error **/

    	    return SapError;
        }

        /** Save the handle for this thread **/

        SapLpcWorkerHandles[i] = Handle;
    }

    /** Return OK **/

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: XsInit returning OK\n"));
    }
    return 0;
}


/*++
*******************************************************************
        S a p X s S h u t d o w n

Routine Description:

        This routine shuts down the LPC interface.

Arguments:

        None.

Return Value:

        None.

*******************************************************************
--*/

VOID
SapXsShutdown(
    VOID)
{
    PSAP_LPC_CLIENT Clientp;
    PLIST_ENTRY Listp;
    PLIST_ENTRY NListp;
    HANDLE Handle;
    ULONG i;
    BOOL Stopped;

    /** **/

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: XsShutdown Entered\n"));
    }

    /** Nuke all the worker threads **/

    if (SapLpcWorkerHandles) {
        for (i = 0 ; i < SapLpcMaxWorkers ; i++) {
            if (SapLpcWorkerHandles[i]) {

                IF_DEBUG(LPC) {
                    SS_PRINT(("NWSAP: XsShutdown: Stopping thread %d\n",
                            SapLpcWorkerHandles[i]));
                }

                /** Stop the thread **/

                Stopped = TerminateThread(SapLpcWorkerHandles[i], 0);

                IF_DEBUG(LPC) {
                    SS_PRINT(("NWSAP: XsShutdown: Stop of thread %d = %d\n",
                            SapLpcWorkerHandles[i], Stopped));
                }            
            }
        }
    }

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: XsShutdown: Closing LPC Port Handle 0x%lx\n",
                SapXsLpcPortHandle));
    }

    /** Close the handle to all threads die **/

    if (SapXsLpcPortHandle)
        NtClose(SapXsLpcPortHandle);

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: XsShutdown: Cleaning up all clients\n"));
    }

    /** Get rid of all the clients **/

    ACQUIRE_LPCCLIENT_LOCK();
    Listp = SapLpcClientList.Flink;
    InitializeListHead(&SapLpcClientList);
    while (Listp != &SapLpcClientList) {

        /** Save ptr to next entry **/

        NListp = Listp->Flink;

        /** Get ptr to the client and get his handle **/

        Clientp = CONTAINING_RECORD(Listp, SAP_LPC_CLIENT, ListEntry);
        Handle = Clientp->Handle;
        Clientp->Handle = NULL;

        /** Close the handle **/

        if (Handle)
            NtClose(Handle);

        /** Free the entry **/

        SAP_FREE(Clientp, "SapShutdown free Clientp structure\n");

        /** Goto the next entry **/

        Listp = NListp;
    }
    RELEASE_LPCCLIENT_LOCK();

    /** Close the event handle **/

    if (SapLpcThreadEvent != NULL)
        CloseHandle(SapLpcThreadEvent);

    /** **/

    if (SapLpcWorkerHandles) {
        SAP_FREE(SapLpcWorkerHandles, "SapXsShutdown: Worker Handles");
    }

    /** All Done **/

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: XsShutdown: DONE\n"));
    }
    return;
}


/*++
*******************************************************************
        S a p X s W o r k e r T h r e a d

Routine Description:

        This is the LPC worker thread used to handle requests
        on our LPC port.

Arguments:

        Threadparm = Parm given in CreateThread
                     (We don't use it)

Return Value:

        Thread exit value.
*******************************************************************
--*/

DWORD WINAPI
SapXsWorkerThread(
    LPVOID Threadparm)
{
    NTSTATUS Status;
    NWSAP_REQUEST_MESSAGE Request;
    NWSAP_REPLY_MESSAGE Reply;
    PPORT_MESSAGE Myreply;
    PSAP_LPC_CLIENT Clientp;

    /** **/

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: XsWorker entered\n"));
    }

    /**
        Listen for requests from clients.  Handle connections
        special.
    **/

    while (1) {

        /**
            Send the reply for the last message and get
            another message to handle
        **/

        IF_DEBUG(LPC) {
            SS_PRINT(("NWSAP: XsWorker: Calling ReplyWaitReceivePort: Handle = 0x%lx\n", SapXsLpcPortHandle));
        }

        Status = NtReplyWaitReceivePort(
                    SapXsLpcPortHandle,         /* Handle               */
                    &Clientp,                   /* Context              */
                    NULL,                       /* Ptr to reply message */
                    (PPORT_MESSAGE)&Request);   /* Ptr to request message */

        /** Setup ptr to our reply message **/

        IF_DEBUG(LPC) {
            SS_PRINT(("NWSAP: XsWorker: Reply Wait Port: status = 0x%lx: Clientp = 0x%lx\n", Status, Clientp));
        }

        /** If shutting down - just leave **/

        if (!SsInitialized)
            break;

        /** If we got an error - handle it **/

        if (!NT_SUCCESS(Status)) {

            IF_DEBUG(ERRORS) {
                SS_PRINT(("NWSAP: XsWorker: NtReplyWaitReceivePort failed: %X\n", Status));
            }

            continue;
        }

        /** If this is a connection - go handle it **/

        if (Request.PortMessage.u2.s2.Type == LPC_CONNECTION_REQUEST) {
            SapXsHandleConnect((PPORT_MESSAGE)&Request);
            continue;
        }

        /** Handle the message **/

        IF_DEBUG(LPC) {
            SS_PRINT(("NWSAP: XsWorker: Got message = %d, context = 0x%lx\n", Request.MessageType, Clientp));
        }

        Myreply = NULL;
        switch (Request.PortMessage.u2.s2.Type) {
        case LPC_REQUEST:

            IF_DEBUG(LPC) {
                SS_PRINT(("NWSAP: Worker: Got REQUEST: %d\n", Request.MessageType));
            }

            /** Handle the message **/

            Myreply = (PPORT_MESSAGE)&Reply;
            switch (Request.MessageType) {

            case NWSAP_LPCMSG_ADDADVERTISE:
                Reply.Error = SapAddAdvertiseInternal(
                            Request.Message.AdvApi.ServerName,
                            Request.Message.AdvApi.ServerType,
                            Request.Message.AdvApi.ServerAddr,
                            Request.Message.AdvApi.RespondNearest,
                            (ULONG)Clientp);

                memcpy(
                    Reply.Message.AdvApi.ServerAddr,
                    Request.Message.AdvApi.ServerAddr,
                    12);

                break;

            case NWSAP_LPCMSG_REMOVEADVERTISE:
                Reply.Error = SapRemoveAdvertiseInternal(
                            Request.Message.AdvApi.ServerName,
                            Request.Message.AdvApi.ServerType);
                break;

            case NWSAP_LPCMSG_GETOBJECTID:
                Reply.Error = SapGetObjectIDInternal(
                            Request.Message.BindLibApi.ObjectName,
                            Request.Message.BindLibApi.ObjectType,
                            &Reply.Message.BindLibApi.ObjectID);
                break;

            case NWSAP_LPCMSG_GETOBJECTNAME:
                Reply.Error = SapGetObjectNameInternal(
                            Request.Message.BindLibApi.ObjectID,
                            Reply.Message.BindLibApi.ObjectName,
                            &Reply.Message.BindLibApi.ObjectType,
                            Reply.Message.BindLibApi.ObjectAddr);
                break;

            case NWSAP_LPCMSG_SEARCH:
                Reply.Error = SapScanObjectInternal(
                            &Request.Message.BindLibApi.ObjectID,
                            Reply.Message.BindLibApi.ObjectName,
                            &Reply.Message.BindLibApi.ObjectType,
                            Request.Message.BindLibApi.ScanType);

                Reply.Message.BindLibApi.ObjectID = Request.Message.BindLibApi.ObjectID;
                break;

            default:
                IF_DEBUG(LPC) {
                    SS_PRINT(("NWSAP: XsWorker: Got unknown LPC SAP msg: %d\n", Request.MessageType));
                }
                Reply.Error = 1;
                break;
            }
            break;

        /** Client has died - clean up and go on **/

        case LPC_PORT_CLOSED:
        case LPC_CLIENT_DIED:

            IF_DEBUG(LPC) {
                SS_PRINT(("NWSAP: XsWorker: Client DIED: Clientp = 0x%lx\n", Clientp));
            }

            /** Take the client out of the list **/

            ACQUIRE_LPCCLIENT_LOCK();
            RemoveEntryList(&Clientp->ListEntry);
            SapNumLpcClients--;
            if (Clientp->Handle) {
                NtClose(Clientp->Handle);
                Clientp->Handle = NULL;
            }
            RELEASE_LPCCLIENT_LOCK();

            /**
                Cleanup all advertises the client had.

                NOTE:  Disabled now because we are not sure whether
                       we want to do it or not.
            **/

#if 0
            SapClientDisconnected((ULONG)Clientp);
#endif

            /** Free the client memory **/

            SAP_FREE(Clientp, "XsWorker: Leaving\n");

            /** There is no reply for this **/

            Myreply  = NULL;
            break;

        /** All others just leave **/

        default:
            IF_DEBUG(LPC) {
                SS_PRINT(("NWSAP: XsWorker: Got unknown LPC msg type %d\n", Request.PortMessage.u2.s2.Type));
            }
            Myreply  = NULL;                /* No reply */
            break;
        }

        /** Setup for the reply and go back up to send it **/

        if (Myreply) {

            /** Fill out the reply **/

            Reply.PortMessage.u1.s1.DataLength =
                        sizeof(Reply) - sizeof(PORT_MESSAGE);
            Reply.PortMessage.u1.s1.TotalLength = sizeof(Reply);
            Reply.PortMessage.u2.ZeroInit = 0;
            Reply.PortMessage.ClientId  = Request.PortMessage.ClientId;
            Reply.PortMessage.MessageId = Request.PortMessage.MessageId;

            /** Send the reply **/

            Status = NtReplyPort(
                        Clientp->Handle,
                        (PPORT_MESSAGE)&Reply);

            IF_DEBUG(LPC) {
                SS_PRINT(("NWSAP: XsWorker: NtReplyPort status = 0x%lx\n", Status));
            }
        }

        /** Go back to top to send reply and get another request **/
    }

    /** All Done - get out **/

    SAP_DEC_LPC_THREAD_COUNT("LpcWorker: Terminating");
    return NO_ERROR;
}


/*++
*******************************************************************
        S a p X s H a n d l e C o n n e c t

Routine Description:

        This routine is called by the SAP LPC worker threads when
        a connect request is received.  It will handle the
        connect request completely here.

Arguments:

        Request = Ptr to the connection message received

Return Value:

        None.
*******************************************************************
--*/

VOID
SapXsHandleConnect(
    PPORT_MESSAGE Request)
{
    NTSTATUS Status;
    PSAP_LPC_CLIENT Clientp;
    BOOLEAN Acceptit;

    /** Allocate a block for this client **/

    Clientp = SAP_MALLOC(sizeof(SAP_LPC_CLIENT), "Get Lpc Client Struct");
    if (Clientp == NULL) {

        IF_DEBUG(ERRORS) {
            SS_PRINT(("NWSAP: XsWorker: Error allocating client structure\n"));
        }

        /** Log the error **/

        SsLogEvent(
                NWSAP_EVENT_LPCLISTENMEMORY_ERROR,
                0,
                NULL,
                0);

        /** Do not accept the connect **/

        Acceptit = FALSE;
    }
    else {

        /** We will accept the connection **/

        Acceptit = TRUE;

        /** Initialize this block **/

        Clientp->Handle  = NULL;
        Clientp->Context = (PVOID)Clientp;
        InitializeListHead(&Clientp->ListEntry);

        /** Put this entry in our client list **/

        ACQUIRE_LPCCLIENT_LOCK();
        InsertHeadList(&SapLpcClientList, &Clientp->ListEntry);
        SapNumLpcClients++;
        RELEASE_LPCCLIENT_LOCK();
    }

    /** Accept/Refuse the connection according to 'acceptit' **/

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: XsWorker: Calling NtAcceptConnectPort: Clientp = 0x%lx\n", Clientp));
    }

    Status = NtAcceptConnectPort(
                 &Clientp->Handle,      /* Handle for this client */
                 Clientp->Context,      /* Port Context         */
                 Request,               /* Connection request   */
                 Acceptit,              /* AcceptConnection     */
                 NULL,                  /* ServerView           */
                 NULL);                 /* Client View          */

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: XsWorker: NtAcceptConnectPort: status = 0x%lx, handle = 0x%lx\n",Status,Clientp->Handle));
    }

    /**
        If it failed - cleanup and return
    **/

    if (!NT_SUCCESS(Status)) {

        /** **/

        IF_DEBUG(ERRORS) {
            SS_PRINT(("NWSAP: XsWorker: NtAcceptConnectPort failed: %X\n", Status));
        }

        /** Take him out of our list **/

        if (Clientp) {
            ACQUIRE_LPCCLIENT_LOCK();
            RemoveEntryList(&Clientp->ListEntry);
            SapNumLpcClients--;
            RELEASE_LPCCLIENT_LOCK();

            /** Free the memory **/

            SAP_FREE(Clientp, "NtAcceptConnectPort error");
        }

        return;
    }

    /** If no Clientp ptr we rejected the connection - we are done **/

    if (Clientp == NULL)
        return;

    /**
        Complete the connection to the port, thereby releasing
        the clients NtConnectPort.
    **/

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: XsWorker: Calling NtCompleteConnectPort\n"));
    }

    Status = NtCompleteConnectPort(Clientp->Handle);

    IF_DEBUG(LPC) {
        SS_PRINT(("NWSAP: XsWorker: NtCompleteConnectPort: status = 0x%lx\n",Status));
    }

    /** If it failed - cleanup and return **/

    if (!NT_SUCCESS(Status)) {
        IF_DEBUG(ERRORS) {
            SS_PRINT(("NWSAP: XsWorker: NtCompleteConnectPort failed: %X\n", Status));
        }

        /** Take him out of our list **/

        ACQUIRE_LPCCLIENT_LOCK();
        RemoveEntryList(&Clientp->ListEntry);
        SapNumLpcClients--;
        RELEASE_LPCCLIENT_LOCK();

        /** Close the handle **/

        NtClose(Clientp->Handle);

        /** Release the memory **/

        SAP_FREE(Clientp, "NtCompleteConnectPort error");
        return;
    }

    /** Everything finished OK **/

    return;
}