summaryrefslogtreecommitdiffstats
path: root/mDNSResponder/mDNSWindows/mdnsNSP/mdnsNSP.c
blob: 2cd01effe640573dcc7bdf84001e58560bbc3b51 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
/* -*- Mode: C; tab-width: 4 -*-
 *
 * Copyright (c) 2003-2004 Apple Computer, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>

#include	"ClientCommon.h"
#include	"CommonServices.h"
#include	"DebugServices.h"

#include	<iphlpapi.h>
#include	<guiddef.h>
#include	<ws2spi.h>
#include	<shlwapi.h>



#include	"dns_sd.h"

#pragma comment(lib, "DelayImp.lib")

#ifdef _MSC_VER
#define swprintf _snwprintf
#define snprintf _snprintf
#endif

#define MAX_LABELS 128

#if 0
#pragma mark == Structures ==
#endif

//===========================================================================================================================
//	Structures
//===========================================================================================================================

typedef struct	Query *		QueryRef;
typedef struct	Query		Query;
struct	Query
{
	QueryRef			next;
	int					refCount;
	DWORD				querySetFlags;
	WSAQUERYSETW *		querySet;
	size_t				querySetSize;
	HANDLE				data4Event;
	HANDLE				data6Event;
	HANDLE				cancelEvent;
	HANDLE				waitHandles[ 3 ];
	DWORD				waitCount;
	DNSServiceRef		resolver4;
	DNSServiceRef		resolver6;
	char				name[ kDNSServiceMaxDomainName ];
	size_t				nameSize;
	uint8_t				numValidAddrs;
	uint32_t			addr4;
	bool				addr4Valid;
	uint8_t				addr6[16];
	u_long				addr6ScopeId;
	bool				addr6Valid;
};

#define BUFFER_INITIAL_SIZE		4192
#define ALIASES_INITIAL_SIZE	5

typedef struct HostsFile
{
	int			m_bufferSize;
	char	*	m_buffer;
	FILE	*	m_fp;
} HostsFile;


typedef struct HostsFileInfo
{
	struct hostent		m_host;
	struct HostsFileInfo	*	m_next;
} HostsFileInfo;


#if 0
#pragma mark == Prototypes ==
#endif

//===========================================================================================================================
//	Prototypes
//===========================================================================================================================

// DLL Exports

BOOL WINAPI		DllMain( HINSTANCE inInstance, DWORD inReason, LPVOID inReserved );
STDAPI			DllRegisterServer( void );
STDAPI			DllRegisterServer( void );

	
// NSP SPIs

int	WSPAPI	NSPCleanup( LPGUID inProviderID );

DEBUG_LOCAL int WSPAPI
	NSPLookupServiceBegin(
		LPGUID					inProviderID,
		LPWSAQUERYSETW			inQuerySet,
		LPWSASERVICECLASSINFOW	inServiceClassInfo,
		DWORD					inFlags,   
		LPHANDLE				outLookup );

DEBUG_LOCAL int WSPAPI
	NSPLookupServiceNext(  
		HANDLE			inLookup,
		DWORD			inFlags,
		LPDWORD			ioBufferLength,
		LPWSAQUERYSETW	outResults );

DEBUG_LOCAL int WSPAPI	NSPLookupServiceEnd( HANDLE inLookup );

DEBUG_LOCAL int WSPAPI
	NSPSetService(
		LPGUID					inProviderID,						
		LPWSASERVICECLASSINFOW	inServiceClassInfo,   
		LPWSAQUERYSETW			inRegInfo,				  
		WSAESETSERVICEOP		inOperation,			   
		DWORD					inFlags );

DEBUG_LOCAL int WSPAPI	NSPInstallServiceClass( LPGUID inProviderID, LPWSASERVICECLASSINFOW inServiceClassInfo );
DEBUG_LOCAL int WSPAPI	NSPRemoveServiceClass( LPGUID inProviderID, LPGUID inServiceClassID );
DEBUG_LOCAL int WSPAPI	NSPGetServiceClassInfo(	LPGUID inProviderID, LPDWORD ioBufSize, LPWSASERVICECLASSINFOW ioServiceClassInfo );

// Private

#define	NSPLock()		EnterCriticalSection( &gLock );
#define	NSPUnlock()		LeaveCriticalSection( &gLock );

DEBUG_LOCAL OSStatus	QueryCreate( const WSAQUERYSETW *inQuerySet, DWORD inQuerySetFlags, QueryRef *outRef );
DEBUG_LOCAL OSStatus	QueryRetain( QueryRef inRef );
DEBUG_LOCAL OSStatus	QueryRelease( QueryRef inRef );

DEBUG_LOCAL void CALLBACK_COMPAT
	QueryRecordCallback4(
		DNSServiceRef		inRef,
		DNSServiceFlags		inFlags,
		uint32_t			inInterfaceIndex,
		DNSServiceErrorType	inErrorCode,
		const char *		inName,    
		uint16_t			inRRType,
		uint16_t			inRRClass,
		uint16_t			inRDataSize,
		const void *		inRData,
		uint32_t			inTTL,
		void *				inContext );

DEBUG_LOCAL void CALLBACK_COMPAT
	QueryRecordCallback6(
		DNSServiceRef		inRef,
		DNSServiceFlags		inFlags,
		uint32_t			inInterfaceIndex,
		DNSServiceErrorType	inErrorCode,
		const char *		inName,    
		uint16_t			inRRType,
		uint16_t			inRRClass,
		uint16_t			inRDataSize,
		const void *		inRData,
		uint32_t			inTTL,
		void *				inContext );

DEBUG_LOCAL OSStatus
	QueryCopyQuerySet( 
		QueryRef 				inRef, 
		const WSAQUERYSETW *	inQuerySet, 
		DWORD 					inQuerySetFlags, 
		WSAQUERYSETW **			outQuerySet, 
		size_t *				outSize );

DEBUG_LOCAL void
	QueryCopyQuerySetTo( 
		QueryRef 				inRef, 
		const WSAQUERYSETW *	inQuerySet, 
		DWORD 					inQuerySetFlags, 
		WSAQUERYSETW *			outQuerySet );

DEBUG_LOCAL size_t	QueryCopyQuerySetSize( QueryRef inRef, const WSAQUERYSETW *inQuerySet, DWORD inQuerySetFlags );

#if( DEBUG )
	void	DebugDumpQuerySet( DebugLevel inLevel, const WSAQUERYSETW *inQuerySet );
	
	#define	dlog_query_set( LEVEL, SET )		DebugDumpQuerySet( LEVEL, SET )
#else
	#define	dlog_query_set( LEVEL, SET )
#endif

DEBUG_LOCAL BOOL		InHostsTable( const char * name );
DEBUG_LOCAL BOOL		IsLocalName( HostsFileInfo * node );
DEBUG_LOCAL BOOL		IsSameName( HostsFileInfo * node, const char * name );
DEBUG_LOCAL OSStatus	HostsFileOpen( HostsFile ** self, const char * fname );
DEBUG_LOCAL OSStatus	HostsFileClose( HostsFile * self );
DEBUG_LOCAL void		HostsFileInfoFree( HostsFileInfo * info );
DEBUG_LOCAL OSStatus	HostsFileNext( HostsFile * self, HostsFileInfo ** hInfo );
DEBUG_LOCAL DWORD		GetScopeId( DWORD ifIndex );

#ifdef ENABLE_REVERSE_LOOKUP
DEBUG_LOCAL OSStatus	IsReverseLookup( LPCWSTR name, size_t size );
#endif


#if 0
#pragma mark == Globals ==
#endif

//===========================================================================================================================
//	Globals
//===========================================================================================================================

// {B600E6E9-553B-4a19-8696-335E5C896153}
DEBUG_LOCAL HINSTANCE				gInstance			= NULL;
DEBUG_LOCAL wchar_t				*	gNSPName			= L"mdnsNSP";
DEBUG_LOCAL GUID					gNSPGUID			= { 0xb600e6e9, 0x553b, 0x4a19, { 0x86, 0x96, 0x33, 0x5e, 0x5c, 0x89, 0x61, 0x53 } };
DEBUG_LOCAL LONG					gRefCount			= 0;
DEBUG_LOCAL CRITICAL_SECTION		gLock;
DEBUG_LOCAL bool					gLockInitialized 	= false;
DEBUG_LOCAL QueryRef				gQueryList	 		= NULL;
DEBUG_LOCAL HostsFileInfo		*	gHostsFileInfo		= NULL;
typedef DWORD
	( WINAPI * GetAdaptersAddressesFunctionPtr )( 
			ULONG 					inFamily, 
			DWORD 					inFlags, 
			PVOID 					inReserved, 
			PIP_ADAPTER_ADDRESSES 	inAdapter, 
			PULONG					outBufferSize );

DEBUG_LOCAL HMODULE								gIPHelperLibraryInstance			= NULL;
DEBUG_LOCAL GetAdaptersAddressesFunctionPtr		gGetAdaptersAddressesFunctionPtr	= NULL;



#if 0
#pragma mark -
#endif

//===========================================================================================================================
//	DllMain
//===========================================================================================================================

BOOL APIENTRY	DllMain( HINSTANCE inInstance, DWORD inReason, LPVOID inReserved )
{
	DEBUG_USE_ONLY( inInstance );
	DEBUG_UNUSED( inReserved );

	switch( inReason )
	{
		case DLL_PROCESS_ATTACH:			
			gInstance = inInstance;		
			gHostsFileInfo	= NULL;
			debug_initialize( kDebugOutputTypeWindowsEventLog, "mDNS NSP", inInstance );
			debug_set_property( kDebugPropertyTagPrintLevel, kDebugLevelNotice );
			dlog( kDebugLevelTrace, "\n" );
			dlog( kDebugLevelVerbose, "%s: process attach\n", __ROUTINE__ );

			break;
		
		case DLL_PROCESS_DETACH:
			HostsFileInfoFree( gHostsFileInfo );
			gHostsFileInfo = NULL;
			dlog( kDebugLevelVerbose, "%s: process detach\n", __ROUTINE__ );
			break;
		
		case DLL_THREAD_ATTACH:
			dlog( kDebugLevelVerbose, "%s: thread attach\n", __ROUTINE__ );
			break;
		
		case DLL_THREAD_DETACH:
			dlog( kDebugLevelVerbose, "%s: thread detach\n", __ROUTINE__ );
			break;
		
		default:
			dlog( kDebugLevelNotice, "%s: unknown reason code (%d)\n", __ROUTINE__, inReason );
			break;
	}

	return( TRUE );
}


//===========================================================================================================================
//	DllRegisterServer
//===========================================================================================================================

STDAPI	DllRegisterServer( void )
{
	WSADATA		wsd;
	WCHAR		path[ MAX_PATH ];
	HRESULT		err;
	
	dlog( kDebugLevelTrace, "DllRegisterServer\n" );

	err = WSAStartup( MAKEWORD( 2, 2 ), &wsd );
	err = translate_errno( err == 0, errno_compat(), WSAEINVAL );
	require_noerr( err, exit );

	// Unregister before registering to workaround an installer
	// problem during upgrade installs.

	WSCUnInstallNameSpace( &gNSPGUID );

	err = GetModuleFileNameW( gInstance, path, MAX_PATH );
	err = translate_errno( err != 0, errno_compat(), kUnknownErr );
	require_noerr( err, exit );

	err = WSCInstallNameSpace( gNSPName, path, NS_DNS, 1, &gNSPGUID );
	err = translate_errno( err == 0, errno_compat(), WSAEINVAL );
	require_noerr( err, exit );
	
exit:

	WSACleanup();
	return( err );
}

//===========================================================================================================================
//	DllUnregisterServer
//===========================================================================================================================

STDAPI	DllUnregisterServer( void )
{
	WSADATA		wsd;
	HRESULT err;
	
	dlog( kDebugLevelTrace, "DllUnregisterServer\n" );
	
	err = WSAStartup( MAKEWORD( 2, 2 ), &wsd );
	err = translate_errno( err == 0, errno_compat(), WSAEINVAL );
	require_noerr( err, exit );
	
	err = WSCUnInstallNameSpace( &gNSPGUID );
	err = translate_errno( err == 0, errno_compat(), WSAEINVAL );
	require_noerr( err, exit );
		
exit:

	WSACleanup();
	return err;
}


//===========================================================================================================================
//	NSPStartup
//
//	This function is called when our namespace DLL is loaded. It sets up the NSP functions we implement and initializes us.
//===========================================================================================================================

int WSPAPI	NSPStartup( LPGUID inProviderID, LPNSP_ROUTINE outRoutines )
{
	OSStatus		err;
	
	dlog( kDebugLevelTrace, "%s begin (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	dlog( kDebugLevelTrace, "%s (GUID=%U, refCount=%ld)\n", __ROUTINE__, inProviderID, gRefCount );
	
	// Only initialize if this is the first time NSPStartup is called. 
	
	if( InterlockedIncrement( &gRefCount ) != 1 )
	{
		err = NO_ERROR;
		goto exit;
	}
	
	// Initialize our internal state.
	
	InitializeCriticalSection( &gLock );
	gLockInitialized = true;
	
	// Set the size to exclude NSPIoctl because we don't implement it.
	
	outRoutines->cbSize					= FIELD_OFFSET( NSP_ROUTINE, NSPIoctl );
	outRoutines->dwMajorVersion			= 4;
	outRoutines->dwMinorVersion			= 4;
	outRoutines->NSPCleanup				= NSPCleanup;
	outRoutines->NSPLookupServiceBegin	= NSPLookupServiceBegin;
	outRoutines->NSPLookupServiceNext	= NSPLookupServiceNext;
	outRoutines->NSPLookupServiceEnd	= NSPLookupServiceEnd;
	outRoutines->NSPSetService			= NSPSetService;
	outRoutines->NSPInstallServiceClass	= NSPInstallServiceClass;
	outRoutines->NSPRemoveServiceClass	= NSPRemoveServiceClass;
	outRoutines->NSPGetServiceClassInfo	= NSPGetServiceClassInfo;
	
	// See if we can get the address for the GetAdaptersAddresses() API.  This is only in XP, but we want our
	// code to run on older versions of Windows

	if ( !gIPHelperLibraryInstance )
	{
		gIPHelperLibraryInstance = LoadLibrary( TEXT( "Iphlpapi" ) );
		if( gIPHelperLibraryInstance )
		{
			gGetAdaptersAddressesFunctionPtr = (GetAdaptersAddressesFunctionPtr) GetProcAddress( gIPHelperLibraryInstance, "GetAdaptersAddresses" );
		}
	}

	err = NO_ERROR;
	
exit:
	dlog( kDebugLevelTrace, "%s end   (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	if( err != NO_ERROR )
	{
		NSPCleanup( inProviderID );
		SetLastError( (DWORD) err );
		return( SOCKET_ERROR );
	}
	return( NO_ERROR );
}

//===========================================================================================================================
//	NSPCleanup
//
//	This function is called when our namespace DLL is unloaded. It cleans up anything we set up in NSPStartup.
//===========================================================================================================================

int	WSPAPI	NSPCleanup( LPGUID inProviderID )
{
	DEBUG_USE_ONLY( inProviderID );
	
	dlog( kDebugLevelTrace, "%s begin (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	dlog( kDebugLevelTrace, "%s (GUID=%U, refCount=%ld)\n", __ROUTINE__, inProviderID, gRefCount );
	
	// Only initialize if this is the first time NSPStartup is called.
	
	if( InterlockedDecrement( &gRefCount ) != 0 )
	{
		goto exit;
	}
	
	// Stop any outstanding queries.
	
	if( gLockInitialized )
	{
		NSPLock();
	}
	while( gQueryList )
	{
		check_string( gQueryList->refCount == 1, "NSPCleanup with outstanding queries!" );
		QueryRelease( gQueryList );
	}
	if( gLockInitialized )
	{
		NSPUnlock();
	}
	
	if( gLockInitialized )
	{
		gLockInitialized = false;
		DeleteCriticalSection( &gLock );
	}

	if( gIPHelperLibraryInstance )
	{
		BOOL ok;
				
		ok = FreeLibrary( gIPHelperLibraryInstance );
		check_translated_errno( ok, GetLastError(), kUnknownErr );
		gIPHelperLibraryInstance = NULL;
	}
	
exit:
	dlog( kDebugLevelTrace, "%s end   (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	return( NO_ERROR );
}

//===========================================================================================================================
//	NSPLookupServiceBegin
//
//	This function maps to the WinSock WSALookupServiceBegin function. It starts the lookup process and returns a HANDLE 
//	that can be used in subsequent operations. Subsequent calls only need to refer to this query by the handle as 
//	opposed to specifying the query parameters each time.
//===========================================================================================================================

DEBUG_LOCAL int WSPAPI
	NSPLookupServiceBegin(
		LPGUID					inProviderID,
		LPWSAQUERYSETW			inQuerySet,
		LPWSASERVICECLASSINFOW	inServiceClassInfo,
		DWORD					inFlags,   
		LPHANDLE				outLookup )
{
	OSStatus		err;
	QueryRef		obj;
	LPCWSTR			name;
	size_t			size;
	LPCWSTR			p;
	DWORD           type;
	DWORD			n;
	DWORD			i;
	INT				family;
	INT				protocol;
	
	DEBUG_UNUSED( inProviderID );
	DEBUG_UNUSED( inServiceClassInfo );
	
	dlog( kDebugLevelTrace, "%s begin (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	
	obj = NULL;
	require_action( inQuerySet, exit, err = WSAEINVAL );
	name = inQuerySet->lpszServiceInstanceName;
	require_action_quiet( name, exit, err = WSAEINVAL );
	require_action( outLookup, exit, err = WSAEINVAL );
	
	dlog( kDebugLevelTrace, "%s (flags=0x%08X, name=\"%S\")\n", __ROUTINE__, inFlags, name );
	dlog_query_set( kDebugLevelVerbose, inQuerySet );
	
	// Check if we can handle this type of request and if we support any of the protocols being requested.
	// We only support the DNS namespace, TCP and UDP protocols, and IPv4. Only blob results are supported.
	
	require_action_quiet( inFlags & (LUP_RETURN_ADDR|LUP_RETURN_BLOB), exit, err = WSASERVICE_NOT_FOUND );
	
	type = inQuerySet->dwNameSpace;
	require_action_quiet( ( type == NS_DNS ) || ( type == NS_ALL ), exit, err = WSASERVICE_NOT_FOUND );
	
	n = inQuerySet->dwNumberOfProtocols;
	if( n > 0 )
	{
		require_action( inQuerySet->lpafpProtocols, exit, err = WSAEINVAL );
		for( i = 0; i < n; ++i )
		{
			family = inQuerySet->lpafpProtocols[ i ].iAddressFamily;
			protocol = inQuerySet->lpafpProtocols[ i ].iProtocol;
			if( ( family == AF_INET ) && ( ( protocol == IPPROTO_UDP ) || ( protocol == IPPROTO_TCP ) ) )
			{
				break;
			}
		}
		require_action_quiet( i < n, exit, err = WSASERVICE_NOT_FOUND );
	}
	
	// Check if the name ends in ".local" and if not, exit with an error since we only resolve .local names.
	// The name may or may not end with a "." (fully qualified) so handle both cases. DNS is also case 
	// insensitive the check for .local has to be case insensitive (.LoCaL is equivalent to .local). This
	// manually does the wchar_t strlen and stricmp to avoid needing any special wchar_t versions of the 
	// libraries. It is probably faster to do the inline compare than invoke functions to do it anyway.
	
	for( p = name; *p; ++p ) {}		// Find end of string
	size = (size_t)( p - name );
	require_action_quiet( size > sizeof_string( ".local" ), exit, err = WSASERVICE_NOT_FOUND );
	
	p = name + ( size - 1 );
	p = ( *p == '.' ) ? ( p - sizeof_string( ".local" ) ) : ( ( p - sizeof_string( ".local" ) ) + 1 );
	if	( ( ( p[ 0 ] != '.' )						||
		( ( p[ 1 ] != 'L' ) && ( p[ 1 ] != 'l' ) )	||
		( ( p[ 2 ] != 'O' ) && ( p[ 2 ] != 'o' ) )	||
		( ( p[ 3 ] != 'C' ) && ( p[ 3 ] != 'c' ) )	||
		( ( p[ 4 ] != 'A' ) && ( p[ 4 ] != 'a' ) )	||
		( ( p[ 5 ] != 'L' ) && ( p[ 5 ] != 'l' ) ) ) )
	{
#ifdef ENABLE_REVERSE_LOOKUP

		err = IsReverseLookup( name, size );

#else

		err = WSASERVICE_NOT_FOUND;

#endif

		require_noerr( err, exit );
	}
	else
	{
		const char	*	replyDomain;
		char			translated[ kDNSServiceMaxDomainName ];
		int				n;
		int				labels		= 0;
		const char	*	label[MAX_LABELS];
		char			text[64];

		n = WideCharToMultiByte( CP_UTF8, 0, name, -1, translated, sizeof( translated ), NULL, NULL );
		require_action( n > 0, exit, err = WSASERVICE_NOT_FOUND );

		// <rdar://problem/4050633>

		// Don't resolve multi-label name

		// <rdar://problem/5914160> Eliminate use of GetNextLabel in mdnsNSP
		// Add checks for GetNextLabel returning NULL, individual labels being greater than
		// 64 bytes, and the number of labels being greater than MAX_LABELS
		replyDomain = translated;

		while (replyDomain && *replyDomain && labels < MAX_LABELS)
		{
			label[labels++]	= replyDomain;
			replyDomain		= GetNextLabel(replyDomain, text);
		}

		require_action( labels == 2, exit, err = WSASERVICE_NOT_FOUND );

		// <rdar://problem/3936771>
		//
		// Check to see if the name of this host is in the hosts table. If so,
		// don't try and resolve it
		
		require_action( InHostsTable( translated ) == FALSE, exit, err = WSASERVICE_NOT_FOUND );
	}

	// The name ends in .local ( and isn't in the hosts table ), .0.8.e.f.ip6.arpa, or .254.169.in-addr.arpa so start the resolve operation. Lazy initialize DNS-SD if needed.
		
	NSPLock();
	
	err = QueryCreate( inQuerySet, inFlags, &obj );
	NSPUnlock();
	require_noerr( err, exit );
	
	*outLookup = (HANDLE) obj;
	
exit:
	dlog( kDebugLevelTrace, "%s end   (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	if( err != NO_ERROR )
	{
		SetLastError( (DWORD) err );
		return( SOCKET_ERROR );
	}
	return( NO_ERROR );
}

//===========================================================================================================================
//	NSPLookupServiceNext
//
//	This function maps to the Winsock call WSALookupServiceNext. This routine takes a handle to a previously defined 
//	query and attempts to locate a service matching the criteria defined by the query. If so, that instance is returned 
//	in the lpqsResults parameter.
//===========================================================================================================================

DEBUG_LOCAL int WSPAPI
	NSPLookupServiceNext(  
		HANDLE			inLookup,
		DWORD			inFlags,
		LPDWORD			ioSize,
		LPWSAQUERYSETW	outResults )
{
	BOOL			data4;
	BOOL			data6;
	OSStatus		err;
	QueryRef		obj;
	DWORD			waitResult;
	size_t			size;
	
	DEBUG_USE_ONLY( inFlags );
	
	dlog( kDebugLevelTrace, "%s begin (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	
	data4 = FALSE;
	data6 = FALSE;
	obj = NULL;
	NSPLock();
	err = QueryRetain( (QueryRef) inLookup );
	require_noerr( err, exit );
	obj = (QueryRef) inLookup;
	require_action( ioSize, exit, err = WSAEINVAL );
	require_action( outResults, exit, err = WSAEINVAL );
	
	dlog( kDebugLevelTrace, "%s (lookup=%#p, flags=0x%08X, *ioSize=%d)\n", __ROUTINE__, inLookup, inFlags, *ioSize );
	
	// Wait for data or a cancel. Release the lock while waiting. This is safe because we've retained the query.

	NSPUnlock();
	waitResult = WaitForMultipleObjects( obj->waitCount, obj->waitHandles, FALSE, 2 * 1000 );
	NSPLock();
	require_action_quiet( waitResult != ( WAIT_OBJECT_0 ), exit, err = WSA_E_CANCELLED );
	err = translate_errno( ( waitResult == WAIT_OBJECT_0 + 1 ) || ( waitResult == WAIT_OBJECT_0 + 2 ), (OSStatus) GetLastError(), WSASERVICE_NOT_FOUND );
	require_noerr_quiet( err, exit );

	// If we've received an IPv4 reply, then hang out briefly for an IPv6 reply

	if ( waitResult == WAIT_OBJECT_0 + 1 )
	{
		data4 = TRUE;
		data6 = WaitForSingleObject( obj->data6Event, 100 ) == WAIT_OBJECT_0 ? TRUE : FALSE;
	}

	// Else we've received an IPv6 reply, so hang out briefly for an IPv4 reply

	else if ( waitResult == WAIT_OBJECT_0 + 2 )
	{
		data4 = WaitForSingleObject( obj->data4Event, 100 ) == WAIT_OBJECT_0 ? TRUE : FALSE;
		data6 = TRUE;
	}

	if ( data4 )
	{
		__try
		{
			err = DNSServiceProcessResult(obj->resolver4);
		}
		__except( EXCEPTION_EXECUTE_HANDLER )
		{
			err = kUnknownErr;
		}

		require_noerr( err, exit );
	}

	if ( data6 )
	{
		__try
		{
			err = DNSServiceProcessResult( obj->resolver6 );
		}
		__except( EXCEPTION_EXECUTE_HANDLER )
		{
			err = kUnknownErr;
		}

		require_noerr( err, exit );
	}

	require_action_quiet( obj->addr4Valid || obj->addr6Valid, exit, err = WSA_E_NO_MORE );

	// Copy the externalized query results to the callers buffer (if it fits).
	
	size = QueryCopyQuerySetSize( obj, obj->querySet, obj->querySetFlags );
	require_action( size <= (size_t) *ioSize, exit, err = WSAEFAULT );
	
	QueryCopyQuerySetTo( obj, obj->querySet, obj->querySetFlags, outResults );
	outResults->dwOutputFlags = RESULT_IS_ADDED;
	obj->addr4Valid = false;
	obj->addr6Valid = false;

exit:
	if( obj )
	{
		QueryRelease( obj );
	}
	NSPUnlock();
	dlog( kDebugLevelTrace, "%s end   (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	if( err != NO_ERROR )
	{
		SetLastError( (DWORD) err );
		return( SOCKET_ERROR );
	}
	return( NO_ERROR );
}

//===========================================================================================================================
//	NSPLookupServiceEnd
//
//	This function maps to the Winsock call WSALookupServiceEnd. Once the user process has finished is query (usually 
//	indicated when WSALookupServiceNext returns the error WSA_E_NO_MORE) a call to this function is made to release any 
//	allocated resources associated with the query.
//===========================================================================================================================

DEBUG_LOCAL int WSPAPI	NSPLookupServiceEnd( HANDLE inLookup )
{
	OSStatus		err;

	dlog( kDebugLevelTrace, "%s begin (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	
	dlog( kDebugLevelTrace, "%s (lookup=%#p)\n", __ROUTINE__, inLookup );
	
	NSPLock();
	err = QueryRelease( (QueryRef) inLookup );
	NSPUnlock();
	require_noerr( err, exit );
	
exit:
	dlog( kDebugLevelTrace, "%s end   (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	if( err != NO_ERROR )
	{
		SetLastError( (DWORD) err );
		return( SOCKET_ERROR );
	}
	return( NO_ERROR );
}

//===========================================================================================================================
//	NSPSetService
//
//	This function maps to the Winsock call WSASetService. This routine is called when the user wants to register or 
//	deregister an instance of a server with our service. For registration, the user needs to associate the server with a 
//	service class. For deregistration the service class is required along with the servicename. The inRegInfo parameter 
//	contains a WSAQUERYSET structure defining the server (such as protocol and address where it is).
//===========================================================================================================================

DEBUG_LOCAL int WSPAPI
	NSPSetService(
		LPGUID					inProviderID,						
		LPWSASERVICECLASSINFOW	inServiceClassInfo,   
		LPWSAQUERYSETW			inRegInfo,				  
		WSAESETSERVICEOP		inOperation,			   
		DWORD					inFlags )
{
	DEBUG_UNUSED( inProviderID );
	DEBUG_UNUSED( inServiceClassInfo );
	DEBUG_UNUSED( inRegInfo );
	DEBUG_UNUSED( inOperation );
	DEBUG_UNUSED( inFlags );
	
	dlog( kDebugLevelTrace, "%s begin (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	dlog( kDebugLevelTrace, "%s\n", __ROUTINE__ );
	
	// We don't allow services to be registered so always return an error.
	
	dlog( kDebugLevelTrace, "%s end   (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	return( WSAEINVAL );
}

//===========================================================================================================================
//	NSPInstallServiceClass
//
//	This function maps to the Winsock call WSAInstallServiceClass. This routine is used to install a service class which 
//	is used to define certain characteristics for a group of services. After a service class is registered, an actual
//	instance of a server may be registered.
//===========================================================================================================================

DEBUG_LOCAL int WSPAPI	NSPInstallServiceClass( LPGUID inProviderID, LPWSASERVICECLASSINFOW inServiceClassInfo )
{
	DEBUG_UNUSED( inProviderID );
	DEBUG_UNUSED( inServiceClassInfo );
	
	dlog( kDebugLevelTrace, "%s begin (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	dlog( kDebugLevelTrace, "%s\n", __ROUTINE__ );
	
	// We don't allow service classes to be installed so always return an error.

	dlog( kDebugLevelTrace, "%s end   (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	return( WSA_INVALID_PARAMETER );
}

//===========================================================================================================================
//	NSPRemoveServiceClass
//
//	This function maps to the Winsock call WSARemoveServiceClass. This routine removes a previously registered service 
//	class. This is accomplished by connecting to the namespace service and writing the GUID which defines the given 
//	service class.
//===========================================================================================================================

DEBUG_LOCAL int WSPAPI	NSPRemoveServiceClass( LPGUID inProviderID, LPGUID inServiceClassID )
{
	DEBUG_UNUSED( inProviderID );
	DEBUG_UNUSED( inServiceClassID );
	
	dlog( kDebugLevelTrace, "%s begin (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	dlog( kDebugLevelTrace, "%s\n", __ROUTINE__ );
	
	// We don't allow service classes to be installed so always return an error.
	
	dlog( kDebugLevelTrace, "%s end   (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	return( WSATYPE_NOT_FOUND );
}

//===========================================================================================================================
//	NSPGetServiceClassInfo
//
//	This function maps to the Winsock call WSAGetServiceClassInfo. This routine returns the information associated with 
//	a given service class.
//===========================================================================================================================

DEBUG_LOCAL int WSPAPI	NSPGetServiceClassInfo(	LPGUID inProviderID, LPDWORD ioSize, LPWSASERVICECLASSINFOW ioServiceClassInfo )
{
	DEBUG_UNUSED( inProviderID );
	DEBUG_UNUSED( ioSize );
	DEBUG_UNUSED( ioServiceClassInfo );
	
	dlog( kDebugLevelTrace, "%s begin (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	dlog( kDebugLevelTrace, "%s\n", __ROUTINE__ );
	
	// We don't allow service classes to be installed so always return an error.
	
	dlog( kDebugLevelTrace, "%s end   (ticks=%d)\n", __ROUTINE__, GetTickCount() );
	return( WSATYPE_NOT_FOUND );
}

#if 0
#pragma mark -
#endif

//===========================================================================================================================
//	QueryCreate
//
//	Warning: Assumes the NSP lock is held.
//===========================================================================================================================

DEBUG_LOCAL OSStatus	QueryCreate( const WSAQUERYSETW *inQuerySet, DWORD inQuerySetFlags, QueryRef *outRef )
{
	OSStatus		err;
	QueryRef		obj;
	char			name[ kDNSServiceMaxDomainName ];
	int				n;
	QueryRef *		p;
	SOCKET			s4;
	SOCKET			s6;

	obj = NULL;
	check( inQuerySet );
	check( inQuerySet->lpszServiceInstanceName );
	check( outRef );
	
	// Convert the wchar_t name to UTF-8.
	
	n = WideCharToMultiByte( CP_UTF8, 0, inQuerySet->lpszServiceInstanceName, -1, name, sizeof( name ), NULL, NULL );
	err = translate_errno( n > 0, (OSStatus) GetLastError(), WSAEINVAL );
	require_noerr( err, exit );
	
	// Allocate the object and append it to the list. Append immediately so releases of partial objects work.
	
	obj = (QueryRef) calloc( 1, sizeof( *obj ) );
	require_action( obj, exit, err = WSA_NOT_ENOUGH_MEMORY );
	
	obj->refCount = 1;
	
	for( p = &gQueryList; *p; p = &( *p )->next ) {}	// Find the end of the list.
	*p = obj;
	
	// Set up cancel event

	obj->cancelEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
	require_action( obj->cancelEvent, exit, err = WSA_NOT_ENOUGH_MEMORY );

	// Set up events to signal when A record data is ready
	
	obj->data4Event = CreateEvent( NULL, TRUE, FALSE, NULL );
	require_action( obj->data4Event, exit, err = WSA_NOT_ENOUGH_MEMORY );
	
	// Start the query.  Handle delay loaded DLL errors.

	__try
	{
		err = DNSServiceQueryRecord( &obj->resolver4, 0, 0, name, kDNSServiceType_A, kDNSServiceClass_IN, QueryRecordCallback4, obj );
	}
	__except( EXCEPTION_EXECUTE_HANDLER )
	{
		err = kUnknownErr;
	}

	require_noerr( err, exit );

	// Attach the socket to the event

	__try
	{
		s4 = DNSServiceRefSockFD(obj->resolver4);
	}
	__except( EXCEPTION_EXECUTE_HANDLER )
	{
		s4 = INVALID_SOCKET;
	}

	err = translate_errno( s4 != INVALID_SOCKET, errno_compat(), kUnknownErr );
	require_noerr( err, exit );

	WSAEventSelect(s4, obj->data4Event, FD_READ|FD_CLOSE);
	
	// Set up events to signal when AAAA record data is ready
	
	obj->data6Event = CreateEvent( NULL, TRUE, FALSE, NULL );
	require_action( obj->data6Event, exit, err = WSA_NOT_ENOUGH_MEMORY );
	
	// Start the query.  Handle delay loaded DLL errors.

	__try
	{
		err = DNSServiceQueryRecord( &obj->resolver6, 0, 0, name, kDNSServiceType_AAAA, kDNSServiceClass_IN, QueryRecordCallback6, obj );
	}
	__except( EXCEPTION_EXECUTE_HANDLER )
	{
		err = kUnknownErr;
	}

	require_noerr( err, exit );

	// Attach the socket to the event

	__try
	{
		s6 = DNSServiceRefSockFD(obj->resolver6);
	}
	__except( EXCEPTION_EXECUTE_HANDLER )
	{
		s6 = INVALID_SOCKET;
	}

	err = translate_errno( s6 != INVALID_SOCKET, errno_compat(), kUnknownErr );
	require_noerr( err, exit );

	WSAEventSelect(s6, obj->data6Event, FD_READ|FD_CLOSE);

	obj->waitCount = 0;
	obj->waitHandles[ obj->waitCount++ ] = obj->cancelEvent;
	obj->waitHandles[ obj->waitCount++ ] = obj->data4Event;
	obj->waitHandles[ obj->waitCount++ ] = obj->data6Event;
	
	check( obj->waitCount == sizeof_array( obj->waitHandles ) );
	
	// Copy the QuerySet so it can be returned later.
	
	obj->querySetFlags = inQuerySetFlags;
	inQuerySetFlags = ( inQuerySetFlags & ~( LUP_RETURN_ADDR | LUP_RETURN_BLOB ) ) | LUP_RETURN_NAME;
	err = QueryCopyQuerySet( obj, inQuerySet, inQuerySetFlags, &obj->querySet, &obj->querySetSize );
	require_noerr( err, exit );
	
	// Success!
	
	*outRef	= obj;
	obj 	= NULL;
	err 	= NO_ERROR;

exit:
	if( obj )
	{
		QueryRelease( obj );
	}
	return( err );
}

//===========================================================================================================================
//	QueryRetain
//
//	Warning: Assumes the NSP lock is held.
//===========================================================================================================================

DEBUG_LOCAL OSStatus	QueryRetain( QueryRef inRef )
{
	OSStatus		err;
	QueryRef		obj;
	
	for( obj = gQueryList; obj; obj = obj->next )
	{
		if( obj == inRef )
		{
			break;
		}
	}
	require_action( obj, exit, err = WSA_INVALID_HANDLE );
	
	++inRef->refCount;
	err = NO_ERROR;
	
exit:
	return( err );
}

//===========================================================================================================================
//	QueryRelease
//
//	Warning: Assumes the NSP lock is held.
//===========================================================================================================================

DEBUG_LOCAL OSStatus	QueryRelease( QueryRef inRef )
{
	OSStatus		err;
	QueryRef *		p;
	BOOL			ok;
		
	// Find the item in the list.
	
	for( p = &gQueryList; *p; p = &( *p )->next )
	{
		if( *p == inRef )
		{
			break;
		}
	}
	require_action( *p, exit, err = WSA_INVALID_HANDLE );
	
	// Signal a cancel to unblock any threads waiting for results.
	
	if( inRef->cancelEvent )
	{
		ok = SetEvent( inRef->cancelEvent );
		check_translated_errno( ok, GetLastError(), WSAEINVAL );
	}
	
	// Stop the query.
	
	if( inRef->resolver4 )
	{
		__try
		{
			DNSServiceRefDeallocate( inRef->resolver4 );
		}
		__except( EXCEPTION_EXECUTE_HANDLER )
		{
		}
		
		inRef->resolver4 = NULL;
	}

	if ( inRef->resolver6 )
	{
		__try
		{
			DNSServiceRefDeallocate( inRef->resolver6 );
		}
		__except( EXCEPTION_EXECUTE_HANDLER )
		{
		}

		inRef->resolver6 = NULL;
	}
	
	// Decrement the refCount. Fully release if it drops to 0. If still referenced, just exit.
	
	if( --inRef->refCount != 0 )
	{
		err = NO_ERROR;
		goto exit;
	}
	*p = inRef->next;
	
	// Release resources.
	
	if( inRef->cancelEvent )
	{
		ok = CloseHandle( inRef->cancelEvent );
		check_translated_errno( ok, GetLastError(), WSAEINVAL );
	}
	if( inRef->data4Event )
	{
		ok = CloseHandle( inRef->data4Event );
		check_translated_errno( ok, GetLastError(), WSAEINVAL );
	}
	if( inRef->data6Event )
	{
		ok = CloseHandle( inRef->data6Event );
		check_translated_errno( ok, GetLastError(), WSAEINVAL );
	}
	if( inRef->querySet )
	{
		free( inRef->querySet );
	}
	free( inRef );
	err = NO_ERROR;
	
exit:
	return( err );
}

//===========================================================================================================================
//	QueryRecordCallback4
//===========================================================================================================================

DEBUG_LOCAL void CALLBACK_COMPAT
	QueryRecordCallback4(
		DNSServiceRef		inRef,
		DNSServiceFlags		inFlags,
		uint32_t			inInterfaceIndex,
		DNSServiceErrorType	inErrorCode,
		const char *		inName,    
		uint16_t			inRRType,
		uint16_t			inRRClass,
		uint16_t			inRDataSize,
		const void *		inRData,
		uint32_t			inTTL,
		void *				inContext )
{
	QueryRef			obj;
	const char *		src;
	char *				dst;
	BOOL				ok;
	
	DEBUG_UNUSED( inFlags );
	DEBUG_UNUSED( inInterfaceIndex );
	DEBUG_UNUSED( inTTL );

	NSPLock();
	obj = (QueryRef) inContext;
	check( obj );
	require_noerr( inErrorCode, exit );
	require_quiet( inFlags & kDNSServiceFlagsAdd, exit );
	require( inRRClass   == kDNSServiceClass_IN, exit );
	require( inRRType    == kDNSServiceType_A, exit );
	require( inRDataSize == 4, exit );
	
	dlog( kDebugLevelTrace, "%s (flags=0x%08X, name=%s, rrType=%d, rDataSize=%d)\n", 
		__ROUTINE__, inFlags, inName, inRRType, inRDataSize );
		
	// Copy the name if needed.
	
	if( obj->name[ 0 ] == '\0' )
	{
		src = inName;
		dst = obj->name;
		while( *src != '\0' )
		{
			*dst++ = *src++;
		}
		*dst = '\0';
		obj->nameSize = (size_t)( dst - obj->name );
		check( obj->nameSize < sizeof( obj->name ) );
	}
	
	// Copy the data.
	
	memcpy( &obj->addr4, inRData, inRDataSize );
	obj->addr4Valid = true;
	obj->numValidAddrs++;
	
	// Signal that a result is ready.
	
	check( obj->data4Event );
	ok = SetEvent( obj->data4Event );
	check_translated_errno( ok, GetLastError(), WSAEINVAL );
	
	// Stop the resolver after the first response.
	
	__try
	{
		DNSServiceRefDeallocate( inRef );
	}
	__except( EXCEPTION_EXECUTE_HANDLER )
	{
	}

	obj->resolver4 = NULL;

exit:
	NSPUnlock();
}

#if 0
#pragma mark -
#endif


//===========================================================================================================================
//	QueryRecordCallback6
//===========================================================================================================================

DEBUG_LOCAL void CALLBACK_COMPAT
	QueryRecordCallback6(
		DNSServiceRef		inRef,
		DNSServiceFlags		inFlags,
		uint32_t			inInterfaceIndex,
		DNSServiceErrorType	inErrorCode,
		const char *		inName,    
		uint16_t			inRRType,
		uint16_t			inRRClass,
		uint16_t			inRDataSize,
		const void *		inRData,
		uint32_t			inTTL,
		void *				inContext )
{
	QueryRef			obj;
	const char *		src;
	char *				dst;
	BOOL				ok;
	
	DEBUG_UNUSED( inFlags );
	DEBUG_UNUSED( inInterfaceIndex );
	DEBUG_UNUSED( inTTL );

	NSPLock();
	obj = (QueryRef) inContext;
	check( obj );
	require_noerr( inErrorCode, exit );
	require_quiet( inFlags & kDNSServiceFlagsAdd, exit );
	require( inRRClass   == kDNSServiceClass_IN, exit );
	require( inRRType    == kDNSServiceType_AAAA, exit );
	require( inRDataSize == 16, exit );
	
	dlog( kDebugLevelTrace, "%s (flags=0x%08X, name=%s, rrType=%d, rDataSize=%d)\n", 
		__ROUTINE__, inFlags, inName, inRRType, inRDataSize );

	// Copy the name if needed.
	
	if( obj->name[ 0 ] == '\0' )
	{
		src = inName;
		dst = obj->name;
		while( *src != '\0' )
		{
			*dst++ = *src++;
		}
		*dst = '\0';
		obj->nameSize = (size_t)( dst - obj->name );
		check( obj->nameSize < sizeof( obj->name ) );
	}
	
	// Copy the data.
	
	memcpy( &obj->addr6, inRData, inRDataSize );

	obj->addr6ScopeId = GetScopeId( inInterfaceIndex );
	require( obj->addr6ScopeId, exit );
	obj->addr6Valid	  = true;
	obj->numValidAddrs++;

	// Signal that we're done
	
	check( obj->data6Event );
	ok = SetEvent( obj->data6Event );
	check_translated_errno( ok, GetLastError(), WSAEINVAL );

	// Stop the resolver after the first response.
	
	__try
	{
		DNSServiceRefDeallocate( inRef );
	}
	__except( EXCEPTION_EXECUTE_HANDLER )
	{
	}

	obj->resolver6 = NULL;

exit:

	
	
	NSPUnlock();
}


//===========================================================================================================================
//	QueryCopyQuerySet
//
//	Warning: Assumes the NSP lock is held.
//===========================================================================================================================

DEBUG_LOCAL OSStatus
	QueryCopyQuerySet( 
		QueryRef 				inRef, 
		const WSAQUERYSETW *	inQuerySet, 
		DWORD 					inQuerySetFlags, 
		WSAQUERYSETW **			outQuerySet, 
		size_t *				outSize )
{
	OSStatus			err;
	size_t				size;
	WSAQUERYSETW *		qs;
	
	check( inQuerySet );
	check( outQuerySet );
	
	size  = QueryCopyQuerySetSize( inRef, inQuerySet, inQuerySetFlags );
	qs = (WSAQUERYSETW *) calloc( 1, size );
	require_action( qs, exit, err = WSA_NOT_ENOUGH_MEMORY  );
	
	QueryCopyQuerySetTo( inRef, inQuerySet, inQuerySetFlags, qs );
	
	*outQuerySet = qs;
	if( outSize )
	{
		*outSize = size;
	}
	qs = NULL;
	err = NO_ERROR;
	
exit:
	if( qs )
	{
		free( qs );
	}
	return( err );	
}



//===========================================================================================================================
//	QueryCopyQuerySetTo
//
//	Warning: Assumes the NSP lock is held.
//===========================================================================================================================

DEBUG_LOCAL void
	QueryCopyQuerySetTo( 
		QueryRef 				inRef, 
		const WSAQUERYSETW *	inQuerySet, 
		DWORD 					inQuerySetFlags, 
		WSAQUERYSETW *			outQuerySet )
{
	uint8_t *		dst;
	LPCWSTR			s;
	LPWSTR			q;
	DWORD			n;
	DWORD			i;
	
#if( DEBUG )
	size_t			debugSize;
	
	debugSize = QueryCopyQuerySetSize( inRef, inQuerySet, inQuerySetFlags );
#endif

	check( inQuerySet );
	check( outQuerySet );

	dst = (uint8_t *) outQuerySet;
	
	// Copy the static portion of the results.
	
	*outQuerySet = *inQuerySet;
	dst += sizeof( *inQuerySet );
	
	if( inQuerySetFlags & LUP_RETURN_NAME )
	{
		s = inQuerySet->lpszServiceInstanceName;
		if( s )
		{
			outQuerySet->lpszServiceInstanceName = (LPWSTR) dst;
			q = (LPWSTR) dst;
			while( ( *q++ = *s++ ) != 0 ) {}
			dst = (uint8_t *) q;
		}
	}
	else
	{
		outQuerySet->lpszServiceInstanceName = NULL;
	}
	
	if( inQuerySet->lpServiceClassId )
	{
		outQuerySet->lpServiceClassId  = (LPGUID) dst;
		*outQuerySet->lpServiceClassId = *inQuerySet->lpServiceClassId;
		dst += sizeof( *inQuerySet->lpServiceClassId );
	}
	
	if( inQuerySet->lpVersion )
	{
		outQuerySet->lpVersion  = (LPWSAVERSION) dst;
		*outQuerySet->lpVersion = *inQuerySet->lpVersion;
		dst += sizeof( *inQuerySet->lpVersion );
	}
	
	s = inQuerySet->lpszComment;
	if( s )
	{
		outQuerySet->lpszComment = (LPWSTR) dst;
		q = (LPWSTR) dst;
		while( ( *q++ = *s++ ) != 0 ) {}
		dst = (uint8_t *) q;
	}
	
	if( inQuerySet->lpNSProviderId )
	{
		outQuerySet->lpNSProviderId  = (LPGUID) dst;
		*outQuerySet->lpNSProviderId = *inQuerySet->lpNSProviderId;
		dst += sizeof( *inQuerySet->lpNSProviderId );
	}
	
	s = inQuerySet->lpszContext;
	if( s )
	{
		outQuerySet->lpszContext = (LPWSTR) dst;
		q = (LPWSTR) dst;
		while( ( *q++ = *s++ ) != 0 ) {}
		dst = (uint8_t *) q;
	}
		
	n = inQuerySet->dwNumberOfProtocols;

	if( n > 0 )
	{
		check( inQuerySet->lpafpProtocols );
		
		outQuerySet->lpafpProtocols = (LPAFPROTOCOLS) dst;
		for( i = 0; i < n; ++i )
		{
			outQuerySet->lpafpProtocols[ i ] = inQuerySet->lpafpProtocols[ i ];
			dst += sizeof( *inQuerySet->lpafpProtocols );
		}
	}
		
	s = inQuerySet->lpszQueryString;
	if( s )
	{
		outQuerySet->lpszQueryString = (LPWSTR) dst;
		q = (LPWSTR) dst;
		while( ( *q++ = *s++ ) != 0 ) {}
		dst = (uint8_t *) q;
	}
	
	// Copy the address(es).
	
	if( ( inQuerySetFlags & LUP_RETURN_ADDR ) && ( inRef->numValidAddrs > 0 ) )
	{
		struct sockaddr_in	*	addr4;
		struct sockaddr_in6	*	addr6;
		int						index;
		
		outQuerySet->dwNumberOfCsAddrs	= inRef->numValidAddrs;
		outQuerySet->lpcsaBuffer 		= (LPCSADDR_INFO) dst;
		dst 							+= ( sizeof( *outQuerySet->lpcsaBuffer ) ) * ( inRef->numValidAddrs ) ;
		index							= 0;
		
		if ( inRef->addr4Valid )
		{	
			outQuerySet->lpcsaBuffer[ index ].LocalAddr.lpSockaddr 			= NULL;
			outQuerySet->lpcsaBuffer[ index ].LocalAddr.iSockaddrLength		= 0;
		
			outQuerySet->lpcsaBuffer[ index ].RemoteAddr.lpSockaddr 		= (LPSOCKADDR) dst;
			outQuerySet->lpcsaBuffer[ index ].RemoteAddr.iSockaddrLength	= sizeof( struct sockaddr_in );
		
			addr4 															= (struct sockaddr_in *) dst;
			memset( addr4, 0, sizeof( *addr4 ) );
			addr4->sin_family												= AF_INET;
			memcpy( &addr4->sin_addr, &inRef->addr4, 4 );
			dst 															+= sizeof( *addr4 );
		
			outQuerySet->lpcsaBuffer[ index ].iSocketType 					= AF_INET;		// Emulate Tcpip NSP
			outQuerySet->lpcsaBuffer[ index ].iProtocol						= IPPROTO_UDP;	// Emulate Tcpip NSP

			index++;
		}

		if ( inRef->addr6Valid )
		{
			outQuerySet->lpcsaBuffer[ index ].LocalAddr.lpSockaddr 			= NULL;
			outQuerySet->lpcsaBuffer[ index ].LocalAddr.iSockaddrLength		= 0;
		
			outQuerySet->lpcsaBuffer[ index ].RemoteAddr.lpSockaddr 		= (LPSOCKADDR) dst;
			outQuerySet->lpcsaBuffer[ index ].RemoteAddr.iSockaddrLength	= sizeof( struct sockaddr_in6 );
		
			addr6 															= (struct sockaddr_in6 *) dst;
			memset( addr6, 0, sizeof( *addr6 ) );
			addr6->sin6_family												= AF_INET6;
			addr6->sin6_scope_id											= inRef->addr6ScopeId;
			memcpy( &addr6->sin6_addr, &inRef->addr6, 16 );
			dst 															+= sizeof( *addr6 );
		
			outQuerySet->lpcsaBuffer[ index ].iSocketType 					= AF_INET6;		// Emulate Tcpip NSP
			outQuerySet->lpcsaBuffer[ index ].iProtocol						= IPPROTO_UDP;	// Emulate Tcpip NSP
		}
	}
	else
	{
		outQuerySet->dwNumberOfCsAddrs	= 0;
		outQuerySet->lpcsaBuffer 		= NULL;
	}
	
	// Copy the hostent blob.
	
	if( ( inQuerySetFlags & LUP_RETURN_BLOB ) && inRef->addr4Valid )
	{
		uint8_t *				base;
		struct hostent *		he;
		uintptr_t *				p;

		outQuerySet->lpBlob	 = (LPBLOB) dst;
		dst 				+= sizeof( *outQuerySet->lpBlob );
		
		base = dst;
		he	 = (struct hostent *) dst;
		dst += sizeof( *he );
		
		he->h_name = (char *)( dst - base );
		memcpy( dst, inRef->name, inRef->nameSize + 1 );
		dst += ( inRef->nameSize + 1 );
		
		he->h_aliases 	= (char **)( dst - base );
		p	  			= (uintptr_t *) dst;
		*p++  			= 0;
		dst 		 	= (uint8_t *) p;
		
		he->h_addrtype 	= AF_INET;
		he->h_length	= 4;
		
		he->h_addr_list	= (char **)( dst - base );
		p	  			= (uintptr_t *) dst;
		dst 		   += ( 2 * sizeof( *p ) );
		*p++			= (uintptr_t)( dst - base );
		*p++			= 0;
		p	  			= (uintptr_t *) dst;
		*p++			= (uintptr_t) inRef->addr4;
		dst 		 	= (uint8_t *) p;
		
		outQuerySet->lpBlob->cbSize 	= (ULONG)( dst - base );
		outQuerySet->lpBlob->pBlobData	= (BYTE *) base;
	}
	dlog_query_set( kDebugLevelVerbose, outQuerySet );

	check( (size_t)( dst - ( (uint8_t *) outQuerySet ) ) == debugSize );
}

//===========================================================================================================================
//	QueryCopyQuerySetSize
//
//	Warning: Assumes the NSP lock is held.
//===========================================================================================================================

DEBUG_LOCAL size_t	QueryCopyQuerySetSize( QueryRef inRef, const WSAQUERYSETW *inQuerySet, DWORD inQuerySetFlags )
{
	size_t		size;
	LPCWSTR		s;
	LPCWSTR		p;
	
	check( inRef );
	check( inQuerySet );
	
	// Calculate the size of the static portion of the results.
	
	size = sizeof( *inQuerySet );
	
	if( inQuerySetFlags & LUP_RETURN_NAME )
	{
		s = inQuerySet->lpszServiceInstanceName;
		if( s )
		{
			for( p = s; *p; ++p ) {}
			size += (size_t)( ( ( p - s ) + 1 ) * sizeof( *p ) );
		}
	}
	
	if( inQuerySet->lpServiceClassId )
	{
		size += sizeof( *inQuerySet->lpServiceClassId );
	}
	
	if( inQuerySet->lpVersion )
	{
		size += sizeof( *inQuerySet->lpVersion );
	}
	
	s = inQuerySet->lpszComment;
	if( s )
	{
		for( p = s; *p; ++p ) {}
		size += (size_t)( ( ( p - s ) + 1 ) * sizeof( *p ) );
	}
	
	if( inQuerySet->lpNSProviderId )
	{
		size += sizeof( *inQuerySet->lpNSProviderId );
	}
	
	s = inQuerySet->lpszContext;
	if( s )
	{
		for( p = s; *p; ++p ) {}
		size += (size_t)( ( ( p - s ) + 1 ) * sizeof( *p ) );
	}
	
	size += ( inQuerySet->dwNumberOfProtocols * sizeof( *inQuerySet->lpafpProtocols ) );
	
	s = inQuerySet->lpszQueryString;
	if( s )
	{
		for( p = s; *p; ++p ) {}
		size += (size_t)( ( ( p - s ) + 1 ) * sizeof( *p ) );
	}
	
	// Calculate the size of the address(es).
	
	if( ( inQuerySetFlags & LUP_RETURN_ADDR ) && inRef->addr4Valid )
	{
		size += sizeof( *inQuerySet->lpcsaBuffer );
		size += sizeof( struct sockaddr_in );
	}

	if( ( inQuerySetFlags & LUP_RETURN_ADDR ) && inRef->addr6Valid )
	{
		size += sizeof( *inQuerySet->lpcsaBuffer );
		size += sizeof( struct sockaddr_in6 );
	}
	
	// Calculate the size of the hostent blob.
	
	if( ( inQuerySetFlags & LUP_RETURN_BLOB ) && inRef->addr4Valid )
	{
		size += sizeof( *inQuerySet->lpBlob );	// Blob ptr/size structure
		size += sizeof( struct hostent );		// Old-style hostent structure
		size += ( inRef->nameSize + 1 );		// Name and null terminator
		size += 4;								// Alias list terminator (0 offset)
		size += 4;								// Offset to address.
		size += 4;								// Address list terminator (0 offset)
		size += 4;								// IPv4 address
	}
	return( size );
}

#if 0
#pragma mark -
#endif

#if( DEBUG )
//===========================================================================================================================
//	DebugDumpQuerySet
//===========================================================================================================================

#define	DebugSocketFamilyToString( FAM )	( ( FAM ) == AF_INET )  ? "AF_INET"  : \
											( ( FAM ) == AF_INET6 ) ? "AF_INET6" : ""

#define	DebugSocketProtocolToString( PROTO )	( ( PROTO ) == IPPROTO_UDP ) ? "IPPROTO_UDP" : \
												( ( PROTO ) == IPPROTO_TCP ) ? "IPPROTO_TCP" : ""

#define	DebugNameSpaceToString( NS )			( ( NS ) == NS_DNS ) ? "NS_DNS" : ( ( NS ) == NS_ALL ) ? "NS_ALL" : ""

void	DebugDumpQuerySet( DebugLevel inLevel, const WSAQUERYSETW *inQuerySet )
{
	DWORD		i;
	
	check( inQuerySet );

	// Fixed portion of the QuerySet.
		
	dlog( inLevel, "QuerySet:\n" );
	dlog( inLevel, "    dwSize:                  %d (expected %d)\n", inQuerySet->dwSize, sizeof( *inQuerySet ) );
	if( inQuerySet->lpszServiceInstanceName )
	{
		dlog( inLevel, "    lpszServiceInstanceName: %S\n", inQuerySet->lpszServiceInstanceName );
	}
	else
	{
		dlog( inLevel, "    lpszServiceInstanceName: <null>\n" );
	}
	if( inQuerySet->lpServiceClassId )
	{
		dlog( inLevel, "    lpServiceClassId:        %U\n", inQuerySet->lpServiceClassId );
	}
	else
	{
		dlog( inLevel, "    lpServiceClassId:        <null>\n" );
	}
	if( inQuerySet->lpVersion )
	{
		dlog( inLevel, "    lpVersion:\n" );
		dlog( inLevel, "        dwVersion:               %d\n", inQuerySet->lpVersion->dwVersion );
		dlog( inLevel, "        dwVersion:               %d\n", inQuerySet->lpVersion->ecHow );
	}
	else
	{
		dlog( inLevel, "    lpVersion:               <null>\n" );
	}
	if( inQuerySet->lpszComment )
	{
		dlog( inLevel, "    lpszComment:             %S\n", inQuerySet->lpszComment );
	}
	else
	{
		dlog( inLevel, "    lpszComment:             <null>\n" );
	}
	dlog( inLevel, "    dwNameSpace:             %d %s\n", inQuerySet->dwNameSpace, 
		DebugNameSpaceToString( inQuerySet->dwNameSpace ) );
	if( inQuerySet->lpNSProviderId )
	{
		dlog( inLevel, "    lpNSProviderId:          %U\n", inQuerySet->lpNSProviderId );
	}
	else
	{
		dlog( inLevel, "    lpNSProviderId:          <null>\n" );
	}
	if( inQuerySet->lpszContext )
	{
		dlog( inLevel, "    lpszContext:             %S\n", inQuerySet->lpszContext );
	}
	else
	{
		dlog( inLevel, "    lpszContext:             <null>\n" );
	}
	dlog( inLevel, "    dwNumberOfProtocols:     %d\n", inQuerySet->dwNumberOfProtocols );
	dlog( inLevel, "    lpafpProtocols:          %s\n", inQuerySet->lpafpProtocols ? "" : "<null>" );
	for( i = 0; i < inQuerySet->dwNumberOfProtocols; ++i )
	{
		if( i != 0 )
		{
			dlog( inLevel, "\n" );
		}
		dlog( inLevel, "        iAddressFamily:          %d %s\n", inQuerySet->lpafpProtocols[ i ].iAddressFamily, 
			DebugSocketFamilyToString( inQuerySet->lpafpProtocols[ i ].iAddressFamily ) );
		dlog( inLevel, "        iProtocol:               %d %s\n", inQuerySet->lpafpProtocols[ i ].iProtocol, 
			DebugSocketProtocolToString( inQuerySet->lpafpProtocols[ i ].iProtocol ) );
	}
	if( inQuerySet->lpszQueryString )
	{
		dlog( inLevel, "    lpszQueryString:         %S\n", inQuerySet->lpszQueryString );
	}
	else
	{
		dlog( inLevel, "    lpszQueryString:         <null>\n" );
	}
	dlog( inLevel, "    dwNumberOfCsAddrs:       %d\n", inQuerySet->dwNumberOfCsAddrs );
	dlog( inLevel, "    lpcsaBuffer:             %s\n", inQuerySet->lpcsaBuffer ? "" : "<null>" );
	for( i = 0; i < inQuerySet->dwNumberOfCsAddrs; ++i )
	{
		if( i != 0 )
		{
			dlog( inLevel, "\n" );
		}
		if( inQuerySet->lpcsaBuffer[ i ].LocalAddr.lpSockaddr && 
			( inQuerySet->lpcsaBuffer[ i ].LocalAddr.iSockaddrLength > 0 ) )
		{
			dlog( inLevel, "        LocalAddr:               %##a\n", 
				inQuerySet->lpcsaBuffer[ i ].LocalAddr.lpSockaddr );
		}
		else
		{
			dlog( inLevel, "        LocalAddr:               <null/empty>\n" );
		}
		if( inQuerySet->lpcsaBuffer[ i ].RemoteAddr.lpSockaddr && 
			( inQuerySet->lpcsaBuffer[ i ].RemoteAddr.iSockaddrLength > 0 ) )
		{
			dlog( inLevel, "        RemoteAddr:              %##a\n", 
				inQuerySet->lpcsaBuffer[ i ].RemoteAddr.lpSockaddr );
		}
		else
		{
			dlog( inLevel, "        RemoteAddr:              <null/empty>\n" );
		}
		dlog( inLevel, "        iSocketType:             %d\n", inQuerySet->lpcsaBuffer[ i ].iSocketType );
		dlog( inLevel, "        iProtocol:               %d\n", inQuerySet->lpcsaBuffer[ i ].iProtocol );
	}
	dlog( inLevel, "    dwOutputFlags:           %d\n", inQuerySet->dwOutputFlags );
	
	// Blob portion of the QuerySet.
	
	if( inQuerySet->lpBlob )
	{
		dlog( inLevel, "    lpBlob:\n" );
		dlog( inLevel, "        cbSize:                  %ld\n", inQuerySet->lpBlob->cbSize );
		dlog( inLevel, "        pBlobData:               %#p\n", inQuerySet->lpBlob->pBlobData );
		dloghex( inLevel, 12, NULL, 0, 0, NULL, 0, 
			inQuerySet->lpBlob->pBlobData, inQuerySet->lpBlob->pBlobData, inQuerySet->lpBlob->cbSize, 
			kDebugFlagsNone, NULL, 0 );
	}
	else
	{
		dlog( inLevel, "    lpBlob:                  <null>\n" );
	}
}
#endif


//===========================================================================================================================
//	InHostsTable
//===========================================================================================================================

DEBUG_LOCAL BOOL
InHostsTable( const char * name )
{
	HostsFileInfo	*	node;
	BOOL				ret = FALSE;
	OSStatus			err;
	
	check( name );

	if ( gHostsFileInfo == NULL )
	{
		TCHAR				systemDirectory[MAX_PATH];
		TCHAR				hFileName[MAX_PATH];
		HostsFile		*	hFile;

		GetSystemDirectory( systemDirectory, sizeof( systemDirectory ) );
		sprintf( hFileName, "%s\\drivers\\etc\\hosts", systemDirectory );
		err = HostsFileOpen( &hFile, hFileName );
		require_noerr( err, exit );

		while ( HostsFileNext( hFile, &node ) == 0 )
		{
			if ( IsLocalName( node ) )
			{
				node->m_next = gHostsFileInfo;
				gHostsFileInfo = node;
			}
			else
			{
				HostsFileInfoFree( node );
			}
		}

		HostsFileClose( hFile );
	}

	for ( node = gHostsFileInfo; node; node = node->m_next )
	{
		if ( IsSameName( node, name ) )
		{
			ret = TRUE;
			break;
		}
	}

exit:

	return ret;
}


//===========================================================================================================================
//	IsLocalName
//===========================================================================================================================

DEBUG_LOCAL BOOL
IsLocalName( HostsFileInfo * node )
{
	BOOL ret = TRUE;

	check( node );

	if ( strstr( node->m_host.h_name, ".local" ) == NULL )
	{
		int i;

		for ( i = 0; node->m_host.h_aliases[i]; i++ )
		{
			if ( strstr( node->m_host.h_aliases[i], ".local" ) )
			{
				goto exit;
			}
		}

		ret = FALSE;
	}

exit:

	return ret;
}


//===========================================================================================================================
//	IsSameName
//===========================================================================================================================

DEBUG_LOCAL BOOL
IsSameName( HostsFileInfo * node, const char * name )
{
	BOOL ret = TRUE;

	check( node );
	check( name );

	if ( strcmp( node->m_host.h_name, name ) != 0 )
	{
		int i;

		for ( i = 0; node->m_host.h_aliases[i]; i++ )
		{
			if ( strcmp( node->m_host.h_aliases[i], name ) == 0 )
			{
				goto exit;
			}
		}

		ret = FALSE;
	}

exit:

	return ret;
}


//===========================================================================================================================
//	HostsFileOpen
//===========================================================================================================================

DEBUG_LOCAL OSStatus
HostsFileOpen( HostsFile ** self, const char * fname )
{
	OSStatus err = kNoErr;

	*self = (HostsFile*) malloc( sizeof( HostsFile ) );
	require_action( *self, exit, err = kNoMemoryErr );
	memset( *self, 0, sizeof( HostsFile ) );

	(*self)->m_bufferSize = BUFFER_INITIAL_SIZE;
	(*self)->m_buffer = (char*) malloc( (*self)->m_bufferSize );
	require_action( (*self)->m_buffer, exit, err = kNoMemoryErr );

	// check malloc

	(*self)->m_fp = fopen( fname, "r" );
	require_action( (*self)->m_fp, exit, err = kUnknownErr );

exit:

	if ( err && *self )
	{
		HostsFileClose( *self );
		*self = NULL;
	}
		
	return err;
}


//===========================================================================================================================
//	HostsFileClose
//===========================================================================================================================

DEBUG_LOCAL OSStatus
HostsFileClose( HostsFile * self )
{
	check( self );

	if ( self->m_buffer )
	{
		free( self->m_buffer );
		self->m_buffer = NULL;
	}

	if ( self->m_fp )
	{
		fclose( self->m_fp );
		self->m_fp = NULL;
	}

	free( self );

	return kNoErr;
} 


//===========================================================================================================================
//	HostsFileInfoFree
//===========================================================================================================================

DEBUG_LOCAL void
HostsFileInfoFree( HostsFileInfo * info )
{
	while ( info )
	{
		HostsFileInfo * next = info->m_next;

		if ( info->m_host.h_addr_list )
		{
			if ( info->m_host.h_addr_list[0] )
			{
				free( info->m_host.h_addr_list[0] );
				info->m_host.h_addr_list[0] = NULL;
			}

			free( info->m_host.h_addr_list );
			info->m_host.h_addr_list = NULL;
		}

		if ( info->m_host.h_aliases )
		{
			int i;

			for ( i = 0; info->m_host.h_aliases[i]; i++ )
			{
				free( info->m_host.h_aliases[i] );
			}

			free( info->m_host.h_aliases );
		}

		if ( info->m_host.h_name )
		{
			free( info->m_host.h_name );
			info->m_host.h_name = NULL;
		}
			
		free( info );

		info = next;
	}
}


//===========================================================================================================================
//	HostsFileNext
//===========================================================================================================================

DEBUG_LOCAL OSStatus
HostsFileNext( HostsFile * self, HostsFileInfo ** hInfo )
{
	struct sockaddr_in6	addr_6;
	struct sockaddr_in	addr_4;
	int					numAliases = ALIASES_INITIAL_SIZE;
	char			*	line;
	char			*	tok;
	int					dwSize;
	int					idx;
	int					i;
	short				family;
	OSStatus			err = kNoErr;

	check( self );
	check( self->m_fp );
	check( hInfo );

	idx	= 0;

	*hInfo = (HostsFileInfo*) malloc( sizeof( HostsFileInfo ) );
	require_action( *hInfo, exit, err = kNoMemoryErr );
	memset( *hInfo, 0, sizeof( HostsFileInfo ) );

	for ( ; ; )
	{
		line = fgets( self->m_buffer + idx, self->m_bufferSize - idx, self->m_fp );
		
		if ( line == NULL )
		{
			err = 1;
			goto exit;
		}

		// If there's no eol and no eof, then we didn't get the whole line

		if ( !strchr( line, '\n' ) && !feof( self->m_fp ) )
		{
			int			bufferSize;
			char	*	buffer;

			/* Try and allocate space for longer line */

			bufferSize	= self->m_bufferSize * 2;
			buffer		= (char*) realloc( self->m_buffer, bufferSize );
			require_action( buffer, exit, err = kNoMemoryErr );
			self->m_bufferSize	= bufferSize;
			self->m_buffer		= buffer;
			idx					= (int) strlen( self->m_buffer );

			continue;
		}

		line	= self->m_buffer;
		idx		= 0;

		if (*line == '#')
		{
			continue;
		}

		// Get rid of either comments or eol characters

		if (( tok = strpbrk(line, "#\n")) != NULL )
		{
			*tok = '\0';
		}

		// Make sure there is some whitespace on this line

		if (( tok = strpbrk(line, " \t")) == NULL )
		{
			continue;
		}

		// Create two strings, where p == the IP Address and tok is the name list

		*tok++ = '\0';

		while ( *tok == ' ' || *tok == '\t')
		{
			tok++;
		}

		// Now we have the name

		(*hInfo)->m_host.h_name = (char*) malloc( strlen( tok ) + 1 );
		require_action( (*hInfo)->m_host.h_name, exit, err = kNoMemoryErr );
		strcpy( (*hInfo)->m_host.h_name, tok );

		// Now create the address (IPv6/IPv4)

		addr_6.sin6_family	= family = AF_INET6;
		dwSize				= sizeof( addr_6 );

		if ( WSAStringToAddress( line, AF_INET6, NULL, ( struct sockaddr*) &addr_6, &dwSize ) != 0 )
		{
			addr_4.sin_family = family = AF_INET;
			dwSize = sizeof( addr_4 );

			if (WSAStringToAddress( line, AF_INET, NULL, ( struct sockaddr*) &addr_4, &dwSize ) != 0 )
			{
				continue;
			}
		}

		(*hInfo)->m_host.h_addr_list = (char**) malloc( sizeof( char**) * 2 );
		require_action( (*hInfo)->m_host.h_addr_list, exit, err = kNoMemoryErr );

		if ( family == AF_INET6 )
		{
			(*hInfo)->m_host.h_length		= (short) sizeof( addr_6.sin6_addr );
			(*hInfo)->m_host.h_addr_list[0] = (char*) malloc( (*hInfo)->m_host.h_length );
			require_action( (*hInfo)->m_host.h_addr_list[0], exit, err = kNoMemoryErr );
			memmove( (*hInfo)->m_host.h_addr_list[0], &addr_6.sin6_addr, sizeof( addr_6.sin6_addr ) );
			
		}
		else
		{
			(*hInfo)->m_host.h_length		= (short) sizeof( addr_4.sin_addr );
			(*hInfo)->m_host.h_addr_list[0] = (char*) malloc( (*hInfo)->m_host.h_length );
			require_action( (*hInfo)->m_host.h_addr_list[0], exit, err = kNoMemoryErr );
			memmove( (*hInfo)->m_host.h_addr_list[0], &addr_4.sin_addr, sizeof( addr_4.sin_addr ) );
		}

		(*hInfo)->m_host.h_addr_list[1] = NULL;
		(*hInfo)->m_host.h_addrtype		= family;

		// Now get the aliases

		if ((tok = strpbrk(tok, " \t")) != NULL)
		{
			*tok++ = '\0';
		}

		i = 0;

		(*hInfo)->m_host.h_aliases		= (char**) malloc( sizeof(char**) * numAliases );
		require_action( (*hInfo)->m_host.h_aliases, exit, err = kNoMemoryErr );
		(*hInfo)->m_host.h_aliases[0]	= NULL;

		while ( tok && *tok )
		{
			// Skip over the whitespace, waiting for the start of the next alias name

			if (*tok == ' ' || *tok == '\t')
			{
				tok++;
				continue;
			}

			// Check to make sure we don't exhaust the alias buffer

			if ( i >= ( numAliases - 1 ) )
			{
				numAliases = numAliases * 2;
				(*hInfo)->m_host.h_aliases = (char**) realloc( (*hInfo)->m_host.h_aliases, numAliases * sizeof( char** ) );
				require_action( (*hInfo)->m_host.h_aliases, exit, err = kNoMemoryErr );
			}

			(*hInfo)->m_host.h_aliases[i] = (char*) malloc( strlen( tok ) + 1 );
			require_action( (*hInfo)->m_host.h_aliases[i], exit, err = kNoMemoryErr );

			strcpy( (*hInfo)->m_host.h_aliases[i], tok );

			if (( tok = strpbrk( tok, " \t")) != NULL )
			{
				*tok++ = '\0';
			}

			(*hInfo)->m_host.h_aliases[++i] = NULL;
		}

		break;
	}

exit:

	if ( err && ( *hInfo ) )
	{
		HostsFileInfoFree( *hInfo );
		*hInfo = NULL;
	}

	return err;
}


#ifdef ENABLE_REVERSE_LOOKUP
//===========================================================================================================================
//	IsReverseLookup
//===========================================================================================================================

DEBUG_LOCAL OSStatus
IsReverseLookup( LPCWSTR name, size_t size )
{
	LPCWSTR		p;
	OSStatus	err = kNoErr;

	// IPv6LL Reverse-mapping domains are {8,9,A,B}.E.F.ip6.arpa
	require_action_quiet( size > sizeof_string( ".0.8.e.f.ip6.arpa" ), exit, err = WSASERVICE_NOT_FOUND );
 
	p = name + ( size - 1 );
	p = ( *p == '.' ) ? ( p - sizeof_string( ".0.8.e.f.ip6.arpa" ) ) : ( ( p - sizeof_string( ".0.8.e.f.ip6.arpa" ) ) + 1 );
	
	if	( ( ( p[ 0 ] != '.' )							||
		( ( p[ 1 ] != '0' ) )							||
		( ( p[ 2 ] != '.' ) )							||
		( ( p[ 3 ] != '8' ) )							||
		( ( p[ 4 ] != '.' ) )							||
		( ( p[ 5 ] != 'E' ) && ( p[ 5 ] != 'e' ) )		||
		( ( p[ 6 ] != '.' ) )							||
		( ( p[ 7 ] != 'F' ) && ( p[ 7 ] != 'f' ) )		||
		( ( p[ 8 ] != '.' ) )							||
		( ( p[ 9 ] != 'I' ) && ( p[ 9 ] != 'i' ) )		||
		( ( p[ 10 ] != 'P' ) && ( p[ 10 ] != 'p' ) )	||	
		( ( p[ 11 ] != '6' ) )							||
		( ( p[ 12 ] != '.' ) )							||
		( ( p[ 13 ] != 'A' ) && ( p[ 13 ] != 'a' ) )	||
		( ( p[ 14 ] != 'R' ) && ( p[ 14 ] != 'r' ) )	||
		( ( p[ 15 ] != 'P' ) && ( p[ 15 ] != 'p' ) )	||
		( ( p[ 16 ] != 'A' ) && ( p[ 16 ] != 'a' ) ) ) )
	{
		require_action_quiet( size > sizeof_string( ".254.169.in-addr.arpa" ), exit, err = WSASERVICE_NOT_FOUND );
 
		p = name + ( size - 1 );
		p = ( *p == '.' ) ? ( p - sizeof_string( ".254.169.in-addr.arpa" ) ) : ( ( p - sizeof_string( ".254.169.in-addr.arpa" ) ) + 1 );
	
		require_action_quiet( ( ( p[ 0 ] == '.' )						 &&
								( ( p[ 1 ] == '2' ) )							&&
								( ( p[ 2 ] == '5' ) )							&&
								( ( p[ 3 ] == '4' ) )							&&
								( ( p[ 4 ] == '.' ) )							&&
								( ( p[ 5 ] == '1' ) )							&&
								( ( p[ 6 ] == '6' ) )							&&
								( ( p[ 7 ] == '9' ) )							&&
								( ( p[ 8 ] == '.' ) )							&&
								( ( p[ 9 ] == 'I' ) || ( p[ 9 ] == 'i' ) )		&&
								( ( p[ 10 ] == 'N' ) || ( p[ 10 ] == 'n' ) )	&&	
								( ( p[ 11 ] == '-' ) )							&&
								( ( p[ 12 ] == 'A' ) || ( p[ 12 ] == 'a' ) )	&&
								( ( p[ 13 ] == 'D' ) || ( p[ 13 ] == 'd' ) )	&&
								( ( p[ 14 ] == 'D' ) || ( p[ 14 ] == 'd' ) )	&&
								( ( p[ 15 ] == 'R' ) || ( p[ 15 ] == 'r' ) )	&&
								( ( p[ 16 ] == '.' ) )							&&
								( ( p[ 17 ] == 'A' ) || ( p[ 17 ] == 'a' ) )	&&
								( ( p[ 18 ] == 'R' ) || ( p[ 18 ] == 'r' ) )	&&
								( ( p[ 19 ] == 'P' ) || ( p[ 19 ] == 'p' ) )	&&
								( ( p[ 20 ] == 'A' ) || ( p[ 20 ] == 'a' ) ) ),
								exit, err = WSASERVICE_NOT_FOUND );
	}

	// It's a reverse lookup

	check( err == kNoErr );

exit:

	return err;
}
#endif

//===========================================================================================================================
//	GetScopeId
//===========================================================================================================================

DEBUG_LOCAL DWORD
GetScopeId( DWORD ifIndex )
{
	DWORD						err;
	int							i;
	DWORD						flags;
	struct ifaddrs *			head;
	struct ifaddrs **			next;
	IP_ADAPTER_ADDRESSES *		iaaList;
	ULONG						iaaListSize;
	IP_ADAPTER_ADDRESSES *		iaa;
	DWORD						scopeId = 0;
	
	head	= NULL;
	next	= &head;
	iaaList	= NULL;
	
	require( gGetAdaptersAddressesFunctionPtr, exit );

	// Get the list of interfaces. The first call gets the size and the second call gets the actual data.
	// This loops to handle the case where the interface changes in the window after getting the size, but before the
	// second call completes. A limit of 100 retries is enforced to prevent infinite loops if something else is wrong.
	
	flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME;
	i = 0;
	for( ;; )
	{
		iaaListSize = 0;
		err = gGetAdaptersAddressesFunctionPtr( AF_UNSPEC, flags, NULL, NULL, &iaaListSize );
		check( err == ERROR_BUFFER_OVERFLOW );
		check( iaaListSize >= sizeof( IP_ADAPTER_ADDRESSES ) );
		
		iaaList = (IP_ADAPTER_ADDRESSES *) malloc( iaaListSize );
		require_action( iaaList, exit, err = ERROR_NOT_ENOUGH_MEMORY );
		
		err = gGetAdaptersAddressesFunctionPtr( AF_UNSPEC, flags, NULL, iaaList, &iaaListSize );
		if( err == ERROR_SUCCESS ) break;
		
		free( iaaList );
		iaaList = NULL;
		++i;
		require( i < 100, exit );
		dlog( kDebugLevelWarning, "%s: retrying GetAdaptersAddresses after %d failure(s) (%d %m)\n", __ROUTINE__, i, err, err );
	}
	
	for( iaa = iaaList; iaa; iaa = iaa->Next )
	{
		DWORD ipv6IfIndex;

		if ( iaa->IfIndex > 0xFFFFFF )
		{
			continue;
		}
		if ( iaa->Ipv6IfIndex > 0xFF )
		{
			continue;
		}

		// For IPv4 interfaces, there seems to be a bug in iphlpapi.dll that causes the 
		// following code to crash when iterating through the prefix list.  This seems
		// to occur when iaa->Ipv6IfIndex != 0 when IPv6 is not installed on the host.
		// This shouldn't happen according to Microsoft docs which states:
		//
		//     "Ipv6IfIndex contains 0 if IPv6 is not available on the interface."
		//
		// So the data structure seems to be corrupted when we return from
		// GetAdaptersAddresses(). The bug seems to occur when iaa->Length <
		// sizeof(IP_ADAPTER_ADDRESSES), so when that happens, we'll manually
		// modify iaa to have the correct values.

		if ( iaa->Length >= sizeof( IP_ADAPTER_ADDRESSES ) )
		{
			ipv6IfIndex = iaa->Ipv6IfIndex;
		}
		else
		{
			ipv6IfIndex	= 0;
		}

		// Skip psuedo and tunnel interfaces.
		
		if( ( ipv6IfIndex == 1 ) || ( iaa->IfType == IF_TYPE_TUNNEL ) )
		{
			continue;
		}

		if ( iaa->IfIndex == ifIndex )
		{
			scopeId = iaa->Ipv6IfIndex;
			break;
		}
	} 

exit:

	if( iaaList )
	{
		free( iaaList );
	}

	return scopeId;
}