File: PnrpPeerResolver.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (2268 lines) | stat: -rw-r--r-- 103,782 bytes parent folder | download | duplicates (9)
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
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------

namespace System.ServiceModel.Channels
{
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Net;
    using System.Net.Sockets;
    using System.Runtime;
    using System.Runtime.CompilerServices;
    using System.Runtime.ConstrainedExecution;
    using System.Runtime.InteropServices;
    using System.Runtime.Versioning;
    using System.Security.Permissions;
    using System.ServiceModel;
    using System.ServiceModel.Diagnostics;
    using System.ServiceModel.PeerResolvers;
    using System.ServiceProcess;
    using System.Text;
    using System.Threading;
    using Microsoft.Win32.SafeHandles;

    sealed class PnrpPeerResolver : PeerResolver
    {
        UnsafePnrpNativeMethods.PeerNameRegistrar registrar = new UnsafePnrpNativeMethods.PeerNameRegistrar();
        static bool isPnrpAvailable;
        static bool isPnrpInstalled;
        const UnsafePnrpNativeMethods.PnrpResolveCriteria resolutionScope = UnsafePnrpNativeMethods.PnrpResolveCriteria.NearestNonCurrentProcess;
        public const int PNRPINFO_HINT = 0x00000001;

        internal const int CommentLength = 80;
        internal const byte TcpTransport = 0x01;
        internal const byte PayloadVersion = 0x01;
        internal const char PathSeparator = '/';
        internal const int MinGuids = 1;
        internal const int MaxGuids = 2;
        internal const byte GuidEscape = 0xFF;
        internal const int MaxAddressEntries = 10;
        internal const int MaxAddressEntriesV1 = 4;
        internal const int MaxPathLength = 200; //this is known prefix+any guids
        static TimeSpan MaxTimeout = new TimeSpan(0, 10, 0); //PNRP validates the timeout to be no greater than 10 minutes
        static TimeSpan MaxResolveTimeout = new TimeSpan(0, 0, 45);
        internal const string GlobalCloudName = "Global_";
        static object SharedLock = new object();
        static Random randomGenerator = new Random();
        static TimeSpan TimeToWaitForStatus = TimeSpan.FromSeconds(15);
        PeerReferralPolicy referralPolicy = PeerReferralPolicy.Share;

        [Flags]
        internal enum PnrpResolveScope
        {
            None = 0,
            Global = 1,
            SiteLocal = 2,
            LinkLocal = 4,
            All = Global | SiteLocal | LinkLocal
        }

        static PnrpPeerResolver()
        {
            // determine if PNRP is installed
            isPnrpAvailable = false;
            using (UnsafePnrpNativeMethods.DiscoveryBase db = new UnsafePnrpNativeMethods.DiscoveryBase())
            {
                isPnrpInstalled = db.IsPnrpInstalled();
                isPnrpAvailable = db.IsPnrpAvailable(TimeToWaitForStatus);
            }
        }

        internal PnrpPeerResolver() : this(PeerReferralPolicy.Share) { }
        internal PnrpPeerResolver(PeerReferralPolicy referralPolicy)
        {
            this.referralPolicy = referralPolicy;
        }

        static Encoding PnrpEncoder
        {
            get
            {
                return System.Text.Encoding.UTF8;
            }
        }

        public static bool IsPnrpAvailable
        {
            get { return isPnrpAvailable; }
        }

        public static bool IsPnrpInstalled
        {
            get { return isPnrpInstalled; }
        }

        public static IPEndPoint GetHint()
        {
            byte[] bytes = new byte[16];
            lock (SharedLock)
            {
                randomGenerator.NextBytes(bytes);
            }
            return new IPEndPoint(new IPAddress(bytes), 0);
        }

        // Get the hint for the node in this process that handles this meshid
        // Get the nodeid for the current node - If the factory is using PrivatePeerNode then this can throw.
        // in which case use a hint of 0
        // The resolver prepends 0. to the meshid so we strip it off before locating the node.
        // false means that the search must include the current process.
        public static bool HasPeerNodeForMesh(string meshId)
        {
            PeerNodeImplementation node = null;
            return PeerNodeImplementation.TryGet(meshId, out node);
        }

        // PNRP doesn't support registering the same peername by the same identity in the same process.
        // Thus, we cannot test the PNRP resolver between two nodes in the same process without a little help.
        // By calling SetMeshExtensions, the resolver will register and resolver different ids, allowing two
        // nodes to work in the same process.
        string localExtension;
        string remoteExtension;
        internal void SetMeshExtensions(string local, string remote)
        {
            localExtension = local;
            remoteExtension = remote;
        }

        internal PnrpResolveScope EnumerateClouds(bool forResolve, Dictionary<uint, string> LinkCloudNames, Dictionary<uint, string> SiteCloudNames)
        {
            bool foundActive = false;
            PnrpResolveScope currentScope = PnrpResolveScope.None;
            LinkCloudNames.Clear();
            SiteCloudNames.Clear();
            UnsafePnrpNativeMethods.CloudInfo[] cloudInfos = UnsafePnrpNativeMethods.PeerCloudEnumerator.GetClouds();

            // If we are resolving we should first look for active clouds only
            // If we find some then we should return those to the caller
            // otherwise we should just load up with clouds
            if (forResolve)
            {
                foreach (UnsafePnrpNativeMethods.CloudInfo cloud in cloudInfos)
                {
                    if (cloud.State == UnsafePnrpNativeMethods.PnrpCloudState.Active)
                    {
                        if (cloud.Scope == UnsafePnrpNativeMethods.PnrpScope.Global)
                        {
                            currentScope |= PnrpResolveScope.Global;
                            foundActive = true;
                        }
                        else if (cloud.Scope == UnsafePnrpNativeMethods.PnrpScope.LinkLocal)
                        {
                            Fx.Assert(!String.IsNullOrEmpty(cloud.Name), "Unknown scope id in the IPAddress");
                            LinkCloudNames.Add(cloud.ScopeId, cloud.Name);
                            currentScope |= PnrpResolveScope.LinkLocal;
                            foundActive = true;
                        }
                        else if (cloud.Scope == UnsafePnrpNativeMethods.PnrpScope.SiteLocal)
                        {
                            Fx.Assert(!String.IsNullOrEmpty(cloud.Name), "Unknown scope id in the IPAddress");
                            SiteCloudNames.Add(cloud.ScopeId, cloud.Name);
                            currentScope |= PnrpResolveScope.SiteLocal;
                            foundActive = true;
                        }
                    }
                }
            }

            if (!foundActive)
            {
                foreach (UnsafePnrpNativeMethods.CloudInfo cloud in cloudInfos)
                {
                    if (!((cloud.State == UnsafePnrpNativeMethods.PnrpCloudState.Dead)
                        || (cloud.State == UnsafePnrpNativeMethods.PnrpCloudState.Disabled)
                        || (cloud.State == UnsafePnrpNativeMethods.PnrpCloudState.NoNet))
                       )
                    {
                        if (cloud.Scope == UnsafePnrpNativeMethods.PnrpScope.Global)
                        {
                            currentScope |= PnrpResolveScope.Global;
                            continue;
                        }
                        if (cloud.Scope == UnsafePnrpNativeMethods.PnrpScope.LinkLocal)
                        {
                            Fx.Assert(!String.IsNullOrEmpty(cloud.Name), "Unknown scope id in the IPAddress");
                            LinkCloudNames.Add(cloud.ScopeId, cloud.Name);
                            currentScope |= PnrpResolveScope.LinkLocal;
                        }
                        else if (cloud.Scope == UnsafePnrpNativeMethods.PnrpScope.SiteLocal)
                        {
                            Fx.Assert(!String.IsNullOrEmpty(cloud.Name), "Unknown scope id in the IPAddress");
                            SiteCloudNames.Add(cloud.ScopeId, cloud.Name);
                            currentScope |= PnrpResolveScope.SiteLocal;
                        }
                    }
                }
            }
            return currentScope;
        }

        class RegistrationHandle
        {
            public string PeerName;
            public List<string> Clouds;
            public RegistrationHandle(string peerName)
            {
                this.PeerName = peerName;
                Clouds = new List<string>();
            }
            public void AddCloud(string name)
            {
                this.Clouds.Add(name);
            }
        }

        public override bool CanShareReferrals
        {
            get
            {
                return referralPolicy != PeerReferralPolicy.DoNotShare;
            }
        }
        public override object Register(string meshId, PeerNodeAddress nodeAddress, TimeSpan timeout)
        {
            ThrowIfNoPnrp();

            PnrpRegistration globalEntry = null;
            PnrpRegistration[] linkEntries = null;
            PnrpRegistration[] siteEntries = null;

            RegistrationHandle regHandle = new RegistrationHandle(meshId);
            Dictionary<uint, string> SiteCloudNames = new Dictionary<uint, string>();
            Dictionary<uint, string> LinkCloudNames = new Dictionary<uint, string>();

            PnrpResolveScope availableScope = EnumerateClouds(false, LinkCloudNames, SiteCloudNames);

            if (availableScope == PnrpResolveScope.None)
            {
                //could not find any clouds.
                PeerExceptionHelper.ThrowInvalidOperation_PnrpNoClouds();
            }

            if (localExtension != null)
                meshId += localExtension;

            try
            {
                PeerNodeAddressToPnrpRegistrations(meshId, LinkCloudNames, SiteCloudNames, nodeAddress, out linkEntries, out siteEntries, out globalEntry);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e)) throw;
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.PeerPnrpIllegalUri), e));
            }
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            try
            {
                PnrpResolveScope currentScope = PnrpResolveScope.None;
                if (globalEntry != null)
                {
                    if (globalEntry.Addresses.Length > 0 && (availableScope & PnrpResolveScope.Global) != 0)
                    {
                        registrar.Register(globalEntry, timeoutHelper.RemainingTime());
                        regHandle.AddCloud(globalEntry.CloudName);
                        currentScope |= PnrpResolveScope.Global;
                    }
                }
                if (linkEntries.Length > 0)
                {
                    foreach (PnrpRegistration entry in linkEntries)
                    {
                        if (entry.Addresses.Length > 0)
                        {
                            registrar.Register(entry, timeoutHelper.RemainingTime());
                            regHandle.AddCloud(entry.CloudName);
                        }
                    }
                    currentScope |= PnrpResolveScope.LinkLocal;
                }
                if (siteEntries.Length > 0)
                {
                    foreach (PnrpRegistration entry in siteEntries)
                    {
                        if (entry.Addresses.Length > 0)
                        {
                            registrar.Register(entry, timeoutHelper.RemainingTime());
                            regHandle.AddCloud(entry.CloudName);
                        }
                    }
                    currentScope |= PnrpResolveScope.SiteLocal;
                }
                if (currentScope == PnrpResolveScope.None)
                {
                    // We have addresses but no cloud that corresponds to them
                    // so we should throw an exception
                    PeerExceptionHelper.ThrowInvalidOperation_PnrpAddressesUnsupported();
                }
            }
            catch (SocketException)
            {
                try
                {
                    Unregister(regHandle, timeoutHelper.RemainingTime());
                }
                catch (SocketException e)
                {
                    DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                }
                throw;
            }

            if (DiagnosticUtility.ShouldTraceInformation)
            {
                PnrpRegisterTraceRecord record = new PnrpRegisterTraceRecord(meshId, globalEntry, siteEntries, linkEntries);
                TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PnrpRegisteredAddresses,
                    SR.GetString(SR.TraceCodePnrpRegisteredAddresses),
                    record, this, null);
            }

            return regHandle;
        }

        void ThrowIfNoPnrp()
        {
            if (!isPnrpAvailable)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                    SR.GetString(SR.PeerPnrpNotAvailable)));
            }
        }

        public override void Unregister(object registrationId, TimeSpan timeout)
        {
            RegistrationHandle regHandle = registrationId as RegistrationHandle;
            if (regHandle == null || String.IsNullOrEmpty(regHandle.PeerName))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.PeerInvalidRegistrationId, regHandle), "registrationId"));
            string meshId = regHandle.PeerName;

            // prepend a 0. for unsecured peername
            string peerName = string.Format(CultureInfo.InvariantCulture, "0.{0}", meshId);
            registrar.Unregister(peerName, regHandle.Clouds, timeout);

            if (DiagnosticUtility.ShouldTraceInformation)
            {
                PnrpPeerResolverTraceRecord record = new PnrpPeerResolverTraceRecord(meshId, new List<PeerNodeAddress>());
                TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PnrpUnregisteredAddresses,
                    SR.GetString(SR.TraceCodePnrpUnregisteredAddresses),
                    record, this, null);
            }
        }

        public override void Update(object registrationId, PeerNodeAddress updatedNodeAddress, TimeSpan timeout)
        {
            RegistrationHandle regHandle = registrationId as RegistrationHandle;
            if (regHandle == null || string.IsNullOrEmpty(regHandle.PeerName))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.PeerInvalidRegistrationId, regHandle), "registrationId"));

            string meshId = regHandle.PeerName;
            Register(meshId, updatedNodeAddress, timeout);
        }

        //return null in case of unrecognized format. consider adding logging.
        PeerNodeAddress PeerNodeAddressFromPnrpRegistration(PnrpRegistration input)
        {
            List<IPAddress> addresses = new List<IPAddress>();
            PeerNodeAddress result = null;
            Guid[] guids;
            StringBuilder pathBuilder = new StringBuilder(MaxPathLength);
            int version = 0;
            string protocolScheme;

            try
            {
                if (input == null || String.IsNullOrEmpty(input.Comment))
                    return null;
                Array.ForEach(input.Addresses, delegate(IPEndPoint obj) { addresses.Add(obj.Address); });
                if (addresses.Count != 0)
                {
                    UriBuilder uriBuilder = new UriBuilder();
                    uriBuilder.Port = input.Addresses[0].Port;
                    uriBuilder.Host = addresses[0].ToString();
                    pathBuilder.Append(PeerStrings.KnownServiceUriPrefix);
                    CharEncoder.Decode(input.Comment, out version, out protocolScheme, out guids);

                    if (
                        (version == PayloadVersion) &&
                        (guids != null) && (guids.Length <= MaxGuids) &&
                        (guids.Length >= MinGuids)
                    )
                    {
                        uriBuilder.Scheme = protocolScheme;
                        Array.ForEach(guids, delegate(Guid guid)
                                            {
                                                pathBuilder.Append(PathSeparator + String.Format(CultureInfo.InvariantCulture, "{0}", guid.ToString()));
                                            }
                        );
                        uriBuilder.Path = String.Format(CultureInfo.InvariantCulture, "{0}", pathBuilder.ToString());
                        result = new PeerNodeAddress(new EndpointAddress(uriBuilder.Uri), new ReadOnlyCollection<IPAddress>(addresses));
                    }
                }
            }
            catch (ArgumentException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
            }
            catch (FormatException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
            }
            catch (IndexOutOfRangeException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
            }

            return result;

        }

        void TrimToMaxAddresses(List<IPEndPoint> addressList)
        {
            if (addressList.Count > MaxAddressEntries)
            {
                addressList.RemoveRange(MaxAddressEntries, addressList.Count - MaxAddressEntries);
            }
        }

        void PeerNodeAddressToPnrpRegistrations(string meshName, Dictionary<uint, string> LinkCloudNames, Dictionary<uint, string> SiteCloudNames, PeerNodeAddress input, out PnrpRegistration[] linkRegs, out PnrpRegistration[] siteRegs, out PnrpRegistration global)
        {
            PnrpRegistration reg = new PnrpRegistration();

            Dictionary<uint, PnrpRegistration> resultsLink = new Dictionary<uint, PnrpRegistration>();
            Dictionary<uint, PnrpRegistration> resultsSite = new Dictionary<uint, PnrpRegistration>();
            PnrpRegistration entry = null;
            string scheme;
            Guid[] guids;
            ParseServiceUri(input.EndpointAddress.Uri, out scheme, out guids);
            int port = input.EndpointAddress.Uri.Port;
            if (port <= 0)
                port = TcpUri.DefaultPort;
            string peerName = string.Format(CultureInfo.InvariantCulture, "0.{0}", meshName);
            string comment = CharEncoder.Encode(PayloadVersion, scheme, guids);
            global = null;
            string cloudName = string.Empty;
            foreach (IPAddress address in input.IPAddresses)
            {
                if (address.AddressFamily == AddressFamily.InterNetworkV6
                    &&
                    ((address.IsIPv6LinkLocal) || (address.IsIPv6SiteLocal))
                )
                {
                    if (address.IsIPv6LinkLocal)
                    {
                        if (!resultsLink.TryGetValue((uint)address.ScopeId, out entry))
                        {
                            if (!LinkCloudNames.TryGetValue((uint)address.ScopeId, out cloudName))
                            {
                                continue;
                            }
                            entry = PnrpRegistration.Create(peerName, comment, cloudName);
                            resultsLink.Add((uint)address.ScopeId, entry);
                        }
                    }
                    else
                    {
                        if (!resultsSite.TryGetValue((uint)address.ScopeId, out entry))
                        {
                            if (!SiteCloudNames.TryGetValue((uint)address.ScopeId, out cloudName))
                            {
                                continue;
                            }
                            entry = PnrpRegistration.Create(peerName, comment, cloudName);
                            resultsSite.Add((uint)address.ScopeId, entry);
                        }
                    }
                    entry.addressList.Add(new IPEndPoint(address, port));
                }
                else
                {
                    if (global == null)
                    {
                        global = PnrpRegistration.Create(peerName, comment, GlobalCloudName);
                    }
                    global.addressList.Add(new IPEndPoint(address, port));
                }
            }
            if (global != null)
            {
                if (global.addressList != null)
                {
                    TrimToMaxAddresses(global.addressList);
                    global.Addresses = global.addressList.ToArray();
                }
                else
                    global.Addresses = new IPEndPoint[0];
            }

            if (resultsLink.Count != 0)
            {
                foreach (PnrpRegistration tempLink in resultsLink.Values)
                {
                    if (tempLink.addressList != null)
                    {
                        TrimToMaxAddresses(tempLink.addressList);
                        tempLink.Addresses = tempLink.addressList.ToArray();
                    }
                    else
                    {
                        tempLink.Addresses = new IPEndPoint[0];
                    }
                }
                linkRegs = new PnrpRegistration[resultsLink.Count];
                resultsLink.Values.CopyTo(linkRegs, 0);
            }
            else
                linkRegs = new PnrpRegistration[0];
            if (resultsSite.Count != 0)
            {
                foreach (PnrpRegistration tempSite in resultsSite.Values)
                {
                    if (tempSite.addressList != null)
                    {
                        TrimToMaxAddresses(tempSite.addressList);
                        tempSite.Addresses = tempSite.addressList.ToArray();
                    }
                    else
                    {
                        tempSite.Addresses = new IPEndPoint[0];
                    }
                }
                siteRegs = new PnrpRegistration[resultsSite.Count];
                resultsSite.Values.CopyTo(siteRegs, 0);
            }
            else
                siteRegs = new PnrpRegistration[0];
        }

        static int ProtocolFromName(string name)
        {
            if (name == Uri.UriSchemeNetTcp)
            {
                return TcpTransport;
            }

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("name", SR.GetString(SR.PeerPnrpIllegalUri));
        }

        static string NameFromProtocol(byte number)
        {
            switch (number)
            {
                case TcpTransport:
                    return Uri.UriSchemeNetTcp;
                default:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.PeerPnrpIllegalUri)));
            }
        }

        void ParseServiceUri(Uri uri, out string scheme, out Guid[] result)
        {
            if (uri != null)
            {
                if ((ProtocolFromName(uri.Scheme) != 0) && !String.IsNullOrEmpty(uri.AbsolutePath))
                {
                    scheme = uri.Scheme;
                    string[] parts = uri.AbsolutePath.Trim(new char[] { ' ', PathSeparator }).Split(PathSeparator);
                    if ((0 == String.Compare(parts[0], PeerStrings.KnownServiceUriPrefix, StringComparison.OrdinalIgnoreCase)))
                    {
                        if (parts.Length >= MinGuids && parts.Length <= MaxGuids + 1)
                        {
                            result = new Guid[parts.Length - 1];
                            try
                            {
                                for (int i = 1; i < parts.Length; i++)
                                    result[i - 1] = Fx.CreateGuid(parts[i]);
                                return;
                            }
                            catch (FormatException e)
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.PeerPnrpIllegalUri), e));
                            }
                        }
                    }
                }
            }
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.PeerPnrpIllegalUri)));
        }

        void MergeResults(Dictionary<string, PnrpRegistration> results, List<PnrpRegistration> regs)
        {
            PnrpRegistration entry = null;
            foreach (PnrpRegistration reg in regs)
            {
                if (!results.TryGetValue(reg.Comment, out entry))
                {
                    entry = reg;
                    results.Add(reg.Comment, reg);
                    entry.addressList = new List<IPEndPoint>();
                }
                entry.addressList.AddRange(reg.Addresses);
                reg.Addresses = null;
            }
        }

        void MergeResults(List<PeerNodeAddress> nodeAddressList, List<PnrpRegistration> globalRegistrations, List<PnrpRegistration> linkRegistrations, List<PnrpRegistration> siteRegistrations)
        {
            Dictionary<string, PnrpRegistration> results = new Dictionary<string, PnrpRegistration>();
            MergeResults(results, globalRegistrations);
            MergeResults(results, siteRegistrations);
            MergeResults(results, linkRegistrations);
            PeerNodeAddress result;
            foreach (PnrpRegistration reg in results.Values)
            {
                reg.Addresses = reg.addressList.ToArray();
                result = PeerNodeAddressFromPnrpRegistration(reg);
                if (result != null)
                    nodeAddressList.Add(result);
            }
        }

        public override ReadOnlyCollection<PeerNodeAddress> Resolve(string meshId, int maxAddresses, TimeSpan timeout)
        {
            ThrowIfNoPnrp();
            UnsafePnrpNativeMethods.PeerNameResolver resolver;
            List<UnsafePnrpNativeMethods.PeerNameResolver> resolvers = new List<UnsafePnrpNativeMethods.PeerNameResolver>();
            List<PnrpRegistration> globalRegistrations = new List<PnrpRegistration>();
            List<PnrpRegistration> linkRegistrations = new List<PnrpRegistration>();
            List<PnrpRegistration> siteRegistrations = new List<PnrpRegistration>();
            List<WaitHandle> handles = new List<WaitHandle>();
            Dictionary<uint, string> SiteCloudNames = new Dictionary<uint, string>();
            Dictionary<uint, string> LinkCloudNames = new Dictionary<uint, string>();
            UnsafePnrpNativeMethods.PnrpResolveCriteria targetScope = resolutionScope;
            TimeoutHelper timeoutHelper = new TimeoutHelper(TimeSpan.Compare(timeout, MaxResolveTimeout) <= 0 ? timeout : MaxResolveTimeout);

            if (!HasPeerNodeForMesh(meshId))
                targetScope = UnsafePnrpNativeMethods.PnrpResolveCriteria.Any;
            PnrpResolveScope currentScope = EnumerateClouds(true, LinkCloudNames, SiteCloudNames);

            if (remoteExtension != null)
                meshId += remoteExtension;

            // prepend a 0. for unsecured peername
            string peerName = string.Format(CultureInfo.InvariantCulture, "0.{0}", meshId);
            if ((currentScope & PnrpResolveScope.Global) != 0)
            {
                resolver = new UnsafePnrpNativeMethods.PeerNameResolver(
                                    peerName, maxAddresses, targetScope, 0, GlobalCloudName, timeoutHelper.RemainingTime(), globalRegistrations);
                handles.Add(resolver.AsyncWaitHandle);
                resolvers.Add(resolver);
            }

            if ((currentScope & PnrpResolveScope.LinkLocal) != 0)
            {
                foreach (KeyValuePair<uint, string> linkEntry in LinkCloudNames)
                {
                    resolver = new UnsafePnrpNativeMethods.PeerNameResolver(
                                    peerName, maxAddresses, targetScope, linkEntry.Key, linkEntry.Value, timeoutHelper.RemainingTime(), linkRegistrations);
                    handles.Add(resolver.AsyncWaitHandle);
                    resolvers.Add(resolver);
                }
            }

            if ((currentScope & PnrpResolveScope.SiteLocal) != 0)
            {
                foreach (KeyValuePair<uint, string> siteEntry in SiteCloudNames)
                {
                    resolver = new UnsafePnrpNativeMethods.PeerNameResolver(
                                    peerName, maxAddresses, targetScope, siteEntry.Key, siteEntry.Value, timeoutHelper.RemainingTime(), siteRegistrations);
                    handles.Add(resolver.AsyncWaitHandle);
                    resolvers.Add(resolver);
                }
            }
            if (handles.Count == 0)
            {
                //could not find any clouds.
                if (DiagnosticUtility.ShouldTraceWarning)
                {
                    Exception exception = new InvalidOperationException(SR.GetString(SR.PnrpNoClouds));
                    PnrpResolveExceptionTraceRecord record = new PnrpResolveExceptionTraceRecord(meshId, string.Empty, exception);
                    TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.PnrpResolvedAddresses,
                        SR.GetString(SR.TraceCodePnrpResolvedAddresses),
                        record, this, null);
                }
                return new ReadOnlyCollection<PeerNodeAddress>(new List<PeerNodeAddress>());
            }

            Exception lastException = null;
            foreach (UnsafePnrpNativeMethods.PeerNameResolver handle in resolvers)
            {
                try
                {
                    handle.End();
                }
                catch (SocketException e)
                {
                    DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                    lastException = e;
                }
            }

            List<PeerNodeAddress> nodeAddressList = new List<PeerNodeAddress>();
            MergeResults(nodeAddressList, globalRegistrations, linkRegistrations, siteRegistrations);
            if ((lastException != null) && (nodeAddressList.Count == 0))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(lastException);
            if (DiagnosticUtility.ShouldTraceInformation)
            {
                PnrpPeerResolverTraceRecord record = new PnrpPeerResolverTraceRecord(meshId, nodeAddressList);
                TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PnrpResolvedAddresses,
                    SR.GetString(SR.TraceCodePnrpResolvedAddresses),
                    record, this, null);
            }
            return new ReadOnlyCollection<PeerNodeAddress>(nodeAddressList);
        }


        // contains the friendly PNRP information
        internal class PnrpRegistration
        {
            public string PeerName;
            public string CloudName;
            public string Comment;
            public IPEndPoint[] Addresses;
            public List<IPEndPoint> addressList;

            internal static PnrpRegistration Create(string peerName, string comment, string cloudName)
            {
                PnrpRegistration reg = new PnrpRegistration();
                reg.Comment = comment;
                reg.CloudName = cloudName;
                reg.PeerName = peerName;
                reg.addressList = new List<IPEndPoint>();
                return reg;
            }
        }

        internal class CharEncoder
        {
            static void CheckAtLimit(int current)
            {
                if (current + 1 >= CommentLength)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.PeerPnrpIllegalUri)));
            }
            static void EncodeByte(byte b, ref int offset, byte[] bytes)
            {
                if (b == 0 || b == GuidEscape)
                {
                    CheckAtLimit(offset);
                    bytes[offset++] = GuidEscape;
                }
                CheckAtLimit(offset);
                bytes[offset++] = b;
            }

            static internal string Encode(int version, string protocolName, Guid[] guids)
            {
                byte[] bytes = new byte[CommentLength];
                int i = 0;
                int protocol = ProtocolFromName(protocolName);
                EncodeByte(Convert.ToByte(version), ref i, bytes);
                EncodeByte(Convert.ToByte(protocol), ref i, bytes);
                EncodeByte(Convert.ToByte(guids.Length), ref i, bytes);
                foreach (Guid guid in guids)
                {
                    foreach (byte b in guid.ToByteArray())
                    {
                        EncodeByte(Convert.ToByte(b), ref i, bytes);
                    }
                }
                if (i % 2 != 0 && i < bytes.Length)
                    bytes[i] = GuidEscape;
                // Now we have a collection of bytes lets turn it into a string
                int length = i;
                int clength = (length / 2) + (length % 2);         // Pack 2 bytes per char
                char[] chars = new char[clength];
                i = 0;
                for (int j = 0; j < clength; j++)
                {
                    chars[j] = Convert.ToChar(bytes[i++] * 0x100 + bytes[i++]);
                }
                return new string(chars);
            }

            static byte GetByte(int offset, char[] chars)
            {
                int p = offset / 2;
                int lo = offset % 2;
                return Convert.ToByte(lo == 1 ? chars[p] & GuidEscape : chars[p] / 0x100);
            }

            static byte DecodeByte(ref int offset, char[] chars)
            {
                byte b = GetByte(offset++, chars);
                if (b == 0xff)
                {
                    b = GetByte(offset++, chars);
                }
                return b;
            }

            static internal void Decode(string buffer, out int version, out string protocolName, out Guid[] guids)
            {
                char[] chars = buffer.ToCharArray();
                byte protocol;
                int i = 0;

                version = DecodeByte(ref i, chars);
                protocol = DecodeByte(ref i, chars);
                protocolName = NameFromProtocol(protocol);
                int length = DecodeByte(ref i, chars);
                guids = new Guid[length];

                for (int g = 0; g < length; g++)
                {
                    byte[] bytes = new byte[16];
                    for (int j = 0; j < 16; j++)
                    {
                        bytes[j] = DecodeByte(ref i, chars);
                    }
                    guids[g] = new Guid(bytes);
                }
            }
        }

        internal enum PnrpErrorCodes
        {
            WSA_PNRP_ERROR_BASE = 11500,
            WSA_PNRP_CLOUD_NOT_FOUND = 11501,
            WSA_PNRP_CLOUD_DISABLED = 11502,
            //these error codes are not relevant for now
            //            WSA_PNRP_INVALID_IDENTITY = 11503,
            //            WSA_PNRP_TOO_MUCH_LOAD = 11504,
            WSA_PNRP_CLOUD_IS_RESOLVE_ONLY = 11505,
            //            WSA_PNRP_CLIENT_INVALID_COMPARTMENT_ID = 11506,
            WSA_PNRP_FW_PORT_BLOCKED = 11507,
            WSA_PNRP_DUPLICATE_PEER_NAME = 11508,
        }

        internal class PnrpException : SocketException
        {
            string message;

            internal PnrpException(int errorCode, string cloud)
                : base(errorCode)
            {
                LoadMessage(errorCode, cloud);
            }

            public override string Message
            {
                get
                {
                    if (!String.IsNullOrEmpty(message))
                        return message;
                    else
                        return base.Message;
                }
            }

            void LoadMessage(int errorCode, string cloud)
            {
                string formatString;
                switch ((PnrpErrorCodes)errorCode)
                {
                    case PnrpErrorCodes.WSA_PNRP_CLOUD_DISABLED:
                        formatString = SR.PnrpCloudDisabled;
                        break;
                    case PnrpErrorCodes.WSA_PNRP_CLOUD_NOT_FOUND:
                        formatString = SR.PnrpCloudNotFound;
                        break;
                    case PnrpErrorCodes.WSA_PNRP_CLOUD_IS_RESOLVE_ONLY:
                        formatString = SR.PnrpCloudResolveOnly;
                        break;
                    case PnrpErrorCodes.WSA_PNRP_FW_PORT_BLOCKED:
                        formatString = SR.PnrpPortBlocked;
                        break;
                    case PnrpErrorCodes.WSA_PNRP_DUPLICATE_PEER_NAME:
                        formatString = SR.PnrpDuplicatePeerName;
                        break;
                    default:
                        formatString = null;
                        break;
                }
                if (formatString != null)
                    message = SR.GetString(formatString, cloud);
            }
        }

        internal static class UnsafePnrpNativeMethods
        {
            // WSA import functions
            [DllImport("ws2_32.dll", CharSet = CharSet.Unicode)]
            [ResourceExposure(ResourceScope.None)]
            static extern int WSASetService(CriticalAllocHandle querySet, WsaSetServiceOp essOperation, int dwControlFlags);

            [DllImport("ws2_32.dll", CharSet = CharSet.Unicode)]
            [ResourceExposure(ResourceScope.None)]
            static extern int WSALookupServiceNext(CriticalLookupHandle hLookup,
                WsaNspControlFlags dwControlFlags, ref int lpdwBufferLength, IntPtr Results);
            [DllImport("ws2_32.dll", CharSet = CharSet.Unicode), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
            [ResourceExposure(ResourceScope.None)]
            static extern int WSALookupServiceEnd(IntPtr hLookup);
            [DllImport("ws2_32.dll", CharSet = CharSet.Unicode)]
            [ResourceExposure(ResourceScope.None)]
            static extern int WSALookupServiceBegin(CriticalAllocHandle query, WsaNspControlFlags dwControlFlags, out CriticalLookupHandle hLookup);
            [DllImport("ws2_32.dll", CharSet = CharSet.Ansi)]
            [ResourceExposure(ResourceScope.None)]
            static extern int WSAStartup(Int16 wVersionRequested, ref WsaData lpWSAData);
            [DllImport("ws2_32.dll", CharSet = CharSet.Ansi)]
            [ResourceExposure(ResourceScope.None)]
            static extern int WSACleanup();
            [DllImport("ws2_32.dll", CharSet = CharSet.Ansi)]
            [ResourceExposure(ResourceScope.None)]
            static extern int WSAGetLastError();
            [DllImport("ws2_32.dll", CharSet = CharSet.Unicode)]
            [ResourceExposure(ResourceScope.None)]
            static extern int WSAEnumNameSpaceProviders(ref int lpdwBufferLength, IntPtr lpnspBuffer);

            // PNRP namespace identifiers
            static Guid SvcIdCloud = new Guid(0xc2239ce6, 0x00c0, 0x4fbf, 0xba, 0xd6, 0x18, 0x13, 0x93, 0x85, 0xa4, 0x9a);
            static Guid SvcIdNameV1 = new Guid(0xc2239ce5, 0x00c0, 0x4fbf, 0xba, 0xd6, 0x18, 0x13, 0x93, 0x85, 0xa4, 0x9a);
            static Guid SvcIdName = new Guid(0xc2239ce7, 0x00c0, 0x4fbf, 0xba, 0xd6, 0x18, 0x13, 0x93, 0x85, 0xa4, 0x9a);
            static Guid NsProviderName = new Guid(0x03fe89cd, 0x766d, 0x4976, 0xb9, 0xc1, 0xbb, 0x9b, 0xc4, 0x2c, 0x7b, 0x4d);
            static Guid NsProviderCloud = new Guid(0x03fe89ce, 0x766d, 0x4976, 0xb9, 0xc1, 0xbb, 0x9b, 0xc4, 0x2c, 0x7b, 0x4d);

            const int MaxAddresses = 10;
            const int MaxAddressesV1 = 4;
            const Int16 RequiredWinsockVersion = 0x0202;

            // specifies the namespace used used by a specified WSAQUERYSET
            [Serializable]
            internal enum NspNamespaces
            {
                Cloud = 39,
                Name = 38,
            }

            [Serializable]
            [Flags]
            internal enum PnrpCloudFlags
            {
                None = 0x0000,
                LocalName = 0x0001, //  Name not valid on other computers
            }

            [Serializable]
            internal enum PnrpCloudState
            {
                Virtual = 0,        //  Not initialized
                Synchronizing = 1,  //  The cache is initializing
                Active = 2,         //  Cloud is active
                Dead = 3,            //  Initialized but lost network
                Disabled = 4,       //disabled in the registry
                NoNet = 5,          //active but lost network
                Alone = 6,
            }

            [Serializable]
            internal enum PnrpExtendedPayloadType
            {
                None = 0,
                Binary,
                String
            }

            // internal because it is exposed by PeerNameResolver
            [Serializable]
            internal enum PnrpResolveCriteria
            {
                Default = 0,                    // Default = PNRP_RESOLVE_CRITERIA_NON_CURRENT_PROCESS_PEER_NAME
                Remote = 1,                     // match first 128 bits (remote node)
                NearestRemote = 2,              // match first 128 bits, and close to top 64 bits
                // of the second 128 bits (remote node)
                NonCurrentProcess = 3,          //  match first 128 bits (not in the current process) 
                NearestNonCurrentProcess = 4,   // match first 128 bits, and close to top 64 bits
                // of the second 128 bits (not in the current process)   
                Any = 5,                        // match first 128 bits (any node)
                Nearest = 6                     // match first 128 bits, and close to top 64 bits
                // of the second 128 bits (any node)   
            }

            [Serializable]
            internal enum PnrpRegisteredIdState
            {
                Ok = 1,     //  Id is active in cloud
                Problem = 2 //  Id is no longer registered in cloud
            }

            internal enum PnrpScope
            {
                Any = 0,
                Global = 1,
                SiteLocal = 2,
                LinkLocal = 3,
            }

            // primary use in this code is to specify what information should be returned by WSALookupServiceNext
            [Flags]
            internal enum WsaNspControlFlags
            {
                Deep = 0x0001,
                Containers = 0x0002,
                NoContainers = 0x0004,
                Nearest = 0x0008,
                ReturnName = 0x0010,
                ReturnType = 0x0020,
                ReturnVersion = 0x0040,
                ReturnComment = 0x0080,
                ReturnAddr = 0x0100,
                ReturnBlob = 0x0200,
                ReturnAliases = 0x0400,
                ReturnQueryString = 0x0800,
                ReturnAll = 0x0FF0,
                ResService = 0x8000,
                FlushCache = 0x1000,
                FlushPrevious = 0x2000,
            }

            internal enum WsaError
            {
                WSAEINVAL = 10022,
                WSAEFAULT = 10014,
                WSAENOMORE = 10102,
                WSA_E_NO_MORE = 10110,
                WSANO_DATA = 11004
            }

            // specifies the operation of WSASetService
            internal enum WsaSetServiceOp
            {
                Register = 0,
                Deregister,
                Delete
            }

            internal struct BlobSafe
            {
                public int cbSize;
                public CriticalAllocHandle pBlobData;
            }

            internal struct BlobNative
            {
                public int cbSize;
                public IntPtr pBlobData;
            }


            // PnrpResolver does not currently support any cloud except Global. If this needs to be changed, we will
            // need to be able to enumerate clouds.

            // managed equivalent of both PNRPCLOUDINFO and PNRP_CLOUD_ID
            // internal because it is exposed by PeerCloudEnumerator
            internal class CloudInfo
            {
                public string Name;
                public PnrpScope Scope;
                public uint ScopeId;
                public PnrpCloudState State;
                public PnrpCloudFlags Flags;
            }

            [Serializable]
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
            internal struct CsAddrInfo
            {
                public IPEndPoint LocalAddr;
                public IPEndPoint RemoteAddr;
                public int iSocketType;
                public int iProtocol;
            }

            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
            internal class CsAddrInfoSafe : IDisposable
            {
                public SOCKET_ADDRESS_SAFE LocalAddr;
                public SOCKET_ADDRESS_SAFE RemoteAddr;
                public int iSocketType;
                public int iProtocol;
                bool disposed;

                public static CsAddrInfoSafe[] FromAddresses(CsAddrInfo[] addresses)
                {
                    CsAddrInfoSafe addr;
                    CsAddrInfoSafe[] result = null;
                    if (addresses == null || addresses.Length == 0)
                        return null;

                    result = new CsAddrInfoSafe[addresses.Length];
                    int i = 0;
                    foreach (CsAddrInfo info in addresses)
                    {
                        addr = new CsAddrInfoSafe();
                        addr.LocalAddr = SOCKET_ADDRESS_SAFE.SocketAddressFromIPEndPoint(info.LocalAddr);
                        addr.RemoteAddr = SOCKET_ADDRESS_SAFE.SocketAddressFromIPEndPoint(info.RemoteAddr);
                        addr.iProtocol = info.iProtocol;
                        addr.iSocketType = info.iSocketType;
                        result[i++] = addr;
                    }
                    return result;
                }
                public static void StructureToPtr(CsAddrInfoSafe input, IntPtr target)
                {
                    CsAddrInfoNative native;
                    native.iProtocol = input.iProtocol;
                    native.iSocketType = input.iSocketType;
                    native.LocalAddr.iSockaddrLength = input.LocalAddr.iSockaddrLength;
                    native.LocalAddr.lpSockAddr = input.LocalAddr.lpSockAddr;
                    native.RemoteAddr.iSockaddrLength = input.RemoteAddr.iSockaddrLength;
                    native.RemoteAddr.lpSockAddr = input.RemoteAddr.lpSockAddr;

                    Marshal.StructureToPtr(native, target, false);
                }
                ~CsAddrInfoSafe()
                {
                    Dispose(false);
                }
                public virtual void Dispose()
                {
                    Dispose(true);
                    GC.SuppressFinalize(this);
                }
                void Dispose(bool disposing)
                {
                    if (disposed)
                    {
                        if (disposing)
                        {
                            LocalAddr.Dispose();
                            RemoteAddr.Dispose();
                        }
                    }
                    disposed = true;
                }

            }

            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
            internal struct CsAddrInfoNative
            {
                public SOCKET_ADDRESS_NATIVE LocalAddr;
                public SOCKET_ADDRESS_NATIVE RemoteAddr;
                public int iSocketType;
                public int iProtocol;
            }

            [Serializable]
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
            internal struct PnrpCloudId
            {
                public int AddressFamily; // should be AF_INET6
                public PnrpScope Scope;     // Global, site, or link
                public uint ScopeId;       // specifies interface

            }

            internal struct PnrpCloudInfo
            {
                public int dwSize;            // size of this struct
                public PnrpCloudId Cloud;       // network cloud information
                public PnrpCloudState dwCloudState; // state of cloud
                public PnrpCloudFlags Flags;
            }

            //native equivalent for easy marshalling. 
            //should be exactly like PnrpInfo except CriticalHandles
            internal struct PnrpInfoNative
            {
                public int dwSize;            // size of this struct
                public string lpwszIdentity;  // identity name string
                public int nMaxResolve;       // number of desired resolutions
                public int dwTimeout;         // time in seconds to wait for responses
                public int dwLifetime;        // time in seconds for validity
                public PnrpResolveCriteria enResolveCriteria; // criteria for resolve matches
                public int dwFlags;           // set of flags
                public SOCKET_ADDRESS_NATIVE saHint; // IPv6 addr use for location
                public PnrpRegisteredIdState enNameState; // state of registered name
            }

            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
            internal struct PnrpInfo
            {
                public int dwSize;            // size of this struct
                public string lpwszIdentity;  // identity name string
                public int nMaxResolve;       // number of desired resolutions
                public int dwTimeout;         // time in seconds to wait for responses
                public int dwLifetime;        // time in seconds for validity
                public PnrpResolveCriteria enResolveCriteria; // criteria for resolve matches
                public int dwFlags;           // set of flags
                public SOCKET_ADDRESS_SAFE saHint; // IPv6 addr use for location
                public PnrpRegisteredIdState enNameState; // state of registered name
                public static void ToPnrpInfoNative(PnrpInfo source, ref PnrpInfoNative target)
                {
                    target.dwSize = source.dwSize;
                    target.lpwszIdentity = source.lpwszIdentity;
                    target.nMaxResolve = source.nMaxResolve;
                    target.dwTimeout = source.dwTimeout;
                    target.dwLifetime = source.dwLifetime;
                    target.enResolveCriteria = source.enResolveCriteria;
                    target.dwFlags = source.dwFlags;
                    if (source.saHint != null)
                    {
                        target.saHint.lpSockAddr = source.saHint.lpSockAddr;
                        target.saHint.iSockaddrLength = source.saHint.iSockaddrLength;
                    }
                    else
                    {
                        target.saHint.lpSockAddr = IntPtr.Zero;
                        target.saHint.iSockaddrLength = 0;
                    }
                    target.enNameState = source.enNameState;
                }
            }

            [Serializable]
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
            internal struct sockaddr_in
            {
                public short sin_family;
                public ushort sin_port;
                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
                public byte[] sin_addr;
                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
                public byte[] sin_zero;
            }

            [Serializable]
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
            internal struct sockaddr_in6
            {
                public short sin6_family;
                public ushort sin6_port;
                public uint sin6_flowinfo;
                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
                public byte[] sin6_addr;
                public uint sin6_scope_id;
            }

            internal class SOCKET_ADDRESS_SAFE : IDisposable
            {
                public CriticalAllocHandle lpSockAddr;
                public int iSockaddrLength;
                bool disposed;
                public static SOCKET_ADDRESS_SAFE SocketAddressFromIPEndPoint(IPEndPoint endpoint)
                {
                    SOCKET_ADDRESS_SAFE socketAddress = new SOCKET_ADDRESS_SAFE();
                    if (endpoint == null)
                        return socketAddress;

                    if (endpoint.AddressFamily == AddressFamily.InterNetwork)
                    {
                        socketAddress.iSockaddrLength = Marshal.SizeOf(typeof(sockaddr_in));
                        socketAddress.lpSockAddr = CriticalAllocHandle.FromSize(socketAddress.iSockaddrLength);
                        sockaddr_in sa = new sockaddr_in();
                        sa.sin_family = (short)AddressFamily.InterNetwork;
                        sa.sin_port = (ushort)endpoint.Port;
                        sa.sin_addr = endpoint.Address.GetAddressBytes();
                        Marshal.StructureToPtr(sa, (IntPtr)socketAddress.lpSockAddr, false);
                    }
                    else if (endpoint.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        socketAddress.iSockaddrLength = Marshal.SizeOf(typeof(sockaddr_in6));
                        socketAddress.lpSockAddr = CriticalAllocHandle.FromSize(socketAddress.iSockaddrLength);
                        sockaddr_in6 sa = new sockaddr_in6();
                        sa.sin6_family = (short)AddressFamily.InterNetworkV6;
                        sa.sin6_port = (ushort)endpoint.Port;
                        sa.sin6_addr = endpoint.Address.GetAddressBytes();
                        sa.sin6_scope_id = (uint)endpoint.Address.ScopeId;
                        Marshal.StructureToPtr(sa, (IntPtr)socketAddress.lpSockAddr, false);
                    }
                    return socketAddress;
                }

                ~SOCKET_ADDRESS_SAFE()
                {
                    Dispose(false);
                }

                public virtual void Dispose()
                {
                    Dispose(true);
                    GC.SuppressFinalize(this);
                }

                void Dispose(bool disposing)
                {
                    if (!disposed)
                    {
                        if (disposing)
                            lpSockAddr.Dispose();
                    }
                    disposed = true;
                }

            }

            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
            internal struct SOCKET_ADDRESS_NATIVE
            {
                public IntPtr lpSockAddr;
                public int iSockaddrLength;
            }

            [Serializable]
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
            internal struct WsaData
            {
                public Int16 wVersion;
                public Int16 wHighVersion;
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]
                public string szDescription;
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
                public string szSystemStatus;

                public Int16 iMaxSockets;
                public Int16 iMaxUdpDg;
                public IntPtr lpVendorInfo;
            }

            [Serializable]
            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
            internal struct WsaNamespaceInfo
            {
                public Guid NSProviderId;
                public int dwNameSpace;
                public int fActive;
                public int dwVersion;
                // don't bother marshalling this as a string since we don't need to look at it
                public IntPtr lpszIdentifier;
            }

            // managed equivalent of WSAQUERYSET
            internal class WsaQuerySet
            {
                public string ServiceInstanceName;
                public Guid ServiceClassId;
                public string Comment;
                public NspNamespaces NameSpace;
                public Guid NSProviderId;
                public string Context;
                public CsAddrInfo[] CsAddrInfos;
                public object Blob;
                static public WsaQuerySetSafe ToWsaQuerySetSafe(WsaQuerySet input)
                {

                    WsaQuerySetSafe result = new WsaQuerySetSafe();
                    if (input == null)
                        return result;

                    result.dwSize = Marshal.SizeOf(typeof(WsaQuerySetNative));
                    result.lpszServiceInstanceName = CriticalAllocHandleString.FromString(input.ServiceInstanceName);
                    result.lpServiceClassId = CriticalAllocHandleGuid.FromGuid(input.ServiceClassId);
                    result.lpszComment = CriticalAllocHandleString.FromString(input.Comment);
                    result.dwNameSpace = input.NameSpace;
                    result.lpNSProviderId = CriticalAllocHandleGuid.FromGuid(input.NSProviderId);
                    result.lpszContext = CriticalAllocHandleString.FromString(input.Context);
                    result.dwNumberOfProtocols = 0;
                    result.lpafpProtocols = IntPtr.Zero; // not used
                    result.lpszQueryString = IntPtr.Zero;

                    if (input.CsAddrInfos != null)
                    {
                        result.dwNumberOfCsAddrs = input.CsAddrInfos.Length;
                        result.addressList = CsAddrInfoSafe.FromAddresses(input.CsAddrInfos);
                    }
                    result.dwOutputFlags = 0;
                    result.lpBlob = CriticalAllocHandlePnrpBlob.FromPnrpBlob(input.Blob);

                    return result;
                }
            }

            internal class CriticalAllocHandlePnrpBlob : CriticalAllocHandle
            {
                public static CriticalAllocHandle FromPnrpBlob(object input)
                {
                    BlobSafe blob = new BlobSafe();
                    if (input != null)
                    {
                        if (input.GetType() == typeof(PnrpInfo))
                        {
                            int blobSize = Marshal.SizeOf(typeof(PnrpInfoNative));
                            blob.pBlobData = CriticalAllocHandle.FromSize(blobSize + Marshal.SizeOf(typeof(BlobNative)));

                            //write the BlobSafe fields first,
                            BlobNative nativeBlob;
                            nativeBlob.cbSize = blobSize;
                            nativeBlob.pBlobData = (IntPtr)(((IntPtr)blob.pBlobData).ToInt64() + Marshal.SizeOf(typeof(BlobNative)));
                            Marshal.StructureToPtr(nativeBlob, (IntPtr)blob.pBlobData, false);
                            PnrpInfo pnrpInfo = (PnrpInfo)input;
                            pnrpInfo.dwSize = blobSize;
                            PnrpInfoNative nativeInfo = new PnrpInfoNative();
                            PnrpInfo.ToPnrpInfoNative(pnrpInfo, ref nativeInfo);
                            Marshal.StructureToPtr(nativeInfo, (IntPtr)nativeBlob.pBlobData, false);
                            blob.cbSize = blobSize;
                        }
                        else if (input.GetType() == typeof(PnrpCloudInfo))
                        {
                            int blobSize = Marshal.SizeOf(input.GetType());
                            blob.pBlobData = CriticalAllocHandle.FromSize(blobSize + Marshal.SizeOf(typeof(BlobNative)));

                            //write the BlobSafe fields first,
                            BlobNative nativeBlob;
                            nativeBlob.cbSize = blobSize;
                            nativeBlob.pBlobData = (IntPtr)(((IntPtr)blob.pBlobData).ToInt64() + Marshal.SizeOf(typeof(BlobNative)));
                            Marshal.StructureToPtr(nativeBlob, (IntPtr)blob.pBlobData, false);
                            PnrpCloudInfo cloudInfo = (PnrpCloudInfo)input;
                            cloudInfo.dwSize = Marshal.SizeOf(typeof(PnrpCloudInfo));
                            Marshal.StructureToPtr(cloudInfo, (IntPtr)nativeBlob.pBlobData, false);
                            blob.cbSize = blobSize;
                        }
                        else
                        {
                            throw Fx.AssertAndThrow("Unknown payload type!");
                        }
                    }
                    return blob.pBlobData;

                }
            }

            internal class CriticalAllocHandleString : CriticalAllocHandle
            {
                public static CriticalAllocHandle FromString(string input)
                {
                    CriticalAllocHandleString result = new CriticalAllocHandleString();
                    RuntimeHelpers.PrepareConstrainedRegions();
                    try { }
                    finally
                    {
                        result.SetHandle(Marshal.StringToHGlobalUni(input));
                    }
                    return result;
                }
            }

            internal class CriticalAllocHandleWsaQuerySetSafe : CriticalAllocHandle
            {
                static int CalculateSize(WsaQuerySetSafe safeQuerySet)
                {
                    int structSize = Marshal.SizeOf(typeof(WsaQuerySetNative));
                    if (safeQuerySet.addressList != null)
                        structSize += safeQuerySet.addressList.Length * Marshal.SizeOf(typeof(CsAddrInfoNative));
                    return structSize;
                }

                public static CriticalAllocHandle FromWsaQuerySetSafe(WsaQuerySetSafe safeQuerySet)
                {
                    CriticalAllocHandle result = CriticalAllocHandle.FromSize(CalculateSize(safeQuerySet));
                    WsaQuerySetSafe.StructureToPtr(safeQuerySet, (IntPtr)result);
                    return result;
                }
            }

            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
            internal class WsaQuerySetSafe : IDisposable
            {
                public int dwSize;
                public CriticalAllocHandle lpszServiceInstanceName;
                public CriticalAllocHandle lpServiceClassId;
                public IntPtr lpVersion; // not used
                public CriticalAllocHandle lpszComment;
                public NspNamespaces dwNameSpace;
                public CriticalAllocHandle lpNSProviderId;
                public CriticalAllocHandle lpszContext;
                public int dwNumberOfProtocols; // 0
                public IntPtr lpafpProtocols; // not used
                public IntPtr lpszQueryString; // not used
                public int dwNumberOfCsAddrs;
                public CsAddrInfoSafe[] addressList;
                public int dwOutputFlags; // 0
                public CriticalAllocHandle lpBlob;
                bool disposed;

                ~WsaQuerySetSafe()
                {
                    Dispose(false);
                }

                public virtual void Dispose()
                {
                    Dispose(true);
                    GC.SuppressFinalize(this);
                }

                void Dispose(bool disposing)
                {
                    if (!disposed)
                    {
                        if (disposing)
                        {
                            if (lpszServiceInstanceName != null)
                                lpszServiceInstanceName.Dispose();
                            if (lpServiceClassId != null)
                                lpServiceClassId.Dispose();
                            if (lpszComment != null)
                                lpszComment.Dispose();
                            if (lpNSProviderId != null)
                                lpNSProviderId.Dispose();
                            if (lpBlob != null)
                                lpBlob.Dispose();
                            if (addressList != null)
                            {
                                foreach (CsAddrInfoSafe addr in addressList)
                                {
                                    addr.Dispose();
                                }
                            }
                        }
                    }
                    disposed = true;
                }

                static public void StructureToPtr(WsaQuerySetSafe input, IntPtr target)
                {
                    WsaQuerySetNative native = new WsaQuerySetNative();
                    native.dwSize = input.dwSize;
                    native.lpszServiceInstanceName = input.lpszServiceInstanceName;
                    native.lpServiceClassId = input.lpServiceClassId;
                    native.lpVersion = IntPtr.Zero; // not used
                    native.lpszComment = input.lpszComment;
                    native.dwNameSpace = input.dwNameSpace;
                    native.lpNSProviderId = input.lpNSProviderId;
                    native.lpszContext = input.lpszContext;
                    native.dwNumberOfProtocols = 0; // 0
                    native.lpafpProtocols = IntPtr.Zero; // not used
                    native.lpszQueryString = IntPtr.Zero; // not used
                    native.dwNumberOfCsAddrs = input.dwNumberOfCsAddrs;
                    native.dwOutputFlags = 0; // 0
                    native.lpBlob = input.lpBlob;

                    Int64 sockAddressStart = target.ToInt64() + Marshal.SizeOf(typeof(WsaQuerySetNative));
                    native.lpcsaBuffer = (IntPtr)sockAddressStart;

                    Marshal.StructureToPtr(native, target, false);
                    MarshalSafeAddressesToNative(input, (IntPtr)sockAddressStart);

                }

                public static void MarshalSafeAddressesToNative(WsaQuerySetSafe safeQuery, IntPtr target)
                {
                    // marshal the addresses
                    if (safeQuery.addressList != null && safeQuery.addressList.Length > 0)
                    {
                        int sizeOfCsAddrInfo = Marshal.SizeOf(typeof(CsAddrInfoNative));
                        Int64 start = target.ToInt64();
                        Fx.Assert(start % IntPtr.Size == 0, "Invalid alignment!!");
                        foreach (CsAddrInfoSafe safeAddress in safeQuery.addressList)
                        {
                            CsAddrInfoSafe.StructureToPtr(safeAddress, (IntPtr)start);
                            start += sizeOfCsAddrInfo;
                        }
                    }
                }

            }

            [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
            internal struct WsaQuerySetNative
            {
                public int dwSize;
                public IntPtr lpszServiceInstanceName;
                public IntPtr lpServiceClassId;
                public IntPtr lpVersion; // not used
                public IntPtr lpszComment;
                public NspNamespaces dwNameSpace;
                public IntPtr lpNSProviderId;
                public IntPtr lpszContext;
                public int dwNumberOfProtocols; // 0
                public IntPtr lpafpProtocols; // not used
                public IntPtr lpszQueryString; // not used
                public int dwNumberOfCsAddrs;
                public IntPtr lpcsaBuffer;
                public int dwOutputFlags; // 0
                public IntPtr lpBlob;
            }

            internal class CriticalLookupHandle : CriticalHandleZeroOrMinusOneIsInvalid
            {
                protected override bool ReleaseHandle()
                {
                    return WSALookupServiceEnd(handle) == 0;
                }
            }

            // base class for ref-counting WSA uses and calling WSAStartup/WSAShutdown
            internal class DiscoveryBase : MarshalByRefObject, IDisposable
            {
                static int refCount = 0;
                static object refCountLock = new object();
                bool disposed;

                public DiscoveryBase()
                {
                    lock (refCountLock)
                    {
                        if (refCount == 0)
                        {
                            WsaData WinsockVersion = new WsaData();
                            int ret = WSAStartup(UnsafePnrpNativeMethods.RequiredWinsockVersion, ref WinsockVersion);
                            if (ret != 0)
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SocketException(ret));
                            }
                        }
                        refCount++;
                    }
                }

                public void Dispose()
                {
                    Dispose(true);
                    GC.SuppressFinalize(this);
                }

                public void Dispose(bool disposing)
                {
                    if (!disposed)
                    {
                        lock (refCountLock)
                        {
                            refCount--;
                            if (refCount == 0)
                            {
                                WSACleanup();
                            }
                        }
                    }
                    disposed = true;
                }

                ~DiscoveryBase()
                {
                    this.Dispose(false);
                }

                [SuppressMessage(FxCop.Category.Security, FxCop.Rule.AptcaMethodsShouldOnlyCallAptcaMethods, Justification = "ServiceController has demands for ServiceControllerPermission.")]
                public bool IsPnrpServiceRunning(TimeSpan waitForService)
                {
                    TimeoutHelper timeoutHelper = new TimeoutHelper(waitForService);
                    try
                    {
                        using (ServiceController sc = new ServiceController("pnrpsvc"))
                        {
                            try
                            {
                                if (sc.Status == ServiceControllerStatus.StopPending)
                                {
                                    sc.WaitForStatus(ServiceControllerStatus.Stopped, timeoutHelper.RemainingTime());
                                }
                                if (sc.Status == ServiceControllerStatus.Stopped)
                                {
                                    sc.Start();
                                }
                                sc.WaitForStatus(ServiceControllerStatus.Running, timeoutHelper.RemainingTime());
                            }
                            catch (Exception e)
                            {
                                if (Fx.IsFatal(e)) throw;
                                if (e is InvalidOperationException || e is TimeoutException)
                                    return false;
                                else
                                    throw;
                            }
                            return (sc.Status == ServiceControllerStatus.Running);
                        }
                    }
                    catch (InvalidOperationException e)
                    {
                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                        Fx.Assert("IsPnrpServiceRunning should be called after IsPnrpInstalled");
                        return false;
                    }
                }

                public bool IsPnrpAvailable(TimeSpan waitForService)
                {
                    if (!IsPnrpInstalled())
                        return false;

                    //make sure that the service is running
                    if (!IsPnrpServiceRunning(waitForService))
                        return false;
                    // If PNRP is installed, ensure that it supports extended payload by attempting to register with
                    // an invalid query set. If extended payload is not available, "WSASERVICE_NOT_FOUND" is returned.
                    // Otherwise, "WSAEINVAL" is returned.

                    //UPDATE: we will work with PNRP 1.0 if it is available.
                    // a separate implementation will work with payload support when available.
                    WsaQuerySet querySet = new WsaQuerySet();
                    querySet.NSProviderId = NsProviderName;
                    querySet.ServiceClassId = SvcIdNameV1;
                    int res = InvokeService(querySet, WsaSetServiceOp.Register, 0);

                    //on xp 64bit, WSANO_DATA is returned
                    if (res == (int)WsaError.WSAEINVAL || res == (int)WsaError.WSANO_DATA)
                        return true;

                    // if the call didn't fail or returned any other error, PNRP clearly isn't working properly
                    return false;

                }

                // determine if any version of PNRP is installed and available
                public bool IsPnrpInstalled()
                {
                    int size = 0;
                    int nProviders;
                    CriticalAllocHandle dataPtr = null;
                    // retrieve the list of installed namespace providers
                    // implemented in a loop in case the size changes between the first and second calls
                    while (true)
                    {
                        nProviders = WSAEnumNameSpaceProviders(ref size, (IntPtr)dataPtr);
                        if (nProviders != -1) // success
                            break;

                        int error = WSAGetLastError();
                        if (error != (int)WsaError.WSAEFAULT) // buffer length to small
                            return false; // any other error effectively means that PNRP isn't usable

                        dataPtr = CriticalAllocHandle.FromSize(size);
                    }

                    // loop through the providers
                    for (int i = 0; i < nProviders; i++)
                    {
                        IntPtr nsInfoPtr = (IntPtr)(((IntPtr)dataPtr).ToInt64() + i *
                            Marshal.SizeOf(typeof(WsaNamespaceInfo)));
                        WsaNamespaceInfo nsInfo = (WsaNamespaceInfo)Marshal.PtrToStructure(nsInfoPtr,
                            typeof(WsaNamespaceInfo));

                        // if this is the PNRP name namespace provider and it is active, it is installed
                        if (nsInfo.NSProviderId == NsProviderName && nsInfo.fActive != 0)
                            return true;
                    }

                    // no PNRP name namespace provider found
                    return false;
                }

                int InvokeService(WsaQuerySet registerQuery, WsaSetServiceOp op, int flags)
                {
                    WsaQuerySetSafe native = WsaQuerySet.ToWsaQuerySetSafe(registerQuery);
                    int error = 0;
                    using (native)
                    {
                        CriticalAllocHandle handle = CriticalAllocHandleWsaQuerySetSafe.FromWsaQuerySetSafe(native);
                        using (handle)
                        {
                            int retval = WSASetService(handle, op, flags);
                            if (retval != 0)
                            {
                                error = WSAGetLastError();
                            }
                        }
                    }
                    return error;
                }

            }

            public class PeerCloudEnumerator : DiscoveryBase
            {
                static public CloudInfo[] GetClouds()
                {
                    int retval = 0;
                    ArrayList clouds = new ArrayList();
                    WsaQuerySet querySet = new WsaQuerySet();
                    CriticalLookupHandle hLookup;

                    PnrpCloudInfo cloudInfo = new PnrpCloudInfo();
                    cloudInfo.dwSize = Marshal.SizeOf(typeof(PnrpCloudInfo));
                    cloudInfo.Cloud.Scope = PnrpScope.Any;
                    cloudInfo.dwCloudState = (PnrpCloudState)0;
                    cloudInfo.Flags = PnrpCloudFlags.None;
                    querySet.NameSpace = NspNamespaces.Cloud;
                    querySet.NSProviderId = NsProviderCloud;
                    querySet.ServiceClassId = SvcIdCloud;
                    querySet.Blob = cloudInfo;

                    WsaQuerySetSafe native = WsaQuerySet.ToWsaQuerySetSafe(querySet);
                    using (native)
                    {
                        CriticalAllocHandle handle = CriticalAllocHandleWsaQuerySetSafe.FromWsaQuerySetSafe(native);
                        retval = WSALookupServiceBegin(handle, WsaNspControlFlags.ReturnAll, out hLookup);
                    }
                    if (retval != 0)
                    {
                        // unable to start the enumeration
                        SocketException exception = new SocketException(WSAGetLastError());
                        Utility.CloseInvalidOutCriticalHandle(hLookup);
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception);
                    }

                    // start with a sensible default size
                    int size = Marshal.SizeOf(typeof(WsaQuerySetSafe)) + 200;
                    //wrap in CriticalAllocHandle when PAYLOAD is enabled
                    CriticalAllocHandle nativeQuerySetPtr = CriticalAllocHandle.FromSize(size);
                    using (hLookup)
                    {
                        while (true)
                        {
                            retval = WSALookupServiceNext(hLookup, 0, ref size, (IntPtr)nativeQuerySetPtr);
                            if (retval != 0)
                            {
                                int error = WSAGetLastError();
                                if (error == (int)WsaError.WSAENOMORE || error == (int)WsaError.WSA_E_NO_MORE)
                                {
                                    // no more
                                    break;
                                }
                                if (error == (int)WsaError.WSAEFAULT)
                                {
                                    // buffer too small, allocate a bigger one of the specified size
                                    if (nativeQuerySetPtr != null)
                                    {
                                        nativeQuerySetPtr.Dispose();
                                        nativeQuerySetPtr = null;
                                    }
                                    //wrap in CriticalAllocHandle when PAYLOAD is enabled
                                    nativeQuerySetPtr = CriticalAllocHandle.FromSize(size);
                                    continue;
                                }

                                // unexpected error
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SocketException(error));
                            }
                            else
                            {
                                if (nativeQuerySetPtr != IntPtr.Zero)
                                {
                                    // marshal the results into something usable
                                    WsaQuerySet resultQuerySet = PeerNameResolver.MarshalWsaQuerySetNativeToWsaQuerySet(nativeQuerySetPtr, 0);
                                    // extract out the friendly cloud attributes
                                    CloudInfo resultCloudInfo = new CloudInfo();
                                    PnrpCloudInfo prnpCloudInfo = (PnrpCloudInfo)resultQuerySet.Blob;
                                    resultCloudInfo.Name = resultQuerySet.ServiceInstanceName;
                                    resultCloudInfo.Scope = prnpCloudInfo.Cloud.Scope;
                                    resultCloudInfo.ScopeId = prnpCloudInfo.Cloud.ScopeId;
                                    resultCloudInfo.State = prnpCloudInfo.dwCloudState;
                                    resultCloudInfo.Flags = prnpCloudInfo.Flags;

                                    // add it to the list to return later
                                    clouds.Add(resultCloudInfo);
                                }
                            }
                        }
                    }

                    // package up the results into a nice array
                    return (CloudInfo[])clouds.ToArray(typeof(CloudInfo));
                }

            }

            internal class PeerNameRegistrar : DiscoveryBase
            {
                const int RegistrationLifetime = 60 * 60; // 1 hour

                public PeerNameRegistrar()
                    : base()
                {
                }

                public void Register(PnrpRegistration registration, TimeSpan timeout)
                {
                    // fill in the PnrpInfo blob using the defaults
                    PnrpInfo pnrpInfo = new PnrpInfo();
                    pnrpInfo.dwLifetime = RegistrationLifetime;
                    pnrpInfo.lpwszIdentity = null;
                    pnrpInfo.dwSize = Marshal.SizeOf(pnrpInfo);
                    pnrpInfo.dwFlags = PNRPINFO_HINT;
                    IPEndPoint hint = PnrpPeerResolver.GetHint();
                    pnrpInfo.saHint = SOCKET_ADDRESS_SAFE.SocketAddressFromIPEndPoint(hint);

                    // fill in the query set
                    WsaQuerySet registerQuery = new WsaQuerySet();
                    registerQuery.NameSpace = NspNamespaces.Name;
                    registerQuery.NSProviderId = NsProviderName;
                    registerQuery.ServiceClassId = SvcIdNameV1;
                    registerQuery.ServiceInstanceName = registration.PeerName;
                    registerQuery.Comment = registration.Comment;
                    registerQuery.Context = registration.CloudName;

                    // copy over the addresses
                    if (registration.Addresses != null)
                    {
                        Fx.Assert(registration.Addresses.Length <= 4, "Pnrp supports only 4 addresses");
                        registerQuery.CsAddrInfos = new CsAddrInfo[registration.Addresses.Length];
                        for (int i = 0; i < registration.Addresses.Length; i++)
                        {
                            // the only interesting part of the CsAddrInfo is the LocalAddress
                            registerQuery.CsAddrInfos[i].LocalAddr = registration.Addresses[i];
                            registerQuery.CsAddrInfos[i].iProtocol = (int)ProtocolType.Tcp;
                            registerQuery.CsAddrInfos[i].iSocketType = (int)SocketType.Stream;
                        }
                    }

                    // copy the blob
                    registerQuery.Blob = pnrpInfo;
                    RegisterService(registerQuery);
                }

                public void Unregister(string peerName, List<string> clouds, TimeSpan timeout)
                {
                    TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                    foreach (string cloud in clouds)
                    {
                        try
                        {
                            Unregister(peerName, cloud, timeoutHelper.RemainingTime());
                        }
                        catch (SocketException e)
                        {
                            DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                        }
                    }
                }

                public void Unregister(string peerName, string cloudName, TimeSpan timeout)
                {
                    // fill in the PnrpInfo with defaults
                    PnrpInfo identityInfo = new PnrpInfo();
                    identityInfo.lpwszIdentity = null;
                    identityInfo.dwSize = Marshal.SizeOf(typeof(PnrpInfo));

                    // fill in the query set
                    WsaQuerySet registerQuery = new WsaQuerySet();
                    registerQuery.NameSpace = NspNamespaces.Name;
                    registerQuery.NSProviderId = NsProviderName;
                    registerQuery.ServiceClassId = SvcIdNameV1;
                    registerQuery.ServiceInstanceName = peerName;
                    registerQuery.Context = cloudName;
                    registerQuery.Blob = identityInfo;

                    DeleteService(registerQuery);
                }

                void RegisterService(WsaQuerySet registerQuery)
                {
                    try
                    {
                        InvokeService(registerQuery, WsaSetServiceOp.Register, 0);
                    }
                    catch (PnrpException)
                    {
                        if (PnrpPeerResolver.MaxAddressEntriesV1 < registerQuery.CsAddrInfos.Length)
                        {
                            List<CsAddrInfo> infos = new List<CsAddrInfo>(registerQuery.CsAddrInfos);
                            infos.RemoveRange(PnrpPeerResolver.MaxAddressEntriesV1, registerQuery.CsAddrInfos.Length - PnrpPeerResolver.MaxAddressEntriesV1);
                            registerQuery.CsAddrInfos = infos.ToArray();
                            InvokeService(registerQuery, WsaSetServiceOp.Register, 0);
                        }
                        else
                            throw;
                    }
                }

                void DeleteService(WsaQuerySet registerQuery)
                {
                    InvokeService(registerQuery, WsaSetServiceOp.Delete, 0);
                }

                static void InvokeService(WsaQuerySet registerQuery, WsaSetServiceOp op, int flags)
                {
                    WsaQuerySetSafe native = WsaQuerySet.ToWsaQuerySetSafe(registerQuery);
                    using (native)
                    {
                        CriticalAllocHandle handle = CriticalAllocHandleWsaQuerySetSafe.FromWsaQuerySetSafe(native);
                        int retval = WSASetService(handle, op, flags);
                        if (retval != 0)
                        {
                            int error = WSAGetLastError();
                            PeerExceptionHelper.ThrowPnrpError(error, registerQuery.Context);
                        }
                    }
                }
            }

            internal class PeerNameResolver : AsyncResult
            {
                WsaQuerySet resolveQuery;
                List<PnrpRegistration> results;
                uint scopeId;
                Exception lastException;
                TimeoutHelper timeoutHelper;

                public PeerNameResolver(string peerName, int numberOfResultsRequested,
                    PnrpResolveCriteria resolveCriteria, TimeSpan timeout, List<PnrpRegistration> results)
                    : this(peerName, numberOfResultsRequested, resolveCriteria, 0, GlobalCloudName, timeout, results)
                {
                }

                public PeerNameResolver(string peerName, int numberOfResultsRequested,
                    PnrpResolveCriteria resolveCriteria, uint scopeId, string cloudName, TimeSpan timeout, List<PnrpRegistration> results)
                    : base(null, null)
                {
                    // pnrp has a hard-coded limit on the timeout value that can be passed to it
                    // maximum value is 10 minutes
                    if (timeout > MaxTimeout)
                    {
                        timeout = MaxTimeout;
                    }
                    timeoutHelper = new TimeoutHelper(timeout);
                    PnrpInfo resolveQueryInfo = new PnrpInfo();
                    resolveQueryInfo.dwSize = Marshal.SizeOf(typeof(PnrpInfo));
                    resolveQueryInfo.nMaxResolve = numberOfResultsRequested;
                    resolveQueryInfo.dwTimeout = (int)timeout.TotalSeconds;
                    resolveQueryInfo.dwLifetime = 0;
                    resolveQueryInfo.enNameState = 0;
                    resolveQueryInfo.lpwszIdentity = null;
                    resolveQueryInfo.dwFlags = PNRPINFO_HINT;
                    IPEndPoint hint = PnrpPeerResolver.GetHint();
                    resolveQueryInfo.enResolveCriteria = resolveCriteria;
                    resolveQueryInfo.saHint = SOCKET_ADDRESS_SAFE.SocketAddressFromIPEndPoint(hint);
                    resolveQuery = new WsaQuerySet();
                    resolveQuery.ServiceInstanceName = peerName;
                    resolveQuery.ServiceClassId = SvcIdNameV1;
                    resolveQuery.NameSpace = NspNamespaces.Name;
                    resolveQuery.NSProviderId = NsProviderName;
                    resolveQuery.Context = cloudName;
                    resolveQuery.Blob = resolveQueryInfo;
                    this.results = results;
                    this.scopeId = scopeId;
                    ActionItem.Schedule(new Action<object>(SyncEnumeration), null);
                }

                public void End()
                {
                    AsyncResult.End<PeerNameResolver>(this);
                }

                public void SyncEnumeration(object state)
                {
                    int retval = 0;
                    CriticalLookupHandle hLookup;
                    WsaQuerySetSafe native = WsaQuerySet.ToWsaQuerySetSafe(resolveQuery);
                    using (native)
                    {
                        CriticalAllocHandle handle = CriticalAllocHandleWsaQuerySetSafe.FromWsaQuerySetSafe(native);
                        retval = WSALookupServiceBegin(handle, WsaNspControlFlags.ReturnAll, out hLookup);
                    }
                    if (retval != 0)
                    {
                        lastException = new PnrpException(WSAGetLastError(), resolveQuery.Context);
                        Utility.CloseInvalidOutCriticalHandle(hLookup);
                        Complete(false, lastException);
                        return;
                    }
                    WsaQuerySet querySet = new WsaQuerySet();

                    // start with a sensible default size
                    int size = Marshal.SizeOf(typeof(WsaQuerySetSafe)) + 400;
                    CriticalAllocHandle nativeQuerySetPtr = CriticalAllocHandle.FromSize(size);
                    try
                    {
                        using (hLookup)
                        {
                            while (true)
                            {
                                if (timeoutHelper.RemainingTime() == TimeSpan.Zero)
                                {
                                    break;
                                }
                                retval = WSALookupServiceNext(hLookup, 0, ref size, (IntPtr)nativeQuerySetPtr);
                                if (retval != 0)
                                {
                                    int error = WSAGetLastError();
                                    if (error == (int)WsaError.WSAENOMORE || error == (int)WsaError.WSA_E_NO_MORE)
                                    {
                                        // no more
                                        break;
                                    }

                                    if (error == (int)WsaError.WSAEFAULT)
                                    {
                                        nativeQuerySetPtr = CriticalAllocHandle.FromSize(size);
                                        continue;
                                    }

                                    // unexpected error
                                    PeerExceptionHelper.ThrowPnrpError(error, querySet.Context);
                                }
                                else
                                {
                                    if (nativeQuerySetPtr != IntPtr.Zero)
                                    {
                                        // marshal the results into something useful
                                        querySet = MarshalWsaQuerySetNativeToWsaQuerySet(nativeQuerySetPtr, scopeId);

                                        // allocate the friendly PnrpRegistration and fill it in
                                        PnrpRegistration pnrpRegistration = new PnrpRegistration();
                                        pnrpRegistration.CloudName = querySet.Context;
                                        pnrpRegistration.Comment = querySet.Comment;
                                        pnrpRegistration.PeerName = querySet.ServiceInstanceName;
                                        pnrpRegistration.Addresses = new IPEndPoint[querySet.CsAddrInfos.Length];
                                        for (int i = 0; i < querySet.CsAddrInfos.Length; i++)
                                            pnrpRegistration.Addresses[i] = querySet.CsAddrInfos[i].LocalAddr;

                                        // add it to the list to return later.
                                        // all cloud enumeratos in the same scope will reference the same list and hence the lock.
                                        lock (results)
                                        {
                                            results.Add(pnrpRegistration);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e)) throw;
                        DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
                        if (DiagnosticUtility.ShouldTraceInformation)
                        {
                            PnrpResolveExceptionTraceRecord record = new PnrpResolveExceptionTraceRecord(resolveQuery.ServiceInstanceName, resolveQuery.Context, e);
                            if (DiagnosticUtility.ShouldTraceError)
                            {
                                TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.PnrpResolveException,
                                    SR.GetString(SR.TraceCodePnrpResolveException), record, this, null);
                            }
                        }
                        lastException = e;
                    }
                    finally
                    {
                        Complete(false, lastException);
                    }
                }

                static internal WsaQuerySet MarshalWsaQuerySetNativeToWsaQuerySet(IntPtr pNativeData)
                {
                    return MarshalWsaQuerySetNativeToWsaQuerySet(pNativeData, 0);
                }

                static internal WsaQuerySet MarshalWsaQuerySetNativeToWsaQuerySet(IntPtr pNativeData, uint scopeId)
                {
                    if (pNativeData == IntPtr.Zero)
                        return null;

                    WsaQuerySet querySet = new WsaQuerySet();
                    // build a native structure from the raw memory
                    WsaQuerySetNative nativeQuerySet;
                    nativeQuerySet = (WsaQuerySetNative)Marshal.PtrToStructure(pNativeData,
                        typeof(WsaQuerySetNative));
                    CsAddrInfoNative nativeCsAddrInfo;
                    int sizeOfCsAddrInfo = Marshal.SizeOf(typeof(CsAddrInfoNative));

                    // copy over the simple fields
                    querySet.Context = Marshal.PtrToStringUni(nativeQuerySet.lpszContext);
                    querySet.NameSpace = nativeQuerySet.dwNameSpace;
                    querySet.ServiceInstanceName = Marshal.PtrToStringUni(nativeQuerySet.lpszServiceInstanceName);
                    querySet.Comment = Marshal.PtrToStringUni(nativeQuerySet.lpszComment);

                    // copy the addresses
                    querySet.CsAddrInfos = new CsAddrInfo[nativeQuerySet.dwNumberOfCsAddrs];
                    for (int i = 0; i < nativeQuerySet.dwNumberOfCsAddrs; i++)
                    {
                        IntPtr addressPtr = (IntPtr)(nativeQuerySet.lpcsaBuffer.ToInt64() + (i * sizeOfCsAddrInfo));
                        nativeCsAddrInfo = (CsAddrInfoNative)Marshal.PtrToStructure(addressPtr,
                            typeof(CsAddrInfoNative));
                        querySet.CsAddrInfos[i].iProtocol = nativeCsAddrInfo.iProtocol;
                        querySet.CsAddrInfos[i].iSocketType = nativeCsAddrInfo.iSocketType;
                        querySet.CsAddrInfos[i].LocalAddr = IPEndPointFromSocketAddress(nativeCsAddrInfo.LocalAddr, scopeId);
                        querySet.CsAddrInfos[i].RemoteAddr = IPEndPointFromSocketAddress(nativeCsAddrInfo.RemoteAddr, scopeId);
                    }

                    // copy the GUIDs
                    if (nativeQuerySet.lpNSProviderId != IntPtr.Zero)
                        querySet.NSProviderId = (Guid)Marshal.PtrToStructure(nativeQuerySet.lpNSProviderId,
                            typeof(Guid));

                    if (nativeQuerySet.lpServiceClassId != IntPtr.Zero)
                        querySet.ServiceClassId = (Guid)Marshal.PtrToStructure(nativeQuerySet.lpServiceClassId,
                            typeof(Guid));

                    // marshal the BLOB according to namespace
                    if (querySet.NameSpace == NspNamespaces.Cloud)
                    {
                        if (nativeQuerySet.lpBlob != IntPtr.Zero)
                        {
                            // give it a default value
                            querySet.Blob = new PnrpCloudInfo();
                            // marshal the blob in order to get the pointer
                            BlobNative blob = (BlobNative)Marshal.PtrToStructure(nativeQuerySet.lpBlob, typeof(BlobNative));
                            // marshal the actual PnrpCloudInfo
                            if (blob.pBlobData != IntPtr.Zero)
                                querySet.Blob = (PnrpCloudInfo)Marshal.PtrToStructure(blob.pBlobData,
                                    typeof(PnrpCloudInfo));
                        }
                    }

                    else if (querySet.NameSpace == NspNamespaces.Name)
                    {
                        if (nativeQuerySet.lpBlob != IntPtr.Zero)
                        {
                            // give it a default value
                            querySet.Blob = new PnrpInfo();
                            // marshal the blob in order to get the pointer
                            BlobSafe blob = (BlobSafe)Marshal.PtrToStructure(nativeQuerySet.lpBlob, typeof(BlobSafe));
                            // marshal the actual PnrpInfo
                            if (blob.pBlobData != IntPtr.Zero)
                            {
                                PnrpInfo pnrpInfo = (PnrpInfo)Marshal.PtrToStructure(blob.pBlobData,
                                    typeof(PnrpInfo));
                                querySet.Blob = pnrpInfo;
                            }
                        }
                    }

                    return querySet;
                }

                static IPEndPoint IPEndPointFromSocketAddress(SOCKET_ADDRESS_NATIVE socketAddress, uint scopeId)
                {
                    IPEndPoint endPoint = null;
                    if (socketAddress.lpSockAddr != IntPtr.Zero)
                    {
                        AddressFamily addressFamily = (AddressFamily)Marshal.ReadInt16(socketAddress.lpSockAddr);
                        if (addressFamily == AddressFamily.InterNetwork)
                        {
                            // if the sockaddr length is not the sizeof(sockaddr_in), the data is invalid so
                            // return an null endpoint
                            if (socketAddress.iSockaddrLength == Marshal.SizeOf(typeof(sockaddr_in)))
                            {
                                sockaddr_in sa = (sockaddr_in)Marshal.PtrToStructure(socketAddress.lpSockAddr,
                                    typeof(sockaddr_in));
                                endPoint = new IPEndPoint(new IPAddress(sa.sin_addr), sa.sin_port);
                            }
                        }
                        else if (addressFamily == AddressFamily.InterNetworkV6)
                        {
                            // if the sockaddr length is not the sizeof(sockaddr_in6), the data is invalid so
                            // return an null endpoint
                            if (socketAddress.iSockaddrLength == Marshal.SizeOf(typeof(sockaddr_in6)))
                            {
                                sockaddr_in6 sa = (sockaddr_in6)Marshal.PtrToStructure(socketAddress.lpSockAddr,
                                    typeof(sockaddr_in6));
                                if (scopeId != 0 && sa.sin6_scope_id != 0)
                                    scopeId = sa.sin6_scope_id;
                                endPoint = new IPEndPoint(new IPAddress(sa.sin6_addr, scopeId), sa.sin6_port);
                            }
                        }
                        // else this is an unknown address family, so return null
                    }

                    return endPoint;
                }

            }
        }
        public override bool Equals(object other)
        {
            return ((other as PnrpPeerResolver) != null);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

    }
}