summaryrefslogtreecommitdiff
path: root/nsprpub/pr/src/io/prsocket.c
blob: e0f917c16a6b90a527ea09b7c527b3ffe3a9b5bd (plain)
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "primpl.h"

#include <string.h>

#if defined(_WIN64)
#ifndef SO_UPDATE_CONNECT_CONTEXT
#define SO_UPDATE_CONNECT_CONTEXT 0x7010
#endif
#endif

/************************************************************************/

/* These two functions are only used in assertions. */
#if defined(DEBUG)

PRBool IsValidNetAddr(const PRNetAddr *addr)
{
    if ((addr != NULL)
#if defined(XP_UNIX) || defined(XP_OS2)
        && (addr->raw.family != PR_AF_LOCAL)
#endif
        && (addr->raw.family != PR_AF_INET6)
        && (addr->raw.family != PR_AF_INET)) {
        return PR_FALSE;
    }
    return PR_TRUE;
}

static PRBool IsValidNetAddrLen(const PRNetAddr *addr, PRInt32 addr_len)
{
    /*
     * The definition of the length of a Unix domain socket address
     * is not uniform, so we don't check it.
     */
    if ((addr != NULL)
#if defined(XP_UNIX) || defined(XP_OS2)
        && (addr->raw.family != AF_UNIX)
#endif
        && (PR_NETADDR_SIZE(addr) != addr_len)) {
#if defined(LINUX) && __GLIBC__ == 2 && __GLIBC_MINOR__ == 1
        /*
         * In glibc 2.1, struct sockaddr_in6 is 24 bytes.  In glibc 2.2
         * and in the 2.4 kernel, struct sockaddr_in6 has the scope_id
         * field and is 28 bytes.  It is possible for socket functions
         * to return an addr_len greater than sizeof(struct sockaddr_in6).
         * We need to allow that.  (Bugzilla bug #77264)
         */
        if ((PR_AF_INET6 == addr->raw.family)
            && (sizeof(addr->ipv6) == addr_len)) {
            return PR_TRUE;
        }
#endif
        /*
         * The accept(), getsockname(), etc. calls on some platforms
         * do not set the actual socket address length on return.
         * In this case, we verifiy addr_len is still the value we
         * passed in (i.e., sizeof(PRNetAddr)).
         */
#if defined(QNX)
        if (sizeof(PRNetAddr) == addr_len) {
            return PR_TRUE;
        }
#endif
        return PR_FALSE;
    }
    return PR_TRUE;
}

#endif /* DEBUG */

static PRInt32 PR_CALLBACK SocketWritev(PRFileDesc *fd, const PRIOVec *iov,
                                        PRInt32 iov_size, PRIntervalTime timeout)
{
    PRThread *me = _PR_MD_CURRENT_THREAD();
    int w = 0;
    const PRIOVec *tmp_iov;
#define LOCAL_MAXIOV    8
    PRIOVec local_iov[LOCAL_MAXIOV];
    PRIOVec *iov_copy = NULL;
    int tmp_out;
    int index, iov_cnt;
    int count=0, sz = 0;    /* 'count' is the return value. */

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return -1;
    }
    if (_PR_IO_PENDING(me)) {
        PR_SetError(PR_IO_PENDING_ERROR, 0);
        return -1;
    }

    /*
     * Assume the first writev will succeed.  Copy iov's only on
     * failure.
     */
    tmp_iov = iov;
    for (index = 0; index < iov_size; index++) {
        sz += iov[index].iov_len;
    }

    iov_cnt = iov_size;

    while (sz > 0) {

        w = _PR_MD_WRITEV(fd, tmp_iov, iov_cnt, timeout);
        if (w < 0) {
            count = -1;
            break;
        }
        count += w;
        if (fd->secret->nonblocking) {
            break;
        }
        sz -= w;

        if (sz > 0) {
            /* find the next unwritten vector */
            for ( index = 0, tmp_out = count;
                  tmp_out >= iov[index].iov_len;
                  tmp_out -= iov[index].iov_len, index++) {;} /* nothing to execute */

            if (tmp_iov == iov) {
                /*
                 * The first writev failed so we
                 * must copy iov's around.
                 * Avoid calloc/free if there
                 * are few enough iov's.
                 */
                if (iov_size - index <= LOCAL_MAXIOV) {
                    iov_copy = local_iov;
                }
                else if ((iov_copy = (PRIOVec *) PR_CALLOC((iov_size - index) *
                                     sizeof *iov_copy)) == NULL) {
                    PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
                    return -1;
                }
                tmp_iov = iov_copy;
            }

            PR_ASSERT(tmp_iov == iov_copy);

            /* fill in the first partial read */
            iov_copy[0].iov_base = &(((char *)iov[index].iov_base)[tmp_out]);
            iov_copy[0].iov_len = iov[index].iov_len - tmp_out;
            index++;

            /* copy the remaining vectors */
            for (iov_cnt=1; index<iov_size; iov_cnt++, index++) {
                iov_copy[iov_cnt].iov_base = iov[index].iov_base;
                iov_copy[iov_cnt].iov_len = iov[index].iov_len;
            }
        }
    }

    if (iov_copy != local_iov) {
        PR_DELETE(iov_copy);
    }
    return count;
}

/************************************************************************/

PR_IMPLEMENT(PRFileDesc *) PR_ImportTCPSocket(PROsfd osfd)
{
    PRFileDesc *fd;

    if (!_pr_initialized) {
        _PR_ImplicitInitialization();
    }
    fd = PR_AllocFileDesc(osfd, PR_GetTCPMethods());
    if (fd != NULL) {
        _PR_MD_MAKE_NONBLOCK(fd);
        _PR_MD_INIT_FD_INHERITABLE(fd, PR_TRUE);
#ifdef _PR_NEED_SECRET_AF
        /* this means we can only import IPv4 sockets here.
         * but this is what the function in ptio.c does.
         * We need a way to import IPv6 sockets, too.
         */
        fd->secret->af = AF_INET;
#endif
    } else {
        _PR_MD_CLOSE_SOCKET(osfd);
    }
    return(fd);
}

PR_IMPLEMENT(PRFileDesc *) PR_ImportUDPSocket(PROsfd osfd)
{
    PRFileDesc *fd;

    if (!_pr_initialized) {
        _PR_ImplicitInitialization();
    }
    fd = PR_AllocFileDesc(osfd, PR_GetUDPMethods());
    if (fd != NULL) {
        _PR_MD_MAKE_NONBLOCK(fd);
        _PR_MD_INIT_FD_INHERITABLE(fd, PR_TRUE);
    } else {
        _PR_MD_CLOSE_SOCKET(osfd);
    }
    return(fd);
}


static const PRIOMethods* PR_GetSocketPollFdMethods(void);

PR_IMPLEMENT(PRFileDesc*) PR_CreateSocketPollFd(PROsfd osfd)
{
    PRFileDesc *fd;

    if (!_pr_initialized) {
        _PR_ImplicitInitialization();
    }

    fd = _PR_Getfd();

    if (fd == NULL) {
        PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
    }
    else
    {
        fd->secret->md.osfd = osfd;
        fd->secret->inheritable = _PR_TRI_FALSE;
        fd->secret->state = _PR_FILEDESC_OPEN;
        fd->methods = PR_GetSocketPollFdMethods();
    }

    return fd;
}  /* PR_CreateSocketPollFD */

PR_IMPLEMENT(PRStatus) PR_DestroySocketPollFd(PRFileDesc *fd)
{
    if (NULL == fd)
    {
        PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
        return PR_FAILURE;
    }
    fd->secret->state = _PR_FILEDESC_CLOSED;
    _PR_Putfd(fd);
    return PR_SUCCESS;
}  /* PR_DestroySocketPollFd */

static PRStatus PR_CALLBACK SocketConnect(
    PRFileDesc *fd, const PRNetAddr *addr, PRIntervalTime timeout)
{
    PRInt32 rv;    /* Return value of _PR_MD_CONNECT */
    const PRNetAddr *addrp = addr;
#if defined(_PR_INET6)
    PRNetAddr addrCopy;
#endif
    PRThread *me = _PR_MD_CURRENT_THREAD();

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return PR_FAILURE;
    }
#if defined(_PR_INET6)
    if (addr->raw.family == PR_AF_INET6) {
        addrCopy = *addr;
        addrCopy.raw.family = AF_INET6;
        addrp = &addrCopy;
    }
#endif

    rv = _PR_MD_CONNECT(fd, addrp, PR_NETADDR_SIZE(addr), timeout);
    PR_LOG(_pr_io_lm, PR_LOG_MAX, ("connect -> %d", rv));
    if (rv == 0) {
        return PR_SUCCESS;
    }
    else {
        return PR_FAILURE;
    }
}

static PRStatus PR_CALLBACK SocketConnectContinue(
    PRFileDesc *fd, PRInt16 out_flags)
{
    PROsfd osfd;
    int err;

    if (out_flags & PR_POLL_NVAL) {
        PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
        return PR_FAILURE;
    }
    if ((out_flags & (PR_POLL_WRITE | PR_POLL_EXCEPT | PR_POLL_ERR)) == 0) {
        PR_ASSERT(out_flags == 0);
        PR_SetError(PR_IN_PROGRESS_ERROR, 0);
        return PR_FAILURE;
    }

    osfd = fd->secret->md.osfd;

#if defined(XP_UNIX)

    err = _MD_unix_get_nonblocking_connect_error(osfd);
    if (err != 0) {
        _PR_MD_MAP_CONNECT_ERROR(err);
        return PR_FAILURE;
    }
    return PR_SUCCESS;

#elif defined(WIN32) || defined(WIN16)

    if (out_flags & PR_POLL_EXCEPT) {
        int len = sizeof(err);
        if (getsockopt(osfd, (int)SOL_SOCKET, SO_ERROR, (char *) &err, &len)
            == SOCKET_ERROR) {
            _PR_MD_MAP_GETSOCKOPT_ERROR(WSAGetLastError());
            return PR_FAILURE;
        }
        if (err != 0) {
            _PR_MD_MAP_CONNECT_ERROR(err);
        } else {
#if defined(_WIN64)
            if (fd->secret->overlappedActive) {
                PRInt32 rvSent;
                if (GetOverlappedResult(osfd, &fd->secret->ol, &rvSent, FALSE) == FALSE) {
                    err = WSAGetLastError();
                    PR_LOG(_pr_io_lm, PR_LOG_MIN,
                           ("SocketConnectContinue GetOverlappedResult failed %d\n", err));
                    if (err != ERROR_IO_INCOMPLETE) {
                        _PR_MD_MAP_CONNECT_ERROR(err);
                        fd->secret->overlappedActive = PR_FALSE;
                    }
                }
            }
            if (err == 0) {
                PR_SetError(PR_UNKNOWN_ERROR, 0);
            }
#else
            PR_SetError(PR_UNKNOWN_ERROR, 0);
#endif
        }
        return PR_FAILURE;
    }

    PR_ASSERT(out_flags & PR_POLL_WRITE);

#if defined(_WIN64)
    if (fd->secret->alreadyConnected) {
        fd->secret->alreadyConnected = PR_FALSE;
    }
    /* TCP Fast Open on Windows must use ConnectEx, which uses overlapped
     * input/output.
     * To get result we need to use GetOverlappedResult. */
    if (fd->secret->overlappedActive) {
        PR_ASSERT(fd->secret->nonblocking);
        PRInt32 rvSent;
        if (GetOverlappedResult(osfd, &fd->secret->ol, &rvSent, FALSE) == TRUE) {
            fd->secret->overlappedActive = PR_FALSE;
            PR_LOG(_pr_io_lm, PR_LOG_MIN,
                   ("SocketConnectContinue GetOverlappedResult succeeded\n"));
            /* When ConnectEx is used, all previously set socket options and
             * property are not enabled and to enable them
             * SO_UPDATE_CONNECT_CONTEXT option need to be set. */
            if (setsockopt((SOCKET)osfd, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0) != 0) {
                err = WSAGetLastError();
                PR_LOG(_pr_io_lm, PR_LOG_MIN,
                       ("SocketConnectContinue setting SO_UPDATE_CONNECT_CONTEXT failed %d\n", err));
                _PR_MD_MAP_SETSOCKOPT_ERROR(err);
                return PR_FAILURE;
            }
            return PR_SUCCESS;
        } else {
            err = WSAGetLastError();
            PR_LOG(_pr_io_lm, PR_LOG_MIN,
                   ("SocketConnectContinue GetOverlappedResult failed %d\n", err));
            if (err != ERROR_IO_INCOMPLETE) {
                _PR_MD_MAP_CONNECT_ERROR(err);
                fd->secret->overlappedActive = PR_FALSE;
                return PR_FAILURE;
            } else {
                PR_SetError(PR_IN_PROGRESS_ERROR, 0);
                return PR_FAILURE;
            }
        }
    }
#endif

    return PR_SUCCESS;

#elif defined(XP_OS2)

    err = _MD_os2_get_nonblocking_connect_error(osfd);
    if (err != 0) {
        _PR_MD_MAP_CONNECT_ERROR(err);
        return PR_FAILURE;
    }
    return PR_SUCCESS;


#else
    PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
    return PR_FAILURE;
#endif
}

PR_IMPLEMENT(PRStatus) PR_GetConnectStatus(const PRPollDesc *pd)
{
    /* Find the NSPR layer and invoke its connectcontinue method */
    PRFileDesc *bottom = PR_GetIdentitiesLayer(pd->fd, PR_NSPR_IO_LAYER);

    if (NULL == bottom) {
        PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
        return PR_FAILURE;
    }
    return SocketConnectContinue(bottom, pd->out_flags);
}

static PRFileDesc* PR_CALLBACK SocketAccept(PRFileDesc *fd, PRNetAddr *addr,
        PRIntervalTime timeout)
{
    PROsfd osfd;
    PRFileDesc *fd2;
    PRUint32 al;
    PRThread *me = _PR_MD_CURRENT_THREAD();
#ifdef WINNT
    PRNetAddr addrCopy;
#endif

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return 0;
    }
    if (_PR_IO_PENDING(me)) {
        PR_SetError(PR_IO_PENDING_ERROR, 0);
        return 0;
    }

#ifdef WINNT
    if (addr == NULL) {
        addr = &addrCopy;
    }
#endif
    al = sizeof(PRNetAddr);
    osfd = _PR_MD_ACCEPT(fd, addr, &al, timeout);
    if (osfd == -1) {
        return 0;
    }

    fd2 = PR_AllocFileDesc(osfd, PR_GetTCPMethods());
    if (!fd2) {
        _PR_MD_CLOSE_SOCKET(osfd);
        return NULL;
    }

    fd2->secret->nonblocking = fd->secret->nonblocking;
    fd2->secret->inheritable = fd->secret->inheritable;
#ifdef WINNT
    if (!fd2->secret->nonblocking && fd2->secret->inheritable != _PR_TRI_TRUE) {
        /*
         * The new socket has been associated with an I/O
         * completion port.  There is no going back.
         */
        fd2->secret->md.io_model_committed = PR_TRUE;
    }
    PR_ASSERT(al == PR_NETADDR_SIZE(addr));
    fd2->secret->md.accepted_socket = PR_TRUE;
    memcpy(&fd2->secret->md.peer_addr, addr, al);
#endif

    /*
     * On some platforms, the new socket created by accept()
     * inherits the nonblocking (or overlapped io) attribute
     * of the listening socket.  As an optimization, these
     * platforms can skip the following _PR_MD_MAKE_NONBLOCK
     * call.
     */
#if !defined(SOLARIS) && !defined(WINNT)
    _PR_MD_MAKE_NONBLOCK(fd2);
#endif

#ifdef _PR_INET6
    if (addr && (AF_INET6 == addr->raw.family)) {
        addr->raw.family = PR_AF_INET6;
    }
#endif
    PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
    PR_ASSERT(IsValidNetAddrLen(addr, al) == PR_TRUE);

    return fd2;
}

#ifdef WINNT
PR_IMPLEMENT(PRFileDesc*) PR_NTFast_Accept(PRFileDesc *fd, PRNetAddr *addr,
        PRIntervalTime timeout)
{
    PROsfd osfd;
    PRFileDesc *fd2;
    PRIntn al;
    PRThread *me = _PR_MD_CURRENT_THREAD();
    PRNetAddr addrCopy;

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return 0;
    }
    if (_PR_IO_PENDING(me)) {
        PR_SetError(PR_IO_PENDING_ERROR, 0);
        return 0;
    }

    if (addr == NULL) {
        addr = &addrCopy;
    }
    al = PR_NETADDR_SIZE(addr);
    osfd = _PR_MD_FAST_ACCEPT(fd, addr, &al, timeout, PR_TRUE, NULL, NULL);
    if (osfd == -1) {
        return 0;
    }

    fd2 = PR_AllocFileDesc(osfd, PR_GetTCPMethods());
    if (!fd2) {
        _PR_MD_CLOSE_SOCKET(osfd);
    } else {
        fd2->secret->nonblocking = fd->secret->nonblocking;
        fd2->secret->md.io_model_committed = PR_TRUE;
        PR_ASSERT(al == PR_NETADDR_SIZE(addr));
        fd2->secret->md.accepted_socket = PR_TRUE;
        memcpy(&fd2->secret->md.peer_addr, addr, al);
#ifdef _PR_INET6
        if (AF_INET6 == addr->raw.family) {
            addr->raw.family = PR_AF_INET6;
        }
#endif
#ifdef _PR_NEED_SECRET_AF
        fd2->secret->af = fd->secret->af;
#endif
    }
    return fd2;
}
#endif /* WINNT */


static PRStatus PR_CALLBACK SocketBind(PRFileDesc *fd, const PRNetAddr *addr)
{
    PRInt32 result;
    const PRNetAddr *addrp = addr;
#if defined(_PR_INET6)
    PRNetAddr addrCopy;
#endif

    PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);

#ifdef XP_UNIX
    if (addr->raw.family == AF_UNIX) {
        /* Disallow relative pathnames */
        if (addr->local.path[0] != '/') {
            PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
            return PR_FAILURE;
        }
    }
#endif /* XP_UNIX */

#if defined(_PR_INET6)
    if (addr->raw.family == PR_AF_INET6) {
        addrCopy = *addr;
        addrCopy.raw.family = AF_INET6;
        addrp = &addrCopy;
    }
#endif
    result = _PR_MD_BIND(fd, addrp, PR_NETADDR_SIZE(addr));
    if (result < 0) {
        return PR_FAILURE;
    }
    return PR_SUCCESS;
}

static PRStatus PR_CALLBACK SocketListen(PRFileDesc *fd, PRIntn backlog)
{
    PRInt32 result;

    result = _PR_MD_LISTEN(fd, backlog);
    if (result < 0) {
        return PR_FAILURE;
    }
    return PR_SUCCESS;
}

static PRStatus PR_CALLBACK SocketShutdown(PRFileDesc *fd, PRIntn how)
{
    PRInt32 result;

    result = _PR_MD_SHUTDOWN(fd, how);
    if (result < 0) {
        return PR_FAILURE;
    }
    return PR_SUCCESS;
}

static PRInt32 PR_CALLBACK SocketRecv(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
                                      PRIntervalTime timeout)
{
    PRInt32 rv;
    PRThread *me = _PR_MD_CURRENT_THREAD();

    if ((flags != 0) && (flags != PR_MSG_PEEK)) {
        PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
        return -1;
    }
    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return -1;
    }
    if (_PR_IO_PENDING(me)) {
        PR_SetError(PR_IO_PENDING_ERROR, 0);
        return -1;
    }

    PR_LOG(_pr_io_lm, PR_LOG_MAX,
           ("recv: fd=%p osfd=%" PR_PRIdOSFD " buf=%p amount=%d flags=%d",
            fd, fd->secret->md.osfd, buf, amount, flags));

#ifdef _PR_HAVE_PEEK_BUFFER
    if (fd->secret->peekBytes != 0) {
        rv = (amount < fd->secret->peekBytes) ?
             amount : fd->secret->peekBytes;
        memcpy(buf, fd->secret->peekBuffer, rv);
        if (flags == 0) {
            /* consume the bytes in the peek buffer */
            fd->secret->peekBytes -= rv;
            if (fd->secret->peekBytes != 0) {
                memmove(fd->secret->peekBuffer,
                        fd->secret->peekBuffer + rv,
                        fd->secret->peekBytes);
            }
        }
        return rv;
    }

    /* allocate peek buffer, if necessary */
    if ((PR_MSG_PEEK == flags) && _PR_FD_NEED_EMULATE_MSG_PEEK(fd)) {
        PR_ASSERT(0 == fd->secret->peekBytes);
        /* impose a max size on the peek buffer */
        if (amount > _PR_PEEK_BUFFER_MAX) {
            amount = _PR_PEEK_BUFFER_MAX;
        }
        if (fd->secret->peekBufSize < amount) {
            if (fd->secret->peekBuffer) {
                PR_Free(fd->secret->peekBuffer);
            }
            fd->secret->peekBufSize = amount;
            fd->secret->peekBuffer = PR_Malloc(amount);
            if (NULL == fd->secret->peekBuffer) {
                fd->secret->peekBufSize = 0;
                PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
                return -1;
            }
        }
    }
#endif

    rv = _PR_MD_RECV(fd, buf, amount, flags, timeout);
    PR_LOG(_pr_io_lm, PR_LOG_MAX, ("recv -> %d, error = %d, os error = %d",
                                   rv, PR_GetError(), PR_GetOSError()));

#ifdef _PR_HAVE_PEEK_BUFFER
    if ((PR_MSG_PEEK == flags) && _PR_FD_NEED_EMULATE_MSG_PEEK(fd)) {
        if (rv > 0) {
            memcpy(fd->secret->peekBuffer, buf, rv);
            fd->secret->peekBytes = rv;
        }
    }
#endif

    return rv;
}

static PRInt32 PR_CALLBACK SocketRead(PRFileDesc *fd, void *buf, PRInt32 amount)
{
    return SocketRecv(fd, buf, amount, 0, PR_INTERVAL_NO_TIMEOUT);
}

static PRInt32 PR_CALLBACK SocketSend(PRFileDesc *fd, const void *buf, PRInt32 amount,
                                      PRIntn flags, PRIntervalTime timeout)
{
    PRInt32 temp, count;
    PRThread *me = _PR_MD_CURRENT_THREAD();

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return -1;
    }
    if (_PR_IO_PENDING(me)) {
        PR_SetError(PR_IO_PENDING_ERROR, 0);
        return -1;
    }

    count = 0;
    while (amount > 0) {
        PR_LOG(_pr_io_lm, PR_LOG_MAX,
               ("send: fd=%p osfd=%" PR_PRIdOSFD " buf=%p amount=%d",
                fd, fd->secret->md.osfd, buf, amount));
        temp = _PR_MD_SEND(fd, buf, amount, flags, timeout);
        if (temp < 0) {
            count = -1;
            break;
        }

        count += temp;
        if (fd->secret->nonblocking) {
            break;
        }
        buf = (const void*) ((const char*)buf + temp);

        amount -= temp;
    }
    PR_LOG(_pr_io_lm, PR_LOG_MAX, ("send -> %d", count));
    return count;
}

static PRInt32 PR_CALLBACK SocketWrite(PRFileDesc *fd, const void *buf, PRInt32 amount)
{
    return SocketSend(fd, buf, amount, 0, PR_INTERVAL_NO_TIMEOUT);
}

static PRStatus PR_CALLBACK SocketClose(PRFileDesc *fd)
{
    if (!fd || !fd->secret
        || (fd->secret->state != _PR_FILEDESC_OPEN
            && fd->secret->state != _PR_FILEDESC_CLOSED)) {
        PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
        return PR_FAILURE;
    }

    if (fd->secret->state == _PR_FILEDESC_OPEN) {
#if defined(_WIN64) && defined(WIN95)
        /* TCP Fast Open on Windows must use ConnectEx, which uses overlapped
         * input/output. Before closing such a socket we must cancelIO.
         */
        if (fd->secret->overlappedActive) {
            PR_ASSERT(fd->secret->nonblocking);
            if (CancelIo((HANDLE) fd->secret->md.osfd) == TRUE) {
                PR_LOG(_pr_io_lm, PR_LOG_MIN,
                       ("SocketClose - CancelIo succeeded\n"));
            } else {
                DWORD err = WSAGetLastError();
                PR_LOG(_pr_io_lm, PR_LOG_MIN,
                       ("SocketClose - CancelIo failed err=%x\n", err));
            }

            DWORD rvSent;
            if (GetOverlappedResult((HANDLE)fd->secret->md.osfd, &fd->secret->ol, &rvSent, FALSE) == TRUE) {
                fd->secret->overlappedActive = PR_FALSE;
                PR_LOG(_pr_io_lm, PR_LOG_MIN,
                       ("SocketClose GetOverlappedResult succeeded\n"));
            } else {
                DWORD err = WSAGetLastError();
                PR_LOG(_pr_io_lm, PR_LOG_MIN,
                       ("SocketClose GetOverlappedResult failed %d\n", err));
                if (err != ERROR_IO_INCOMPLETE) {
                    _PR_MD_MAP_CONNECT_ERROR(err);
                    fd->secret->overlappedActive = PR_FALSE;
                }
            }
        }

        if (fd->secret->overlappedActive &&
            _fd_waiting_for_overlapped_done_lock) {
            // Put osfd into the list to be checked later.
            PRFileDescList *forWaiting = PR_NEW(PRFileDescList);
            if (!forWaiting) {
                PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
                return PR_FAILURE;
            }
            forWaiting->fd = fd;

            PR_Lock(_fd_waiting_for_overlapped_done_lock);
            forWaiting->next = _fd_waiting_for_overlapped_done;
            _fd_waiting_for_overlapped_done = forWaiting;
            PR_Unlock(_fd_waiting_for_overlapped_done_lock);

            return PR_SUCCESS;
        }
#endif

        if (_PR_MD_CLOSE_SOCKET(fd->secret->md.osfd) < 0) {
            return PR_FAILURE;
        }
        fd->secret->state = _PR_FILEDESC_CLOSED;
    }

#ifdef _PR_HAVE_PEEK_BUFFER
    if (fd->secret->peekBuffer) {
        PR_ASSERT(fd->secret->peekBufSize > 0);
        PR_DELETE(fd->secret->peekBuffer);
        fd->secret->peekBufSize = 0;
        fd->secret->peekBytes = 0;
    }
#endif

    PR_FreeFileDesc(fd);
    return PR_SUCCESS;
}

static PRInt32 PR_CALLBACK SocketAvailable(PRFileDesc *fd)
{
    PRInt32 rv;
#ifdef _PR_HAVE_PEEK_BUFFER
    if (fd->secret->peekBytes != 0) {
        return fd->secret->peekBytes;
    }
#endif
    rv =  _PR_MD_SOCKETAVAILABLE(fd);
    return rv;
}

static PRInt64 PR_CALLBACK SocketAvailable64(PRFileDesc *fd)
{
    PRInt64 rv;
#ifdef _PR_HAVE_PEEK_BUFFER
    if (fd->secret->peekBytes != 0) {
        LL_I2L(rv, fd->secret->peekBytes);
        return rv;
    }
#endif
    LL_I2L(rv, _PR_MD_SOCKETAVAILABLE(fd));
    return rv;
}

static PRStatus PR_CALLBACK SocketSync(PRFileDesc *fd)
{
    return PR_SUCCESS;
}

static PRInt32 PR_CALLBACK SocketSendTo(
    PRFileDesc *fd, const void *buf, PRInt32 amount,
    PRIntn flags, const PRNetAddr *addr, PRIntervalTime timeout)
{
    PRInt32 temp, count;
    const PRNetAddr *addrp = addr;
#if defined(_PR_INET6)
    PRNetAddr addrCopy;
#endif
    PRThread *me = _PR_MD_CURRENT_THREAD();

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return -1;
    }
    if (_PR_IO_PENDING(me)) {
        PR_SetError(PR_IO_PENDING_ERROR, 0);
        return -1;
    }

    PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
#if defined(_PR_INET6)
    if (addr->raw.family == PR_AF_INET6) {
        addrCopy = *addr;
        addrCopy.raw.family = AF_INET6;
        addrp = &addrCopy;
    }
#endif

    count = 0;
    do {
        temp = _PR_MD_SENDTO(fd, buf, amount, flags,
                             addrp, PR_NETADDR_SIZE(addr), timeout);
        if (temp < 0) {
            count = -1;
            break;
        }
        count += temp;
        if (fd->secret->nonblocking) {
            break;
        }
        buf = (const void*) ((const char*)buf + temp);
        amount -= temp;
    } while (amount > 0);
    return count;
}

#if defined(_WIN64) && defined(WIN95)
static PRInt32 PR_CALLBACK SocketTCPSendTo(
    PRFileDesc *fd, const void *buf, PRInt32 amount,
    PRIntn flags, const PRNetAddr *addr, PRIntervalTime timeout)
{
    PRInt32 temp, count;
    const PRNetAddr *addrp = addr;
#if defined(_PR_INET6)
    PRNetAddr addrCopy;
#endif
    PRThread *me = _PR_MD_CURRENT_THREAD();

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return -1;
    }
    if (_PR_IO_PENDING(me)) {
        PR_SetError(PR_IO_PENDING_ERROR, 0);
        return -1;
    }

    PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
#if defined(_PR_INET6)
    if (addr->raw.family == PR_AF_INET6) {
        addrCopy = *addr;
        addrCopy.raw.family = AF_INET6;
        addrp = &addrCopy;
    }
#endif

    count = 0;
    while (amount > 0) {
        temp = _PR_MD_TCPSENDTO(fd, buf, amount, flags,
                                addrp, PR_NETADDR_SIZE(addr), timeout);
        if (temp < 0) {
            count = -1;
            break;
        }
        count += temp;
        if (fd->secret->nonblocking) {
            break;
        }
        buf = (const void*) ((const char*)buf + temp);
        amount -= temp;
    }
    return count;
}
#endif

static PRInt32 PR_CALLBACK SocketRecvFrom(PRFileDesc *fd, void *buf, PRInt32 amount,
        PRIntn flags, PRNetAddr *addr, PRIntervalTime timeout)
{
    PRInt32 rv;
    PRUint32 al;
    PRThread *me = _PR_MD_CURRENT_THREAD();

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return -1;
    }
    if (_PR_IO_PENDING(me)) {
        PR_SetError(PR_IO_PENDING_ERROR, 0);
        return -1;
    }

    al = sizeof(PRNetAddr);
    rv = _PR_MD_RECVFROM(fd, buf, amount, flags, addr, &al, timeout);
#ifdef _PR_INET6
    if (addr && (AF_INET6 == addr->raw.family)) {
        addr->raw.family = PR_AF_INET6;
    }
#endif
    return rv;
}

static PRInt32 PR_CALLBACK SocketAcceptRead(PRFileDesc *sd, PRFileDesc **nd,
        PRNetAddr **raddr, void *buf, PRInt32 amount,
        PRIntervalTime timeout)
{
    PRInt32 rv;
    PRThread *me = _PR_MD_CURRENT_THREAD();

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return -1;
    }
    if (_PR_IO_PENDING(me)) {
        PR_SetError(PR_IO_PENDING_ERROR, 0);
        return -1;
    }
    /* The socket must be in blocking mode. */
    if (sd->secret->nonblocking) {
        PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
        return -1;
    }
    *nd = NULL;

#if defined(WINNT)
    {
        PROsfd newSock;
        PRNetAddr *raddrCopy;

        if (raddr == NULL) {
            raddr = &raddrCopy;
        }
        rv = _PR_MD_ACCEPT_READ(sd, &newSock, raddr, buf, amount, timeout);
        if (rv < 0) {
            rv = -1;
        } else {
            /* Successfully accepted and read; create the new PRFileDesc */
            *nd = PR_AllocFileDesc(newSock, PR_GetTCPMethods());
            if (*nd == 0) {
                _PR_MD_CLOSE_SOCKET(newSock);
                /* PR_AllocFileDesc() has invoked PR_SetError(). */
                rv = -1;
            } else {
                (*nd)->secret->md.io_model_committed = PR_TRUE;
                (*nd)->secret->md.accepted_socket = PR_TRUE;
                memcpy(&(*nd)->secret->md.peer_addr, *raddr,
                       PR_NETADDR_SIZE(*raddr));
#ifdef _PR_INET6
                if (AF_INET6 == *raddr->raw.family) {
                    *raddr->raw.family = PR_AF_INET6;
                }
#endif
            }
        }
    }
#else
    rv = PR_EmulateAcceptRead(sd, nd, raddr, buf, amount, timeout);
#endif
    return rv;
}

#ifdef WINNT
PR_IMPLEMENT(PRInt32) PR_NTFast_AcceptRead(PRFileDesc *sd, PRFileDesc **nd,
        PRNetAddr **raddr, void *buf, PRInt32 amount,
        PRIntervalTime timeout)
{
    PRInt32 rv;
    PROsfd newSock;
    PRThread *me = _PR_MD_CURRENT_THREAD();
    PRNetAddr *raddrCopy;

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return -1;
    }
    if (_PR_IO_PENDING(me)) {
        PR_SetError(PR_IO_PENDING_ERROR, 0);
        return -1;
    }
    *nd = NULL;

    if (raddr == NULL) {
        raddr = &raddrCopy;
    }
    rv = _PR_MD_FAST_ACCEPT_READ(sd, &newSock, raddr, buf, amount,
                                 timeout, PR_TRUE, NULL, NULL);
    if (rv < 0) {
        rv = -1;
    } else {
        /* Successfully accepted and read; create the new PRFileDesc */
        *nd = PR_AllocFileDesc(newSock, PR_GetTCPMethods());
        if (*nd == 0) {
            _PR_MD_CLOSE_SOCKET(newSock);
            /* PR_AllocFileDesc() has invoked PR_SetError(). */
            rv = -1;
        } else {
            (*nd)->secret->md.io_model_committed = PR_TRUE;
            (*nd)->secret->md.accepted_socket = PR_TRUE;
            memcpy(&(*nd)->secret->md.peer_addr, *raddr,
                   PR_NETADDR_SIZE(*raddr));
#ifdef _PR_INET6
            if (AF_INET6 == *raddr->raw.family) {
                *raddr->raw.family = PR_AF_INET6;
            }
#endif
#ifdef _PR_NEED_SECRET_AF
            (*nd)->secret->af = sd->secret->af;
#endif
        }
    }
    return rv;
}

PR_IMPLEMENT(PRInt32) PR_NTFast_AcceptRead_WithTimeoutCallback(
    PRFileDesc *sd, PRFileDesc **nd,
    PRNetAddr **raddr, void *buf, PRInt32 amount,
    PRIntervalTime timeout,
    _PR_AcceptTimeoutCallback callback,
    void *callbackArg)
{
    PRInt32 rv;
    PROsfd newSock;
    PRThread *me = _PR_MD_CURRENT_THREAD();
    PRNetAddr *raddrCopy;

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return -1;
    }
    if (_PR_IO_PENDING(me)) {
        PR_SetError(PR_IO_PENDING_ERROR, 0);
        return -1;
    }
    *nd = NULL;

    if (raddr == NULL) {
        raddr = &raddrCopy;
    }
    rv = _PR_MD_FAST_ACCEPT_READ(sd, &newSock, raddr, buf, amount,
                                 timeout, PR_TRUE, callback, callbackArg);
    if (rv < 0) {
        rv = -1;
    } else {
        /* Successfully accepted and read; create the new PRFileDesc */
        *nd = PR_AllocFileDesc(newSock, PR_GetTCPMethods());
        if (*nd == 0) {
            _PR_MD_CLOSE_SOCKET(newSock);
            /* PR_AllocFileDesc() has invoked PR_SetError(). */
            rv = -1;
        } else {
            (*nd)->secret->md.io_model_committed = PR_TRUE;
            (*nd)->secret->md.accepted_socket = PR_TRUE;
            memcpy(&(*nd)->secret->md.peer_addr, *raddr,
                   PR_NETADDR_SIZE(*raddr));
#ifdef _PR_INET6
            if (AF_INET6 == *raddr->raw.family) {
                *raddr->raw.family = PR_AF_INET6;
            }
#endif
#ifdef _PR_NEED_SECRET_AF
            (*nd)->secret->af = sd->secret->af;
#endif
        }
    }
    return rv;
}
#endif /* WINNT */

#ifdef WINNT
PR_IMPLEMENT(void)
PR_NTFast_UpdateAcceptContext(PRFileDesc *socket, PRFileDesc *acceptSocket)
{
    _PR_MD_UPDATE_ACCEPT_CONTEXT(
        socket->secret->md.osfd, acceptSocket->secret->md.osfd);
}
#endif /* WINNT */

static PRInt32 PR_CALLBACK SocketSendFile(
    PRFileDesc *sd, PRSendFileData *sfd,
    PRTransmitFileFlags flags, PRIntervalTime timeout)
{
    PRInt32 rv;
    PRThread *me = _PR_MD_CURRENT_THREAD();

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return -1;
    }
    if (_PR_IO_PENDING(me)) {
        PR_SetError(PR_IO_PENDING_ERROR, 0);
        return -1;
    }
    /* The socket must be in blocking mode. */
    if (sd->secret->nonblocking) {
        PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
        return -1;
    }
#if defined(WINNT)
    rv = _PR_MD_SENDFILE(sd, sfd, flags, timeout);
    if ((rv >= 0) && (flags == PR_TRANSMITFILE_CLOSE_SOCKET)) {
        /*
         * This should be kept the same as SocketClose, except
         * that _PR_MD_CLOSE_SOCKET(sd->secret->md.osfd) should
         * not be called because the socket will be recycled.
         */
        PR_FreeFileDesc(sd);
    }
#else
    rv = PR_EmulateSendFile(sd, sfd, flags, timeout);
#endif  /* WINNT */

    return rv;
}

static PRInt32 PR_CALLBACK SocketTransmitFile(PRFileDesc *sd, PRFileDesc *fd,
        const void *headers, PRInt32 hlen, PRTransmitFileFlags flags,
        PRIntervalTime timeout)
{
    PRSendFileData sfd;

    sfd.fd = fd;
    sfd.file_offset = 0;
    sfd.file_nbytes = 0;
    sfd.header = headers;
    sfd.hlen = hlen;
    sfd.trailer = NULL;
    sfd.tlen = 0;

    return(SocketSendFile(sd, &sfd, flags, timeout));
}

static PRStatus PR_CALLBACK SocketGetName(PRFileDesc *fd, PRNetAddr *addr)
{
    PRInt32 result;
    PRUint32 addrlen;

    addrlen = sizeof(PRNetAddr);
    result = _PR_MD_GETSOCKNAME(fd, addr, &addrlen);
    if (result < 0) {
        return PR_FAILURE;
    }
#ifdef _PR_INET6
    if (AF_INET6 == addr->raw.family) {
        addr->raw.family = PR_AF_INET6;
    }
#endif
    PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
    PR_ASSERT(IsValidNetAddrLen(addr, addrlen) == PR_TRUE);
    return PR_SUCCESS;
}

static PRStatus PR_CALLBACK SocketGetPeerName(PRFileDesc *fd, PRNetAddr *addr)
{
    PRInt32 result;
    PRUint32 addrlen;

    addrlen = sizeof(PRNetAddr);
    result = _PR_MD_GETPEERNAME(fd, addr, &addrlen);
    if (result < 0) {
        return PR_FAILURE;
    }
#ifdef _PR_INET6
    if (AF_INET6 == addr->raw.family) {
        addr->raw.family = PR_AF_INET6;
    }
#endif
    PR_ASSERT(IsValidNetAddr(addr) == PR_TRUE);
    PR_ASSERT(IsValidNetAddrLen(addr, addrlen) == PR_TRUE);
    return PR_SUCCESS;
}

static PRInt16 PR_CALLBACK SocketPoll(
    PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags)
{
    *out_flags = 0;

#if defined(_WIN64)
    if (in_flags & PR_POLL_WRITE) {
        if (fd->secret->alreadyConnected) {
            *out_flags = PR_POLL_WRITE;
            return PR_POLL_WRITE;
        }
    }
#endif
    return in_flags;
}  /* SocketPoll */

static PRIOMethods tcpMethods = {
    PR_DESC_SOCKET_TCP,
    SocketClose,
    SocketRead,
    SocketWrite,
    SocketAvailable,
    SocketAvailable64,
    SocketSync,
    (PRSeekFN)_PR_InvalidInt,
    (PRSeek64FN)_PR_InvalidInt64,
    (PRFileInfoFN)_PR_InvalidStatus,
    (PRFileInfo64FN)_PR_InvalidStatus,
    SocketWritev,
    SocketConnect,
    SocketAccept,
    SocketBind,
    SocketListen,
    SocketShutdown,
    SocketRecv,
    SocketSend,
    (PRRecvfromFN)_PR_InvalidInt,
#if defined(_WIN64) && defined(WIN95)
    SocketTCPSendTo, /* This is for fast open. We imitate Linux interface. */
#else
    (PRSendtoFN)_PR_InvalidInt,
#endif
    SocketPoll,
    SocketAcceptRead,
    SocketTransmitFile,
    SocketGetName,
    SocketGetPeerName,
    (PRReservedFN)_PR_InvalidInt,
    (PRReservedFN)_PR_InvalidInt,
    _PR_SocketGetSocketOption,
    _PR_SocketSetSocketOption,
    SocketSendFile,
    SocketConnectContinue,
    (PRReservedFN)_PR_InvalidInt,
    (PRReservedFN)_PR_InvalidInt,
    (PRReservedFN)_PR_InvalidInt,
    (PRReservedFN)_PR_InvalidInt
};

static PRIOMethods udpMethods = {
    PR_DESC_SOCKET_UDP,
    SocketClose,
    SocketRead,
    SocketWrite,
    SocketAvailable,
    SocketAvailable64,
    SocketSync,
    (PRSeekFN)_PR_InvalidInt,
    (PRSeek64FN)_PR_InvalidInt64,
    (PRFileInfoFN)_PR_InvalidStatus,
    (PRFileInfo64FN)_PR_InvalidStatus,
    SocketWritev,
    SocketConnect,
    (PRAcceptFN)_PR_InvalidDesc,
    SocketBind,
    SocketListen,
    SocketShutdown,
    SocketRecv,
    SocketSend,
    SocketRecvFrom,
    SocketSendTo,
    SocketPoll,
    (PRAcceptreadFN)_PR_InvalidInt,
    (PRTransmitfileFN)_PR_InvalidInt,
    SocketGetName,
    SocketGetPeerName,
    (PRReservedFN)_PR_InvalidInt,
    (PRReservedFN)_PR_InvalidInt,
    _PR_SocketGetSocketOption,
    _PR_SocketSetSocketOption,
    (PRSendfileFN)_PR_InvalidInt,
    (PRConnectcontinueFN)_PR_InvalidStatus,
    (PRReservedFN)_PR_InvalidInt,
    (PRReservedFN)_PR_InvalidInt,
    (PRReservedFN)_PR_InvalidInt,
    (PRReservedFN)_PR_InvalidInt
};


static PRIOMethods socketpollfdMethods = {
    (PRDescType) 0,
    (PRCloseFN)_PR_InvalidStatus,
    (PRReadFN)_PR_InvalidInt,
    (PRWriteFN)_PR_InvalidInt,
    (PRAvailableFN)_PR_InvalidInt,
    (PRAvailable64FN)_PR_InvalidInt64,
    (PRFsyncFN)_PR_InvalidStatus,
    (PRSeekFN)_PR_InvalidInt,
    (PRSeek64FN)_PR_InvalidInt64,
    (PRFileInfoFN)_PR_InvalidStatus,
    (PRFileInfo64FN)_PR_InvalidStatus,
    (PRWritevFN)_PR_InvalidInt,
    (PRConnectFN)_PR_InvalidStatus,
    (PRAcceptFN)_PR_InvalidDesc,
    (PRBindFN)_PR_InvalidStatus,
    (PRListenFN)_PR_InvalidStatus,
    (PRShutdownFN)_PR_InvalidStatus,
    (PRRecvFN)_PR_InvalidInt,
    (PRSendFN)_PR_InvalidInt,
    (PRRecvfromFN)_PR_InvalidInt,
    (PRSendtoFN)_PR_InvalidInt,
    SocketPoll,
    (PRAcceptreadFN)_PR_InvalidInt,
    (PRTransmitfileFN)_PR_InvalidInt,
    (PRGetsocknameFN)_PR_InvalidStatus,
    (PRGetpeernameFN)_PR_InvalidStatus,
    (PRReservedFN)_PR_InvalidInt,
    (PRReservedFN)_PR_InvalidInt,
    (PRGetsocketoptionFN)_PR_InvalidStatus,
    (PRSetsocketoptionFN)_PR_InvalidStatus,
    (PRSendfileFN)_PR_InvalidInt,
    (PRConnectcontinueFN)_PR_InvalidStatus,
    (PRReservedFN)_PR_InvalidInt,
    (PRReservedFN)_PR_InvalidInt,
    (PRReservedFN)_PR_InvalidInt,
    (PRReservedFN)_PR_InvalidInt
};

PR_IMPLEMENT(const PRIOMethods*) PR_GetTCPMethods()
{
    return &tcpMethods;
}

PR_IMPLEMENT(const PRIOMethods*) PR_GetUDPMethods()
{
    return &udpMethods;
}

static const PRIOMethods* PR_GetSocketPollFdMethods()
{
    return &socketpollfdMethods;
}  /* PR_GetSocketPollFdMethods */

#if !defined(_PR_INET6) || defined(_PR_INET6_PROBE)
PR_EXTERN(PRStatus) _pr_push_ipv6toipv4_layer(PRFileDesc *fd);

#if defined(_PR_INET6_PROBE)

extern PRBool _pr_ipv6_is_present(void);

PR_IMPLEMENT(PRBool) _pr_test_ipv6_socket()
{
    PROsfd osfd;

    osfd = _PR_MD_SOCKET(AF_INET6, SOCK_STREAM, 0);
    if (osfd != -1) {
        _PR_MD_CLOSE_SOCKET(osfd);
        return PR_TRUE;
    }
    return PR_FALSE;
}
#endif  /* _PR_INET6_PROBE */

#endif

PR_IMPLEMENT(PRFileDesc*) PR_Socket(PRInt32 domain, PRInt32 type, PRInt32 proto)
{
    PROsfd osfd;
    PRFileDesc *fd;
    PRInt32 tmp_domain = domain;

    if (!_pr_initialized) {
        _PR_ImplicitInitialization();
    }
    if (PR_AF_INET != domain
        && PR_AF_INET6 != domain
#if defined(XP_UNIX) || defined(XP_OS2)
        && PR_AF_LOCAL != domain
#endif
       ) {
        PR_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR, 0);
        return NULL;
    }

#if defined(_PR_INET6_PROBE)
    if (PR_AF_INET6 == domain) {
        domain = _pr_ipv6_is_present() ? AF_INET6 : AF_INET;
    }
#elif defined(_PR_INET6)
    if (PR_AF_INET6 == domain) {
        domain = AF_INET6;
    }
#else
    if (PR_AF_INET6 == domain) {
        domain = AF_INET;
    }
#endif  /* _PR_INET6 */
    osfd = _PR_MD_SOCKET(domain, type, proto);
    if (osfd == -1) {
        return 0;
    }
    if (type == SOCK_STREAM) {
        fd = PR_AllocFileDesc(osfd, PR_GetTCPMethods());
    }
    else {
        fd = PR_AllocFileDesc(osfd, PR_GetUDPMethods());
    }
    /*
     * Make the sockets non-blocking
     */
    if (fd != NULL) {
        _PR_MD_MAKE_NONBLOCK(fd);
        _PR_MD_INIT_FD_INHERITABLE(fd, PR_FALSE);
#ifdef _PR_NEED_SECRET_AF
        fd->secret->af = domain;
#endif
#if defined(_PR_INET6_PROBE) || !defined(_PR_INET6)
        /*
         * For platforms with no support for IPv6
         * create layered socket for IPv4-mapped IPv6 addresses
         */
        if (PR_AF_INET6 == tmp_domain && PR_AF_INET == domain) {
            if (PR_FAILURE == _pr_push_ipv6toipv4_layer(fd)) {
                PR_Close(fd);
                fd = NULL;
            }
        }
#endif
    } else {
        _PR_MD_CLOSE_SOCKET(osfd);
    }

    return fd;
}

PR_IMPLEMENT(PRFileDesc *) PR_NewTCPSocket(void)
{
    PRInt32 domain = AF_INET;

    return PR_Socket(domain, SOCK_STREAM, 0);
}

PR_IMPLEMENT(PRFileDesc*) PR_NewUDPSocket(void)
{
    PRInt32 domain = AF_INET;

    return PR_Socket(domain, SOCK_DGRAM, 0);
}

PR_IMPLEMENT(PRFileDesc *) PR_OpenTCPSocket(PRIntn af)
{
    return PR_Socket(af, SOCK_STREAM, 0);
}

PR_IMPLEMENT(PRFileDesc*) PR_OpenUDPSocket(PRIntn af)
{
    return PR_Socket(af, SOCK_DGRAM, 0);
}

PR_IMPLEMENT(PRStatus) PR_NewTCPSocketPair(PRFileDesc *f[])
{
#ifdef XP_UNIX
    PRInt32 rv, osfd[2];

    if (!_pr_initialized) {
        _PR_ImplicitInitialization();
    }

    rv = _PR_MD_SOCKETPAIR(AF_UNIX, SOCK_STREAM, 0, osfd);
    if (rv == -1) {
        return PR_FAILURE;
    }

    f[0] = PR_AllocFileDesc(osfd[0], PR_GetTCPMethods());
    if (!f[0]) {
        _PR_MD_CLOSE_SOCKET(osfd[0]);
        _PR_MD_CLOSE_SOCKET(osfd[1]);
        /* PR_AllocFileDesc() has invoked PR_SetError(). */
        return PR_FAILURE;
    }
    f[1] = PR_AllocFileDesc(osfd[1], PR_GetTCPMethods());
    if (!f[1]) {
        PR_Close(f[0]);
        _PR_MD_CLOSE_SOCKET(osfd[1]);
        /* PR_AllocFileDesc() has invoked PR_SetError(). */
        return PR_FAILURE;
    }
    _PR_MD_MAKE_NONBLOCK(f[0]);
    _PR_MD_INIT_FD_INHERITABLE(f[0], PR_FALSE);
    _PR_MD_MAKE_NONBLOCK(f[1]);
    _PR_MD_INIT_FD_INHERITABLE(f[1], PR_FALSE);
    return PR_SUCCESS;
#elif defined(WINNT)
    /*
     * A socket pair is often used for interprocess communication,
     * so we need to make sure neither socket is associated with
     * the I/O completion port; otherwise it can't be used by a
     * child process.
     *
     * The default implementation below cannot be used for NT
     * because PR_Accept would have associated the I/O completion
     * port with the listening and accepted sockets.
     */
    SOCKET listenSock;
    SOCKET osfd[2];
    struct sockaddr_in selfAddr, peerAddr;
    int addrLen;

    if (!_pr_initialized) {
        _PR_ImplicitInitialization();
    }

    osfd[0] = osfd[1] = INVALID_SOCKET;
    listenSock = socket(AF_INET, SOCK_STREAM, 0);
    if (listenSock == INVALID_SOCKET) {
        goto failed;
    }
    selfAddr.sin_family = AF_INET;
    selfAddr.sin_port = 0;
    selfAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); /* BugZilla: 35408 */
    addrLen = sizeof(selfAddr);
    if (bind(listenSock, (struct sockaddr *) &selfAddr,
             addrLen) == SOCKET_ERROR) {
        goto failed;
    }
    if (getsockname(listenSock, (struct sockaddr *) &selfAddr,
                    &addrLen) == SOCKET_ERROR) {
        goto failed;
    }
    if (listen(listenSock, 5) == SOCKET_ERROR) {
        goto failed;
    }
    osfd[0] = socket(AF_INET, SOCK_STREAM, 0);
    if (osfd[0] == INVALID_SOCKET) {
        goto failed;
    }
    selfAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

    /*
     * Only a thread is used to do the connect and accept.
     * I am relying on the fact that connect returns
     * successfully as soon as the connect request is put
     * into the listen queue (but before accept is called).
     * This is the behavior of the BSD socket code.  If
     * connect does not return until accept is called, we
     * will need to create another thread to call connect.
     */
    if (connect(osfd[0], (struct sockaddr *) &selfAddr,
                addrLen) == SOCKET_ERROR) {
        goto failed;
    }
    /*
     * A malicious local process may connect to the listening
     * socket, so we need to verify that the accepted connection
     * is made from our own socket osfd[0].
     */
    if (getsockname(osfd[0], (struct sockaddr *) &selfAddr,
                    &addrLen) == SOCKET_ERROR) {
        goto failed;
    }
    osfd[1] = accept(listenSock, (struct sockaddr *) &peerAddr, &addrLen);
    if (osfd[1] == INVALID_SOCKET) {
        goto failed;
    }
    if (peerAddr.sin_port != selfAddr.sin_port) {
        /* the connection we accepted is not from osfd[0] */
        PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
        goto failed;
    }
    closesocket(listenSock);

    f[0] = PR_AllocFileDesc(osfd[0], PR_GetTCPMethods());
    if (!f[0]) {
        closesocket(osfd[0]);
        closesocket(osfd[1]);
        /* PR_AllocFileDesc() has invoked PR_SetError(). */
        return PR_FAILURE;
    }
    f[1] = PR_AllocFileDesc(osfd[1], PR_GetTCPMethods());
    if (!f[1]) {
        PR_Close(f[0]);
        closesocket(osfd[1]);
        /* PR_AllocFileDesc() has invoked PR_SetError(). */
        return PR_FAILURE;
    }
    _PR_MD_INIT_FD_INHERITABLE(f[0], PR_FALSE);
    _PR_MD_INIT_FD_INHERITABLE(f[1], PR_FALSE);
    return PR_SUCCESS;

failed:
    if (listenSock != INVALID_SOCKET) {
        closesocket(listenSock);
    }
    if (osfd[0] != INVALID_SOCKET) {
        closesocket(osfd[0]);
    }
    if (osfd[1] != INVALID_SOCKET) {
        closesocket(osfd[1]);
    }
    return PR_FAILURE;
#else /* not Unix or NT */
    /*
     * default implementation
     */
    PRFileDesc *listenSock;
    PRNetAddr selfAddr, peerAddr;
    PRUint16 port;

    f[0] = f[1] = NULL;
    listenSock = PR_NewTCPSocket();
    if (listenSock == NULL) {
        goto failed;
    }
    PR_InitializeNetAddr(PR_IpAddrLoopback, 0, &selfAddr); /* BugZilla: 35408 */
    if (PR_Bind(listenSock, &selfAddr) == PR_FAILURE) {
        goto failed;
    }
    if (PR_GetSockName(listenSock, &selfAddr) == PR_FAILURE) {
        goto failed;
    }
    port = ntohs(selfAddr.inet.port);
    if (PR_Listen(listenSock, 5) == PR_FAILURE) {
        goto failed;
    }
    f[0] = PR_NewTCPSocket();
    if (f[0] == NULL) {
        goto failed;
    }
#ifdef _PR_CONNECT_DOES_NOT_BIND
    /*
     * If connect does not implicitly bind the socket (e.g., on
     * BeOS), we have to bind the socket so that we can get its
     * port with getsockname later.
     */
    PR_InitializeNetAddr(PR_IpAddrLoopback, 0, &selfAddr);
    if (PR_Bind(f[0], &selfAddr) == PR_FAILURE) {
        goto failed;
    }
#endif
    PR_InitializeNetAddr(PR_IpAddrLoopback, port, &selfAddr);

    /*
     * Only a thread is used to do the connect and accept.
     * I am relying on the fact that PR_Connect returns
     * successfully as soon as the connect request is put
     * into the listen queue (but before PR_Accept is called).
     * This is the behavior of the BSD socket code.  If
     * connect does not return until accept is called, we
     * will need to create another thread to call connect.
     */
    if (PR_Connect(f[0], &selfAddr, PR_INTERVAL_NO_TIMEOUT)
        == PR_FAILURE) {
        goto failed;
    }
    /*
     * A malicious local process may connect to the listening
     * socket, so we need to verify that the accepted connection
     * is made from our own socket f[0].
     */
    if (PR_GetSockName(f[0], &selfAddr) == PR_FAILURE) {
        goto failed;
    }
    f[1] = PR_Accept(listenSock, &peerAddr, PR_INTERVAL_NO_TIMEOUT);
    if (f[1] == NULL) {
        goto failed;
    }
    if (peerAddr.inet.port != selfAddr.inet.port) {
        /* the connection we accepted is not from f[0] */
        PR_SetError(PR_INSUFFICIENT_RESOURCES_ERROR, 0);
        goto failed;
    }
    PR_Close(listenSock);
    return PR_SUCCESS;

failed:
    if (listenSock) {
        PR_Close(listenSock);
    }
    if (f[0]) {
        PR_Close(f[0]);
    }
    if (f[1]) {
        PR_Close(f[1]);
    }
    return PR_FAILURE;
#endif
}

PR_IMPLEMENT(PROsfd)
PR_FileDesc2NativeHandle(PRFileDesc *fd)
{
    if (fd) {
        fd = PR_GetIdentitiesLayer(fd, PR_NSPR_IO_LAYER);
    }
    if (!fd) {
        PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
        return -1;
    }
    return fd->secret->md.osfd;
}

PR_IMPLEMENT(void)
PR_ChangeFileDescNativeHandle(PRFileDesc *fd, PROsfd handle)
{
    if (fd) {
        fd->secret->md.osfd = handle;
    }
}

/*
** Select compatibility
**
*/

PR_IMPLEMENT(void) PR_FD_ZERO(PR_fd_set *set)
{
    memset(set, 0, sizeof(PR_fd_set));
}

PR_IMPLEMENT(void) PR_FD_SET(PRFileDesc *fh, PR_fd_set *set)
{
    PR_ASSERT( set->hsize < PR_MAX_SELECT_DESC );

    set->harray[set->hsize++] = fh;
}

PR_IMPLEMENT(void) PR_FD_CLR(PRFileDesc *fh, PR_fd_set *set)
{
    PRUint32 index, index2;

    for (index = 0; index<set->hsize; index++)
        if (set->harray[index] == fh) {
            for (index2=index; index2 < (set->hsize-1); index2++) {
                set->harray[index2] = set->harray[index2+1];
            }
            set->hsize--;
            break;
        }
}

PR_IMPLEMENT(PRInt32) PR_FD_ISSET(PRFileDesc *fh, PR_fd_set *set)
{
    PRUint32 index;
    for (index = 0; index<set->hsize; index++)
        if (set->harray[index] == fh) {
            return 1;
        }
    return 0;
}

PR_IMPLEMENT(void) PR_FD_NSET(PROsfd fd, PR_fd_set *set)
{
    PR_ASSERT( set->nsize < PR_MAX_SELECT_DESC );

    set->narray[set->nsize++] = fd;
}

PR_IMPLEMENT(void) PR_FD_NCLR(PROsfd fd, PR_fd_set *set)
{
    PRUint32 index, index2;

    for (index = 0; index<set->nsize; index++)
        if (set->narray[index] == fd) {
            for (index2=index; index2 < (set->nsize-1); index2++) {
                set->narray[index2] = set->narray[index2+1];
            }
            set->nsize--;
            break;
        }
}

PR_IMPLEMENT(PRInt32) PR_FD_NISSET(PROsfd fd, PR_fd_set *set)
{
    PRUint32 index;
    for (index = 0; index<set->nsize; index++)
        if (set->narray[index] == fd) {
            return 1;
        }
    return 0;
}


#if !defined(NEED_SELECT)
#include "obsolete/probslet.h"

#define PD_INCR 20

static PRPollDesc *_pr_setfd(
    PR_fd_set *set, PRInt16 flags, PRPollDesc *polldesc)
{
    PRUintn fsidx, pdidx;
    PRPollDesc *poll = polldesc;

    if (NULL == set) {
        return poll;
    }

    /* First set the pr file handle osfds */
    for (fsidx = 0; fsidx < set->hsize; fsidx++)
    {
        for (pdidx = 0; 1; pdidx++)
        {
            if ((PRFileDesc*)-1 == poll[pdidx].fd)
            {
                /* our vector is full - extend and condition it */
                poll = (PRPollDesc*)PR_Realloc(
                           poll, (pdidx + 1 + PD_INCR) * sizeof(PRPollDesc));
                if (NULL == poll) {
                    goto out_of_memory;
                }
                memset(
                    poll + pdidx * sizeof(PRPollDesc),
                    0, PD_INCR * sizeof(PRPollDesc));
                poll[pdidx + PD_INCR].fd = (PRFileDesc*)-1;
            }
            if ((NULL == poll[pdidx].fd)
                || (poll[pdidx].fd == set->harray[fsidx]))
            {
                /* PR_ASSERT(0 == (poll[pdidx].in_flags & flags)); */
                /* either empty or prevously defined */
                poll[pdidx].fd = set->harray[fsidx];  /* possibly redundant */
                poll[pdidx].in_flags |= flags;  /* possibly redundant */
                break;
            }
        }
    }

#if 0
    /* Second set the native osfds */
    for (fsidx = 0; fsidx < set->nsize; fsidx++)
    {
        for (pdidx = 0; ((PRFileDesc*)-1 != poll[pdidx].fd); pdidx++)
        {
            if ((PRFileDesc*)-1 == poll[pdidx].fd)
            {
                /* our vector is full - extend and condition it */
                poll = PR_Realloc(
                           poll, (pdidx + PD_INCR) * sizeof(PRPollDesc));
                if (NULL == poll) {
                    goto out_of_memory;
                }
                memset(
                    poll + pdidx * sizeof(PRPollDesc),
                    0, PD_INCR * sizeof(PRPollDesc));
                poll[(pdidx + PD_INCR)].fd = (PRFileDesc*)-1;
            }
            if ((NULL == poll[pdidx].fd)
                || (poll[pdidx].fd == set->narray[fsidx]))
            {
                /* either empty or prevously defined */
                poll[pdidx].fd = set->narray[fsidx];
                PR_ASSERT(0 == (poll[pdidx].in_flags & flags));
                poll[pdidx].in_flags |= flags;
                break;
            }
        }
    }
#endif /* 0 */

    return poll;

out_of_memory:
    if (NULL != polldesc) {
        PR_DELETE(polldesc);
    }
    return NULL;
}  /* _pr_setfd */

#endif /* !defined(NEED_SELECT) */

PR_IMPLEMENT(PRInt32) PR_Select(
    PRInt32 unused, PR_fd_set *pr_rd, PR_fd_set *pr_wr,
    PR_fd_set *pr_ex, PRIntervalTime timeout)
{

#if !defined(NEED_SELECT)
    PRInt32 npds = 0;
    /*
    ** Find out how many fds are represented in the three lists.
    ** Then allocate a polling descriptor for the logical union
    ** (there can't be any overlapping) and call PR_Poll().
    */

    PRPollDesc *copy, *poll;

    static PRBool warning = PR_TRUE;
    if (warning) {
        warning = _PR_Obsolete( "PR_Select()", "PR_Poll()");
    }

    /* try to get an initial guesss at how much space we need */
    npds = 0;
    if ((NULL != pr_rd) && ((pr_rd->hsize + pr_rd->nsize - npds) > 0)) {
        npds = pr_rd->hsize + pr_rd->nsize;
    }
    if ((NULL != pr_wr) && ((pr_wr->hsize + pr_wr->nsize - npds) > 0)) {
        npds = pr_wr->hsize + pr_wr->nsize;
    }
    if ((NULL != pr_ex) && ((pr_ex->hsize + pr_ex->nsize - npds) > 0)) {
        npds = pr_ex->hsize + pr_ex->nsize;
    }

    if (0 == npds)
    {
        PR_Sleep(timeout);
        return 0;
    }

    copy = poll = (PRPollDesc*)PR_Calloc(npds + PD_INCR, sizeof(PRPollDesc));
    if (NULL == poll) {
        goto out_of_memory;
    }
    poll[npds + PD_INCR - 1].fd = (PRFileDesc*)-1;

    poll = _pr_setfd(pr_rd, PR_POLL_READ, poll);
    if (NULL == poll) {
        goto out_of_memory;
    }
    poll = _pr_setfd(pr_wr, PR_POLL_WRITE, poll);
    if (NULL == poll) {
        goto out_of_memory;
    }
    poll = _pr_setfd(pr_ex, PR_POLL_EXCEPT, poll);
    if (NULL == poll) {
        goto out_of_memory;
    }
    unused = 0;
    while (NULL != poll[unused].fd && (PRFileDesc*)-1 != poll[unused].fd)
    {
        ++unused;
    }

    PR_ASSERT(unused > 0);
    npds = PR_Poll(poll, unused, timeout);

    if (npds > 0)
    {
        /* Copy the results back into the fd sets */
        if (NULL != pr_rd) {
            pr_rd->nsize = pr_rd->hsize = 0;
        }
        if (NULL != pr_wr) {
            pr_wr->nsize = pr_wr->hsize = 0;
        }
        if (NULL != pr_ex) {
            pr_ex->nsize = pr_ex->hsize = 0;
        }
        for (copy = &poll[unused - 1]; copy >= poll; --copy)
        {
            if (copy->out_flags & PR_POLL_NVAL)
            {
                PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
                npds = -1;
                break;
            }
            if (copy->out_flags & PR_POLL_READ)
                if (NULL != pr_rd) {
                    pr_rd->harray[pr_rd->hsize++] = copy->fd;
                }
            if (copy->out_flags & PR_POLL_WRITE)
                if (NULL != pr_wr) {
                    pr_wr->harray[pr_wr->hsize++] = copy->fd;
                }
            if (copy->out_flags & PR_POLL_EXCEPT)
                if (NULL != pr_ex) {
                    pr_ex->harray[pr_ex->hsize++] = copy->fd;
                }
        }
    }
    PR_DELETE(poll);

    return npds;
out_of_memory:
    PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
    return -1;

#endif /* !defined(NEED_SELECT) */

}