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
/*
 * COPYRIGHT:   See COPYING in the top level directory
 * PROJECT:     ReactOS WinSock 2 API
 * FILE:        dll/win32/ws2_32_new/src/nscatalo.c
 * PURPOSE:     Namespace Catalog Object
 * PROGRAMMER:  Alex Ionescu (alex@relsoft.net)
 */

/* INCLUDES ******************************************************************/

#include <ws2_32.h>

#define NDEBUG
#include <debug.h>

/* DATA **********************************************************************/

#define WsNcLock()          EnterCriticalSection(&Catalog->Lock)
#define WsNcUnlock()        LeaveCriticalSection(&Catalog->Lock)

/* FUNCTIONS *****************************************************************/

PNSCATALOG
WSAAPI
WsNcAllocate(VOID)
{
    PNSCATALOG Catalog;

    /* Allocate the catalog */
    Catalog = HeapAlloc(WsSockHeap, HEAP_ZERO_MEMORY, sizeof(*Catalog));

    /* Return it */
    return Catalog;
}

BOOLEAN
WSAAPI
WsNcOpen(IN PNSCATALOG Catalog,
         IN HKEY ParentKey)
{
    LONG ErrorCode;
    DWORD CreateDisposition;
    HKEY CatalogKey, NewKey;
    DWORD RegType = REG_DWORD;
    DWORD RegSize = sizeof(DWORD);
    DWORD UniqueId = 0;
    DWORD NewData = 0;
    CHAR* CatalogKeyName;

    /* Initialize the catalog lock and namespace list */
    InitializeCriticalSection(&Catalog->Lock);
    InitializeListHead(&Catalog->CatalogList);

    /* Read the catalog name */
    ErrorCode = RegQueryValueEx(ParentKey,<--- ErrorCode is assigned
                                "Current_NameSpace_Catalog",
                                0,
                                &RegType,
                                NULL,
                                &RegSize);

    CatalogKeyName = HeapAlloc(WsSockHeap, 0, RegSize);

    /* Read the catalog name */
    ErrorCode = RegQueryValueEx(ParentKey,<--- ErrorCode is overwritten<--- ErrorCode is assigned
                                "Current_NameSpace_Catalog",
                                0,
                                &RegType,
                                (LPBYTE)CatalogKeyName,
                                &RegSize);

    /* Open the Catalog Key */
    ErrorCode = RegOpenKeyEx(ParentKey,<--- ErrorCode is overwritten
                             CatalogKeyName,
                             0,
                             MAXIMUM_ALLOWED,
                             &CatalogKey);

    /* If we didn't find the key, create it */
    if (ErrorCode == ERROR_SUCCESS)
    {
        /* Fake that we opened an existing key */
        CreateDisposition = REG_OPENED_EXISTING_KEY;
    }
    else if (ErrorCode == ERROR_FILE_NOT_FOUND)
    {
        /* Create the Catalog Name */
        ErrorCode = RegCreateKeyEx(ParentKey,
                                   CatalogKeyName,
                                   0,
                                   NULL,
                                   REG_OPTION_NON_VOLATILE,
                                   KEY_ALL_ACCESS,
                                   NULL,
                                   &CatalogKey,
                                   &CreateDisposition);
    }

    HeapFree(WsSockHeap, 0, CatalogKeyName);
    RegType = REG_DWORD;
    RegSize = sizeof(DWORD);

    /* Fail if that didn't work */
    if (ErrorCode != ERROR_SUCCESS) return FALSE;

    /* Check if we had to create the key */
    if (CreateDisposition == REG_CREATED_NEW_KEY)
    {
        /* Write the count of entries (0 now) */
        ErrorCode = RegSetValueEx(CatalogKey,
                                  "Num_Catalog_Entries",
                                  0,
                                  REG_DWORD,
                                  (LPBYTE)&NewData,
                                  sizeof(NewData));
        if (ErrorCode != ERROR_SUCCESS)
        {
            /* Close the key and fail */
            RegCloseKey(CatalogKey);
            return FALSE;
        }

        /* Write the first catalog entry Uniqe ID */
        NewData = 1;
        ErrorCode = RegSetValueEx(CatalogKey,
                                  "Serial_Access_Num",
                                  0,
                                  REG_DWORD,
                                  (LPBYTE)&NewData,
                                  sizeof(NewData));
        if (ErrorCode != ERROR_SUCCESS)
        {
            /* Close the key and fail */
            RegCloseKey(CatalogKey);
            return FALSE;
        }

        /* Create a key for this entry */
        ErrorCode = RegCreateKeyEx(CatalogKey,
                                   "Catalog_Entries",
                                   0,
                                   NULL,
                                   REG_OPTION_NON_VOLATILE,
                                   KEY_ALL_ACCESS,
                                   NULL,
                                   &NewKey,
                                   &CreateDisposition);
        if (ErrorCode != ERROR_SUCCESS)
        {
            /* Close the key and fail */
            RegCloseKey(CatalogKey);
            return FALSE;
        }

        /* Close the key since we don't need it */
        RegCloseKey(NewKey);
    }
    else
    {
        RegSize = sizeof(UniqueId);
        /* Read the serial number */
        ErrorCode = RegQueryValueEx(CatalogKey,
                                    "Serial_Access_Num",
                                    0,
                                    &RegType,
                                    (LPBYTE)&UniqueId,
                                    &RegSize);

        /* Check if it's missing for some reason */
        if (ErrorCode != ERROR_SUCCESS)
        {
            /* Write the first catalog entry Unique ID */
            NewData = 1;
            ErrorCode = RegSetValueEx(CatalogKey,
                                      "Serial_Access_Num",
                                      0,
                                      REG_DWORD,
                                      (LPBYTE)&NewData,
                                      sizeof(NewData));
        }
    }

    /* Set the Catalog Key */
    Catalog->CatalogKey = CatalogKey;
    return TRUE;
}

INT
WSAAPI
WsNcInitializeFromRegistry(IN PNSCATALOG Catalog,
                           IN HKEY ParentKey,
                           IN HANDLE CatalogEvent)
{
    INT ErrorCode = WSASYSCALLFAILURE;

    /* Open the catalog */
    if (WsNcOpen(Catalog, ParentKey))
    {
        /* Refresh it */
        ErrorCode = WsNcRefreshFromRegistry(Catalog, CatalogEvent);
    }

    /* Return the status */
    return ErrorCode;
}

INT
WSAAPI
WsNcRefreshFromRegistry(IN PNSCATALOG Catalog,
                        IN HANDLE CatalogEvent)
{
    INT ErrorCode;
    BOOLEAN LocalEvent = FALSE;
    LIST_ENTRY LocalList;
    DWORD UniqueId;
    HKEY EntriesKey;
    DWORD CatalogEntries;
    PNSCATALOG_ENTRY CatalogEntry;
    BOOL NewChangesMade;
    PLIST_ENTRY Entry;
    DWORD RegType = REG_DWORD;
    DWORD RegSize = sizeof(DWORD);
    DWORD i;

    /* Check if we got an event */
    if (!CatalogEvent)
    {
        /* Create an event ourselves */
        CatalogEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
        if (!CatalogEvent) return WSASYSCALLFAILURE;
        LocalEvent = TRUE;
    }

    /* Lock the catalog */
    WsNcLock();

    /* Initialize our local list for the loop */
    InitializeListHead(&LocalList);

    /* Start looping */
    do
    {
        /* Setup notifications for the catalog entry */
        ErrorCode = WsSetupCatalogProtection(Catalog->CatalogKey,
                                             CatalogEvent,
                                             &UniqueId);
        if (ErrorCode != ERROR_SUCCESS) break;

        /* Check if we've changed till now */
        if (UniqueId == Catalog->UniqueId)
        {
            /* We haven't, so return */
            ErrorCode = ERROR_SUCCESS;
            break;
        }

        /* Now Open the Entries */
        ErrorCode = RegOpenKeyEx(Catalog->CatalogKey,
                                 "Catalog_Entries",
                                 0,
                                 MAXIMUM_ALLOWED,
                                 &EntriesKey);
        if (ErrorCode != ERROR_SUCCESS)
        {
            /* Critical failure */
            ErrorCode = WSASYSCALLFAILURE;
            break;
        }

        /* Find out how many there are */
        ErrorCode = RegQueryValueEx(Catalog->CatalogKey,
                                    "Num_Catalog_Entries",
                                    0,
                                    &RegType,
                                    (LPBYTE)&CatalogEntries,
                                    &RegSize);
        if (ErrorCode != ERROR_SUCCESS)
        {
            /* Critical failure */
            ErrorCode = WSASYSCALLFAILURE;
            break;
        }

        /* Initialize them all */
        for (i = 1; i <= CatalogEntries; i++)
        {
            /* Allocate a Catalog Entry Structure */
            CatalogEntry = WsNcEntryAllocate();
            if (!CatalogEntry)
            {
                /* Not enough memory, fail */
                ErrorCode = WSA_NOT_ENOUGH_MEMORY;
                break;
            }

            /* Initialize it from the Registry Key */
            ErrorCode = WsNcEntryInitializeFromRegistry(CatalogEntry,
                                                        EntriesKey,
                                                        i);
            if (ErrorCode != ERROR_SUCCESS)
            {
                /* We failed to get it, dereference the entry and leave */
                WsNcEntryDereference(CatalogEntry);
                break;
            }

            /* Insert it to our List */
            InsertTailList(&LocalList, &CatalogEntry->CatalogLink);
        }

        /* Close the catalog key */
        RegCloseKey(EntriesKey);

        /* Check if we changed during our read and if we have success */
        NewChangesMade = WsCheckCatalogState(CatalogEvent);
        if (!NewChangesMade && ErrorCode == ERROR_SUCCESS)
        {
            /* All is good, update the protocol list */
            WsNcUpdateNamespaceList(Catalog, &LocalList);

            /* Update and return */
            Catalog->UniqueId = UniqueId;
            break;
        }

        /* We failed and/or catalog data changed, free what we did till now */
        while (!IsListEmpty(&LocalList))
        {
            /* Get the LP Catalog Item */
            Entry = RemoveHeadList(&LocalList);
            CatalogEntry = CONTAINING_RECORD(Entry, NSCATALOG_ENTRY, CatalogLink);

            /* Dereference it */
            WsNcEntryDereference(CatalogEntry);
        }
    } while (NewChangesMade);

    /* Release the lock */
    WsNcUnlock();

    /* Close the event, if any was created by us */
    if (LocalEvent) CloseHandle(CatalogEvent);

    /* All Done */
    return ErrorCode;
}

VOID
WSAAPI
WsNcEnumerateCatalogItems(IN PNSCATALOG Catalog,
                          IN PNSCATALOG_ENUMERATE_PROC Callback,
                          IN PVOID Context)
{
    PLIST_ENTRY Entry;
    PNSCATALOG_ENTRY CatalogEntry;
    BOOL GoOn = TRUE;

    /* Lock the catalog */
    WsNcLock();

    /* Loop the entries */
    Entry = Catalog->CatalogList.Flink;
    while (GoOn && (Entry != &Catalog->CatalogList))
    {
        /* Get the entry */
        CatalogEntry = CONTAINING_RECORD(Entry, NSCATALOG_ENTRY, CatalogLink);

        /* Move to the next one and call the callback */
        Entry = Entry->Flink;
        GoOn = Callback(Context, CatalogEntry);
    }

    /* Release the lock */
    WsNcUnlock();
}

INT
WSAAPI
WsNcLoadProvider(IN PNSCATALOG Catalog,
                 IN PNSCATALOG_ENTRY CatalogEntry)
{
    INT ErrorCode = ERROR_SUCCESS;
    PNS_PROVIDER Provider;

    /* Lock the catalog */
    WsNcLock();

    /* Check if we have a provider already */
    if (!CatalogEntry->Provider)
    {
        /* Allocate a provider */
        if ((Provider = WsNpAllocate()))
        {
            /* Initialize it */
            ErrorCode = WsNpInitialize(Provider,
                                       CatalogEntry->DllPath,
                                       &CatalogEntry->ProviderId);

            /* Ensure success */
            if (ErrorCode == ERROR_SUCCESS)
            {
                /* Set the provider */
                WsNcEntrySetProvider(CatalogEntry, Provider);
            }

            /* Dereference it */
            WsNpDereference(Provider);
        }
        else
        {
            /* No memory */
            ErrorCode = WSA_NOT_ENOUGH_MEMORY;
        }
    }

    /* Release the lock and return */
    WsNcUnlock();
    return ErrorCode;
}

INT
WSAAPI
WsNcGetServiceClassInfo(IN PNSCATALOG Catalog,
                        IN OUT LPDWORD BugSize,
                        IN OUT LPWSASERVICECLASSINFOW lpServiceClassInfo)
{
    /* Not yet implemented in the spec? */
    SetLastError(ERROR_SUCCESS);
    return SOCKET_ERROR;
}

VOID
WSAAPI
WsNcUpdateNamespaceList(IN PNSCATALOG Catalog,
                        IN PLIST_ENTRY List)
{
    LIST_ENTRY TempList;
    PNSCATALOG_ENTRY CatalogEntry, OldCatalogEntry;
    PLIST_ENTRY Entry;

    /* First move from our list to the old one */
    InsertHeadList(&Catalog->CatalogList, &TempList);
    RemoveEntryList(&Catalog->CatalogList);
    InitializeListHead(&Catalog->CatalogList);

    /* Loop every item on the list */
    while (!IsListEmpty(List))
    {
        /* Get the catalog entry */
        Entry = RemoveHeadList(List);
        CatalogEntry = CONTAINING_RECORD(Entry, NSCATALOG_ENTRY, CatalogLink);

        /* Check if this item is already on our list */
        Entry = TempList.Flink;
        while (Entry != &TempList)
        {
            /* Get the catalog entry */
            OldCatalogEntry = CONTAINING_RECORD(Entry, NSCATALOG_ENTRY, CatalogLink);
            Entry = Entry->Flink;

            /* Check if they match */
            if (IsEqualGUID(&CatalogEntry->ProviderId,
                            &OldCatalogEntry->ProviderId))
            {
                /* We have a match, use the old item instead */
                WsNcEntryDereference(CatalogEntry);
                CatalogEntry = OldCatalogEntry;
                RemoveEntryList(&CatalogEntry->CatalogLink);

                /* Decrease the number of protocols we have */
                Catalog->ItemCount--;
                break;
            }
        }

        /* Add this item */
        InsertTailList(&Catalog->CatalogList, &CatalogEntry->CatalogLink);
        Catalog->ItemCount++;
    }

    /* If there's anything left on the temporary list */
    while (!IsListEmpty(&TempList))
    {
        /* Get the entry */
        Entry = RemoveHeadList(&TempList);
        CatalogEntry = CONTAINING_RECORD(Entry, NSCATALOG_ENTRY, CatalogLink);

        /* Remove it */
        Catalog->ItemCount--;
        WsNcEntryDereference(CatalogEntry);
    }
}

INT
WSAAPI
WsNcGetCatalogFromProviderId(IN PNSCATALOG Catalog,
                             IN LPGUID ProviderId,
                             OUT PNSCATALOG_ENTRY *CatalogEntry)
{
    INT ErrorCode = WSAEINVAL;
    PLIST_ENTRY NextEntry;
    PNSCATALOG_ENTRY Entry;

    /* Lock the catalog */
    WsNcLock();

    /* Match the Id with all the entries in the List */
    NextEntry = Catalog->CatalogList.Flink;
    while (NextEntry != &Catalog->CatalogList)
    {
        /* Get the Current Entry */
        Entry = CONTAINING_RECORD(NextEntry, NSCATALOG_ENTRY, CatalogLink);
        NextEntry = NextEntry->Flink;

        /* Check if this is the Catalog Entry ID we want */
        if (IsEqualGUID(&Entry->ProviderId, ProviderId))
        {
            /* If it doesn't already have a provider, load the provider */
            if (!Entry->Provider)
                ErrorCode = WsNcLoadProvider(Catalog, Entry);

            /* If we succeeded, reference the entry and return it */
            if (Entry->Provider /* || ErrorCode == ERROR_SUCCESS */)
            {
                InterlockedIncrement(&Entry->RefCount);
                *CatalogEntry = Entry;
                ErrorCode = ERROR_SUCCESS;
                break;
            }
        }
    }

    /* Release the lock and return */
    WsNcUnlock();
    return ErrorCode;
}

BOOL
WSAAPI
WsNcMatchProtocols(IN DWORD NameSpace,
                   IN LONG AddressFamily,
                   IN LPWSAQUERYSETW QuerySet)
{
    DWORD ProtocolCount = QuerySet->dwNumberOfProtocols;
    LPAFPROTOCOLS AfpProtocols = QuerySet->lpafpProtocols;
    LONG Family;

    /* Check for valid family */
    if (AddressFamily != -1)
    {
        /* Check if it's the magic */
        if (AddressFamily == AF_UNSPEC) return TRUE;
        Family = AddressFamily;
    }
    else
    {
        /* No family given, check for namespace */
        if (NameSpace == NS_SAP)
        {
            /* Use IPX family */
            Family = AF_IPX;
        }
        else
        {
            /* Other namespace, it's valid */
            return TRUE;
        }
    }

    /* Now try to get a match */
    while (ProtocolCount--)
    {
        /* Check this protocol entry */
        if ((AfpProtocols->iAddressFamily == AF_UNSPEC) ||
            (AfpProtocols->iAddressFamily == Family))
        {
            /* Match found */
            return TRUE;
        }

        /* Move to the next one */
        AfpProtocols++;
    }

    /* No match */
    return FALSE;
}

VOID
WSAAPI
WsNcRemoveCatalogItem(IN PNSCATALOG Catalog,
                      IN PNSCATALOG_ENTRY Entry)
{
    /* Remove the entry from the list */
    RemoveEntryList(&Entry->CatalogLink);

    /* Decrease our count */
    Catalog->ItemCount--;
}

VOID
WSAAPI
WsNcDelete(IN PNSCATALOG Catalog)
{
    PLIST_ENTRY Entry;
    PNSCATALOG_ENTRY CatalogEntry;

    /* Check if we're initialized */
    if (!Catalog->CatalogList.Flink) return;

    /* Acquire lock */
    WsNcLock();

    /* Loop every entry */
    Entry = Catalog->CatalogList.Flink;
    while (Entry != &Catalog->CatalogList)
    {
        /* Get this entry */
        CatalogEntry = CONTAINING_RECORD(Entry, NSCATALOG_ENTRY, CatalogLink);

        /* Remove it and dereference it */
        WsNcRemoveCatalogItem(Catalog, CatalogEntry);
        WsNcEntryDereference(CatalogEntry);

        /* Move to the next entry */
        Entry = Catalog->CatalogList.Flink;
    }

    /* Check if the catalog key is opened */
    if (Catalog->CatalogKey)
    {
        /* Close it */
        RegCloseKey(Catalog->CatalogKey);
        Catalog->CatalogKey = NULL;
    }

    /* Release and delete the lock */
    WsNcUnlock();
    DeleteCriticalSection(&Catalog->Lock);

    /* Delete the object */
    HeapFree(WsSockHeap, 0, Catalog);
}