aboutsummaryrefslogtreecommitdiff
path: root/winsup/cygwin/fhandler_socket_unix.cc
blob: 825bf1c850eff632e718f1dc68b31accd99c633a (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
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
/* fhandler_socket_unix.cc.

   See fhandler.h for a description of the fhandler classes.

   This file is part of Cygwin.

   This software is a copyrighted work licensed under the terms of the
   Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
   details. */

#include "winsup.h"

GUID __cygwin_socket_guid = {
  .Data1 = 0xefc1714d,
  .Data2 = 0x7b19,
  .Data3 = 0x4407,
  .Data4 = { 0xba, 0xb3, 0xc5, 0xb1, 0xf9, 0x2c, 0xb8, 0x8c }
};

#ifdef __WITH_AF_UNIX

#include <w32api/winioctl.h>
#include <asm/byteorder.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/param.h>
#include <sys/statvfs.h>
#include <cygwin/acl.h>
#include <mqueue.h>
#include "cygerrno.h"
#include "path.h"
#include "fhandler.h"
#include "dtable.h"
#include "cygheap.h"
#include "shared_info.h"
#include "ntdll.h"
#include "miscfuncs.h"
#include "tls_pbuf.h"

/*
   Message queue:

     A socket that wants to read creates a POSIX message queue.  The
     name of the mqueue is "/af-unix-[sd]-<uniq_id>".

    - [sd] is s for SOCK_STREAM, d for SOCK_DGRAM
    - <uniq_id> is an 8 byte hex unique number

   Abstract socket:

     An abstract socket is represented by a symlink in the native
     NT namespace, within the Cygwin subdir in BasedNamedObjects.
     So it's globally available but only exists as long as at least on
     descriptor on the socket is open, as desired.

     The name of the symlink is: "af-unix-<sun_path>"

     <sun_path> is the transposed sun_path string, including the leading
     NUL.  The transposition is simplified in that it uses every byte
     in the valid sun_path name as is, no extra multibyte conversion.
     The content of the symlink is the name of the underlying mqueue.

  Named socket:

    A named socket is represented by a reparse point with a Cygwin-specific
    tag and GUID.  The GenericReparseBuffer content is the name of the
    underlying mqueue.

   Note: We use MAX_PATH below for convenience where sufficient.  It's
   big enough to hold sun_paths as well as mqueue names as well as packet
   headers etc., so we don't have to use tmp_pathbuf as often.

   Every packet sent to a peer is a combination of the socket name of the
   local socket, the ancillary data, and the actual user data.  The data
   is always sent in this order.  The header contains length information
   for the entire packet, as well as for all three data blocks.  The
   combined maximum size of a packet is 64K, including the header.

   A connecting, bound STREAM socket sends its local sun_path once after
   a successful connect.  An already connected socket also sends its local
   sun_path after a successful bind (border case, but still...).  These
   packets don't contain any other data (cmsg_len == 0, data_len == 0).

   A bound DGRAM socket sends its sun_path with each sendmsg/sendto.
*/

static inline ptrdiff_t
AF_UNIX_PKT_OFFSETOF_NAME (af_unix_pkt_hdr_t *phdr)
{
  return sizeof (af_unix_pkt_hdr_t);
}

static inline ptrdiff_t
AF_UNIX_PKT_OFFSETOF_CMSG (af_unix_pkt_hdr_t *phdr)
{
  return AF_UNIX_PKT_OFFSETOF_NAME (phdr) + phdr->name_len;
}

static inline ptrdiff_t
AF_UNIX_PKT_OFFSETOF_DATA (af_unix_pkt_hdr_t *phdr)
{
  return AF_UNIX_PKT_OFFSETOF_CMSG (phdr) + phdr->cmsg_len;
}

static inline struct sockaddr_un *
AF_UNIX_PKT_NAME (af_unix_pkt_hdr_t *phdr)
{
  return (struct sockaddr_un *)
	 ((PBYTE)(phdr) + AF_UNIX_PKT_OFFSETOF_NAME (phdr));
}

static inline struct cmsghdr *
AF_UNIX_PKT_CMSG (af_unix_pkt_hdr_t *phdr)
{
   return (struct cmsghdr *)
	  ((PBYTE)(phdr) + AF_UNIX_PKT_OFFSETOF_CMSG (phdr));
}

static inline void *
AF_UNIX_PKT_DATA (af_unix_pkt_hdr_t *phdr)
{
   return (void *) ((PBYTE)(phdr) + AF_UNIX_PKT_OFFSETOF_DATA (phdr));
}

static inline void *
AF_UNIX_PKT_DATA_END (af_unix_pkt_hdr_t *phdr)
{
   return (void *) ((PBYTE)(phdr) + AF_UNIX_PKT_OFFSETOF_DATA (phdr)
				  + (phdr)->data_len);
}

inline bool
AF_UNIX_PKT_DATA_APPEND (af_unix_pkt_hdr_t *phdr, void *data, uint16_t dlen)
{
  if ((uint32_t) phdr->pckt_len + (uint32_t) dlen > MAX_AF_UN_PKT_LEN)
    return false;
  memcpy (AF_UNIX_PKT_DATA_END (phdr), data, dlen);
  phdr->pckt_len += dlen;
  phdr->data_len += dlen;
  return true;
}

/* Some error conditions on pipes have multiple status codes, unfortunately. */
#define STATUS_PIPE_NO_INSTANCE_AVAILABLE(status)	\
		({ NTSTATUS _s = (status); \
		   _s == STATUS_INSTANCE_NOT_AVAILABLE \
		   || _s == STATUS_PIPE_NOT_AVAILABLE \
		   || _s == STATUS_PIPE_BUSY; })

#define STATUS_PIPE_IS_CLOSED(status)	\
		({ NTSTATUS _s = (status); \
		   _s == STATUS_PIPE_CLOSING \
		   || _s == STATUS_PIPE_BROKEN \
		   || _s == STATUS_PIPE_EMPTY; })

#define STATUS_PIPE_INVALID(status) \
		({ NTSTATUS _s = (status); \
		   _s == STATUS_INVALID_INFO_CLASS \
		   || _s == STATUS_INVALID_PIPE_STATE \
		   || _s == STATUS_INVALID_READ_MODE; })

#define STATUS_PIPE_MORE_DATA(status) \
		({ NTSTATUS _s = (status); \
		   _s == STATUS_BUFFER_OVERFLOW \
		   || _s == STATUS_MORE_PROCESSING_REQUIRED; })

/* Default timeout value of connect: 20 secs, as on Linux. */
#define AF_UNIX_CONNECT_TIMEOUT 20

/* Message queue priorities */
enum
{
  af_un_prio_normal,
  af_un_prio_admin,
  af_un_prio_rewrite,		/* For rewritten packet after partial read. */
};

void
sun_name_t::set (const struct sockaddr_un *name, socklen_t namelen)
{
  if (namelen < 0)
    namelen = 0;
  un_len = namelen < (__socklen_t) sizeof un ? namelen : sizeof un;
  un.sun_family = AF_UNIX;
  if (name && un_len)
    memcpy (&un, name, un_len);
  _nul[un_len] = '\0';
}

static HANDLE
create_event ()
{
  NTSTATUS status;
  OBJECT_ATTRIBUTES attr;
  HANDLE evt = NULL;

  InitializeObjectAttributes (&attr, NULL, 0, NULL, NULL);
  status = NtCreateEvent (&evt, EVENT_ALL_ACCESS, &attr,
			  NotificationEvent, FALSE);
  if (!NT_SUCCESS (status))
    __seterrno_from_nt_status (status);
  return evt;
}

/* Called from socket, socketpair, accept4 */
int
fhandler_socket_unix::create_shmem ()
{
  HANDLE sect;
  OBJECT_ATTRIBUTES attr;
  NTSTATUS status;
  LARGE_INTEGER size = { .QuadPart = sizeof (af_unix_shmem_t) };
  SIZE_T viewsize = sizeof (af_unix_shmem_t);
  PVOID addr = NULL;

  InitializeObjectAttributes (&attr, NULL, OBJ_INHERIT, NULL, NULL);
  status = NtCreateSection (&sect, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY
				   | SECTION_MAP_READ | SECTION_MAP_WRITE,
			    &attr, &size, PAGE_READWRITE, SEC_COMMIT, NULL);
  if (!NT_SUCCESS (status))
    {
      __seterrno_from_nt_status (status);
      return -1;
    }
  status = NtMapViewOfSection (sect, NtCurrentProcess (), &addr, 0, viewsize,
			       NULL, &viewsize, ViewShare, 0, PAGE_READWRITE);
  if (!NT_SUCCESS (status))
    {
      NtClose (sect);
      __seterrno_from_nt_status (status);
      return -1;
    }
  shmem_handle = sect;
  shmem = (af_unix_shmem_t *) addr;
  return 0;
}

/* Called from dup, fixup_after_fork.  Expects shmem_handle to be
   valid. */
int
fhandler_socket_unix::reopen_shmem ()
{
  NTSTATUS status;
  SIZE_T viewsize = sizeof (af_unix_shmem_t);
  PVOID addr = NULL;

  status = NtMapViewOfSection (shmem_handle, NtCurrentProcess (), &addr, 0,
			       viewsize, NULL, &viewsize, ViewShare, 0,
			       PAGE_READWRITE);
  if (!NT_SUCCESS (status))
    {
      __seterrno_from_nt_status (status);
      return -1;
    }
  shmem = (af_unix_shmem_t *) addr;
  return 0;
}

/* Character length of mqueue name, excluding trailing NUL. */
#define CYGWIN_MQUEUE_SOCKET_NAME_LEN     27

/* Character position encoding the socket type in an mqueue name. */
#define CYGWIN_MQUEUE_SOCKET_TYPE_POS	9

void
fhandler_socket_unix::gen_mqueue_name ()
{
  char mqueue_name_buf[CYGWIN_MQUEUE_SOCKET_NAME_LEN + 1];

  __small_sprintf (mqueue_name_buf, "/af-unix-%c-%016x",
		    get_type_char (),
		    get_unique_id ());
  set_mqueue_name (mqueue_name_buf);
}

HANDLE
fhandler_socket_unix::create_abstract_link (const sun_name_t *sun,
					    const char *mqueue_name)
{
  WCHAR name[MAX_PATH], wmqueue_name[MAX_PATH];
  OBJECT_ATTRIBUTES attr;
  NTSTATUS status;
  UNICODE_STRING uname, umqueue_name;
  HANDLE fh = NULL;

  PWCHAR p = wcpcpy (name, L"af-unix-");
  /* NUL bytes have no special meaning in an abstract socket name, so
     we assume iso-8859-1 for simplicity and transpose the string.
     transform_chars_af_unix is doing just that. */
  p = transform_chars_af_unix (p, sun->un.sun_path, sun->un_len);
  *p = L'\0';
  RtlInitUnicodeString (&uname, name);
  InitializeObjectAttributes (&attr, &uname, OBJ_CASE_INSENSITIVE,
			      get_shared_parent_dir (), NULL);
  /* Fill symlink with name of mqueue */
  sys_mbstowcs (wmqueue_name, MAX_PATH, mqueue_name);
  RtlInitUnicodeString (&umqueue_name, wmqueue_name);
  status = NtCreateSymbolicLinkObject (&fh, SYMBOLIC_LINK_ALL_ACCESS,
				       &attr, &umqueue_name);
  if (!NT_SUCCESS (status))
    {
      if (status == STATUS_OBJECT_NAME_EXISTS
	  || status == STATUS_OBJECT_NAME_COLLISION)
	set_errno (EADDRINUSE);
      else
	__seterrno_from_nt_status (status);
    }
  return fh;
}

HANDLE
fhandler_socket_unix::create_reparse_point (const sun_name_t *sun,
					    const char *mqueue_name)
{
  ULONG access;
  HANDLE old_trans = NULL, trans = NULL;
  OBJECT_ATTRIBUTES attr;
  IO_STATUS_BLOCK io;
  NTSTATUS status;
  HANDLE fh = NULL;
  PREPARSE_GUID_DATA_BUFFER rp;

  const DWORD data_len = CYGWIN_MQUEUE_SOCKET_NAME_LEN + 1;

  path_conv pc (sun->un.sun_path, PC_SYM_FOLLOW);
  if (pc.error)
    {
      set_errno (pc.error);
      return NULL;
    }
  if (pc.exists ())
    {
      set_errno (EADDRINUSE);
      return NULL;
    }
 /* We will overwrite the DACL after the call to NtCreateFile.  This
    requires READ_CONTROL and WRITE_DAC access, otherwise get_file_sd
    and set_file_sd both have to open the file again.
    FIXME: On remote NTFS shares open sometimes fails because even the
    creator of the file doesn't have the right to change the DACL.
    I don't know what setting that is or how to recognize such a share,
    so for now we don't request WRITE_DAC on remote drives. */
  access = DELETE | FILE_GENERIC_WRITE;
  if (!pc.isremote ())
    access |= READ_CONTROL | WRITE_DAC | WRITE_OWNER;
  if ((pc.fs_flags () & FILE_SUPPORTS_TRANSACTIONS))
    start_transaction (old_trans, trans);

retry_after_transaction_error:
  status = NtCreateFile (&fh, DELETE | FILE_GENERIC_WRITE,
			 pc.get_object_attr (attr, sec_none_nih), &io,
			 NULL, FILE_ATTRIBUTE_NORMAL, 0, FILE_CREATE,
			 FILE_SYNCHRONOUS_IO_NONALERT
			 | FILE_NON_DIRECTORY_FILE
			 | FILE_OPEN_FOR_BACKUP_INTENT
			 | FILE_OPEN_REPARSE_POINT,
			 NULL, 0);
  if (NT_TRANSACTIONAL_ERROR (status) && trans)
    {
      stop_transaction (status, old_trans, trans);
      goto retry_after_transaction_error;
    }

  if (!NT_SUCCESS (status))
    {
      if (io.Information == FILE_EXISTS)
	set_errno (EADDRINUSE);
      else
	__seterrno_from_nt_status (status);
      goto out;
    }
  rp = (PREPARSE_GUID_DATA_BUFFER)
       alloca (REPARSE_GUID_DATA_BUFFER_HEADER_SIZE + data_len);
  rp->ReparseTag = IO_REPARSE_TAG_CYGUNIX;
  rp->ReparseDataLength = data_len;
  rp->Reserved = 0;
  memcpy (&rp->ReparseGuid, CYGWIN_SOCKET_GUID, sizeof (GUID));
  strcpy ((char *) rp->GenericReparseBuffer.DataBuffer, mqueue_name);
  status = NtFsControlFile (fh, NULL, NULL, NULL, &io,
			    FSCTL_SET_REPARSE_POINT, rp,
			    REPARSE_GUID_DATA_BUFFER_HEADER_SIZE
			    + rp->ReparseDataLength, NULL, 0);
  if (NT_SUCCESS (status))
    {
      mode_t perms = (S_IRWXU | S_IRWXG | S_IRWXO) & ~cygheap->umask;
      set_created_file_access (fh, pc, perms);
      NtClose (fh);
      /* We don't have to keep the file open, but the caller needs to
         get a value != NULL to know the file creation went fine. */
      fh = INVALID_HANDLE_VALUE;
    }
  else if (!trans)
    {
      FILE_DISPOSITION_INFORMATION fdi = { TRUE };

      __seterrno_from_nt_status (status);
      status = NtSetInformationFile (fh, &io, &fdi, sizeof fdi,
				     FileDispositionInformation);
      if (!NT_SUCCESS (status))
	debug_printf ("Setting delete dispostion failed, status = %y",
		      status);
      NtClose (fh);
      fh = NULL;
    }

out:
  if (trans)
    stop_transaction (status, old_trans, trans);
  return fh;
}

HANDLE
fhandler_socket_unix::create_socket (const sun_name_t *sun)
{
  if (sun->un_len <= (socklen_t) sizeof (sa_family_t)
      || (sun->un_len == 3 && sun->un.sun_path[0] == '\0'))
    {
      set_errno (EINVAL);
      return NULL;
    }
  if (sun->un.sun_path[0] == '\0')
    return create_abstract_link (sun, get_mqueue_name ());
  return create_reparse_point (sun, get_mqueue_name ());
}

HANDLE
fhandler_socket_unix::open_abstract_link (sun_name_t *sun,
					  char *mqueue_name)
{
  WCHAR name[MAX_PATH], wmqueue_name[MAX_PATH];
  OBJECT_ATTRIBUTES attr;
  NTSTATUS status;
  UNICODE_STRING uname, umqueue_name;
  HANDLE fh;

  PWCHAR p = wcpcpy (name, L"af-unix-");
  p = transform_chars_af_unix (p, sun->un.sun_path, sun->un_len);
  *p = L'\0';
  RtlInitUnicodeString (&uname, name);
  InitializeObjectAttributes (&attr, &uname, OBJ_CASE_INSENSITIVE,
			      get_shared_parent_dir (), NULL);
  status = NtOpenSymbolicLinkObject (&fh, SYMBOLIC_LINK_QUERY, &attr);
  if (!NT_SUCCESS (status))
    {
      __seterrno_from_nt_status (status);
      return NULL;
    }
  if (mqueue_name)
    {
      RtlInitEmptyUnicodeString (&umqueue_name, wmqueue_name,
				 MAX_PATH * sizeof (WCHAR));
      status = NtQuerySymbolicLinkObject (fh, &umqueue_name, NULL);
    }
  if (mqueue_name)
    {
      if (!NT_SUCCESS (status))
	{
	  NtClose (fh);
	  __seterrno_from_nt_status (status);
	  return NULL;
	}
      sys_wcstombs (mqueue_name, MAX_PATH, wmqueue_name);
    }
  return fh;
}

HANDLE
fhandler_socket_unix::open_reparse_point (sun_name_t *sun,
					  char *mqueue_name)
{
  NTSTATUS status;
  HANDLE fh;
  OBJECT_ATTRIBUTES attr;
  IO_STATUS_BLOCK io;
  PREPARSE_GUID_DATA_BUFFER rp;
  tmp_pathbuf tp;

  path_conv pc (sun->un.sun_path, PC_SYM_FOLLOW);
  if (pc.error)
    {
      set_errno (pc.error);
      return NULL;
    }
  if (!pc.exists ())
    {
      set_errno (ENOENT);
      return NULL;
    }
  pc.get_object_attr (attr, sec_none_nih);
  do
    {
      status = NtOpenFile (&fh, FILE_GENERIC_READ, &attr, &io,
			   FILE_SHARE_VALID_FLAGS,
			   FILE_SYNCHRONOUS_IO_NONALERT
			   | FILE_NON_DIRECTORY_FILE
			   | FILE_OPEN_FOR_BACKUP_INTENT
			   | FILE_OPEN_REPARSE_POINT);
      if (status == STATUS_SHARING_VIOLATION)
        {
          /* While we hope that the sharing violation is only temporary, we
             also could easily get stuck here, waiting for a file in use by
             some greedy Win32 application.  Therefore we should never wait
             endlessly without checking for signals and thread cancel event. */
          pthread_testcancel ();
          if (cygwait (NULL, cw_nowait, cw_sig_eintr) == WAIT_SIGNALED
              && !_my_tls.call_signal_handler ())
            {
              set_errno (EINTR);
              return NULL;
            }
          yield ();
        }
      else if (!NT_SUCCESS (status))
        {
          __seterrno_from_nt_status (status);
          return NULL;
        }
    }
  while (status == STATUS_SHARING_VIOLATION);
  rp = (PREPARSE_GUID_DATA_BUFFER) tp.c_get ();
  status = NtFsControlFile (fh, NULL, NULL, NULL, &io, FSCTL_GET_REPARSE_POINT,
			    NULL, 0, rp, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
  if (rp->ReparseTag == IO_REPARSE_TAG_CYGUNIX
      && memcmp (CYGWIN_SOCKET_GUID, &rp->ReparseGuid, sizeof (GUID)) == 0)
    {
      if (mqueue_name)
	strcpy (mqueue_name, (char *) rp->GenericReparseBuffer.DataBuffer);
      return fh;
    }
  NtClose (fh);
  return NULL;
}

HANDLE
fhandler_socket_unix::open_socket (sun_name_t *sun, int &type,
				   char *mqueue_name)
{
  HANDLE fh = NULL;

  if (sun->un_len <= (socklen_t) sizeof (sa_family_t)
      || (sun->un_len == 3 && sun->un.sun_path[0] == '\0'))
    set_errno (EINVAL);
  else if (sun->un.sun_family != AF_UNIX)
    set_errno (EAFNOSUPPORT);
  else if (sun->un.sun_path[0] == '\0')
    fh = open_abstract_link (sun, mqueue_name);
  else
    fh = open_reparse_point (sun, mqueue_name);
  if (fh)
    switch (mqueue_name[CYGWIN_MQUEUE_SOCKET_TYPE_POS])
      {
      case 'd':
	type = SOCK_DGRAM;
	break;
      case 's':
	type = SOCK_STREAM;
	break;
      default:
	set_errno (EINVAL);
	NtClose (fh);
	fh = NULL;
	break;
      }
  return fh;
}

HANDLE
fhandler_socket_unix::autobind (sun_name_t* sun)
{
  uint32_t id;
  HANDLE fh;

  do
    {
      /* Use only 5 hex digits (up to 2^20 sockets) for Linux compat */
      set_unique_id ();
      id = get_unique_id () & 0xfffff;
      sun->un.sun_path[0] = '\0';
      sun->un_len = sizeof (sa_family_t)
		    + 1 /* leading NUL */
		    + __small_sprintf (sun->un.sun_path + 1, "%5X", id);
    }
  while ((fh = create_abstract_link (sun, get_mqueue_name ())) == NULL);
  return fh;
}

char
fhandler_socket_unix::get_type_char ()
{
  switch (get_socket_type ())
    {
    case SOCK_STREAM:
      return 's';
    case SOCK_DGRAM:
      return 'd';
    default:
      return '?';
    }
}

/* Returns error code, but callers don't check it. */
static int
set_mqueue_non_blocking (mqd_t mqd, bool nonblocking)
{
  struct mq_attr attr;

  if (mq_getattr (mqd, &attr) < 0)
    return get_errno ();
  if (nonblocking)
    attr.mq_flags |= O_NONBLOCK;
  else
    attr.mq_flags &= ~O_NONBLOCK;
  if (mq_setattr (mqd, &attr, NULL) < 0)
    return get_errno ();
  return 0;
}

/* This also sets the pipe to message mode unconditionally. */
void
fhandler_socket_unix::set_pipe_non_blocking (bool nonblocking)
{
  if (get_handle ())
    {
      NTSTATUS status;
      IO_STATUS_BLOCK io;
      FILE_PIPE_INFORMATION fpi;

      fpi.ReadMode = FILE_PIPE_MESSAGE_MODE;
      fpi.CompletionMode = nonblocking ? FILE_PIPE_COMPLETE_OPERATION
				       : FILE_PIPE_QUEUE_OPERATION;
      status = NtSetInformationFile (get_handle (), &io, &fpi, sizeof fpi,
				     FilePipeInformation);
      if (!NT_SUCCESS (status))
	debug_printf ("NtSetInformationFile(FilePipeInformation): %y", status);
    }
}

/* Apart from being called from bind(), from_bind indicates that the caller
   already locked state_lock, so send_sock_info doesn't lock, only unlocks
   state_lock. */
int
fhandler_socket_unix::send_sock_info (bool from_bind)
{
  sun_name_t *sun;
  size_t plen;
  size_t clen = 0;
  af_unix_pkt_hdr_t *packet;
  int ret;

  if (!from_bind)
    {
      state_lock ();
      /* When called from connect, initialize credentials.  accept4 already
	 did it (copied from listening socket). */
      if (sock_cred ()->pid == 0)
	set_cred ();
    }
  sun = sun_path ();
  plen = sizeof *packet + sun->un_len;
  /* When called from connect/accept4, send SCM_CREDENTIALS, too. */
  if (!from_bind)
    {
      clen = CMSG_SPACE (sizeof (struct ucred));
      plen += clen;
    }
  packet = (af_unix_pkt_hdr_t *) alloca (plen);
  packet->init (true, _SHUT_NONE, sun->un_len, clen, 0);
  if (sun)
    memcpy (AF_UNIX_PKT_NAME (packet), &sun->un, sun->un_len);
  if (!from_bind)
    {
      struct cmsghdr *cmsg = AF_UNIX_PKT_CMSG (packet);
      cmsg->cmsg_level = SOL_SOCKET;
      cmsg->cmsg_type = SCM_CREDENTIALS;
      cmsg->cmsg_len = CMSG_LEN (sizeof (struct ucred));
      memcpy (CMSG_DATA(cmsg), sock_cred (), sizeof (struct ucred));
    }

  state_unlock ();

  /* The theory: Fire and forget. */
  io_lock ();
  set_mqueue_non_blocking (get_mqd_out (), true);
  ret = mq_send (get_mqd_out (), (const char *) packet, packet->pckt_len,
		 af_un_prio_admin);
  set_mqueue_non_blocking (get_mqd_out (), is_nonblocking ());
  io_unlock ();
  if (ret < 0)
    debug_printf ("Couldn't send my name: mq_send, %E");
  return ret;
}

/* Called from connect_mqueue and wait_mqueue after successfully
   getting peer's mqueue name. */
void
fhandler_socket_unix::xchg_sock_info ()
{
  send_sock_info (false);
  recv_peer_info ();
}

/* Reads an administrative packet from the pipe and handles it.  If
   PEEK is true, checks first to see if the next packet in the pipe is
   an administrative packet; otherwise the caller must set io_lock and
   check this.  Returns an error code, but callers ignore it. */
int
fhandler_socket_unix::grab_admin_pkt (bool peek)
{
  /* MAX_PATH is more than sufficient for admin packets. */
  af_unix_pkt_hdr_t *packet = (af_unix_pkt_hdr_t *) alloca (MAX_PATH);
  ssize_t nr;

  if (peek)
    {
      io_lock ();
      nr = peek_mqueue ((char *) packet, MAX_PATH);
      if (nr < 0)
	{
	  io_unlock ();
	  if (get_errno () == EAGAIN)
	    return 0;
	  return get_errno ();
	}
      if (!packet->admin_pkt)
	{
	  io_unlock ();
	  return 0;
	}
    }
  nr = _mq_recv (get_mqd_in (), (char *) packet, MAX_PATH, 0);
  io_unlock ();
  if (nr < 0)
    return get_errno ();
  state_lock ();
  if (packet->shut_info)
    {
      /* Peer's shutdown sends the SHUT flags as used by the peer.
	 They have to be reversed for our side. */
      int shut_info = saw_shutdown ();
      if (packet->shut_info & _SHUT_RECV)
	shut_info |= _SHUT_SEND;
      if (packet->shut_info & _SHUT_SEND)
	shut_info |= _SHUT_RECV;
      saw_shutdown (shut_info);
      /* FIXME: anything else here? */
    }
  if (packet->name_len > 0)
    peer_sun_path (AF_UNIX_PKT_NAME (packet), packet->name_len);
  if (packet->cmsg_len > 0)
    {
      struct cmsghdr *cmsg = (struct cmsghdr *)
	alloca (packet->cmsg_len);
      memcpy (cmsg, AF_UNIX_PKT_CMSG (packet), packet->cmsg_len);
      if (cmsg->cmsg_level == SOL_SOCKET
	  && cmsg->cmsg_type == SCM_CREDENTIALS)
	peer_cred ((struct ucred *) CMSG_DATA(cmsg));
    }
  state_unlock ();
  return 0;
}

/* Returns an error code.  Locking is not required when called from accept4,
   user space doesn't know about this socket yet. */
int
fhandler_socket_unix::recv_peer_info ()
{
  af_unix_pkt_hdr_t *packet;
  struct sockaddr_un *un;
  size_t len;
  int ret = 0;
  struct timespec timeout;

  len = sizeof *packet + sizeof *un + CMSG_SPACE (sizeof (struct ucred));
  packet = (af_unix_pkt_hdr_t *) alloca (len);
  set_mqueue_non_blocking (get_mqd_in (), false);
  clock_gettime (CLOCK_REALTIME, &timeout);
  timeout.tv_sec += AF_UNIX_CONNECT_TIMEOUT;
  if (_mq_timedrecv (get_mqd_in (), (char *) packet, len, &timeout, 0) < 0)
    ret = get_errno ();
  if (ret == ETIMEDOUT)
    ret = ECONNABORTED;
  set_mqueue_non_blocking (get_mqd_in (), is_nonblocking ());
  if (ret == 0)
    {
      if (packet->name_len > 0)
	peer_sun_path (AF_UNIX_PKT_NAME (packet), packet->name_len);
      if (packet->cmsg_len > 0)
	{
	  struct cmsghdr *cmsg = (struct cmsghdr *) alloca (packet->cmsg_len);
	  memcpy (cmsg, AF_UNIX_PKT_CMSG (packet), packet->cmsg_len);
	  if (cmsg->cmsg_level == SOL_SOCKET
	      && cmsg->cmsg_type == SCM_CREDENTIALS)
	    peer_cred ((struct ucred *) CMSG_DATA(cmsg));
	}
    }
  return ret;
}

NTSTATUS
fhandler_socket_unix::npfs_handle (HANDLE &nph)
{
  static NO_COPY SRWLOCK npfs_lock;
  static NO_COPY HANDLE npfs_dirh;

  NTSTATUS status = STATUS_SUCCESS;
  OBJECT_ATTRIBUTES attr;
  IO_STATUS_BLOCK io;

  /* Lockless after first call. */
  if (npfs_dirh)
    {
      nph = npfs_dirh;
      return STATUS_SUCCESS;
    }
  AcquireSRWLockExclusive (&npfs_lock);
  if (!npfs_dirh)
    {
      InitializeObjectAttributes (&attr, &ro_u_npfs, 0, NULL, NULL);
      status = NtOpenFile (&npfs_dirh, FILE_READ_ATTRIBUTES | SYNCHRONIZE,
			   &attr, &io, FILE_SHARE_READ | FILE_SHARE_WRITE,
			   0);
    }
  ReleaseSRWLockExclusive (&npfs_lock);
  if (NT_SUCCESS (status))
    nph = npfs_dirh;
  return status;
}

/* FIXME: What about close_on_exec? */
int
fhandler_socket_unix::create_mqueue (bool listener)
{
  mqd_t mqd;
  struct mq_attr attr;
  int flags = O_RDWR | O_CREAT | O_EXCL;
  mode_t mode = S_IRUSR | S_IWUSR | S_IWGRP | S_IWOTH;

  if (mq_unlink (get_mqueue_name ()) < 0 && get_errno () != ENOENT)
    {
      debug_printf ("Can't unlink old mqueue, %E");
      return -1;
    }
  if (listener)
    {
      /* A listener can only handle one connection request at a time,
	 and it is small. */
      attr.mq_maxmsg = 1;
      attr.mq_msgsize = MAX_PATH;
    }
  else
    {
      attr.mq_maxmsg = 10;		/* Probably too small. */
      attr.mq_msgsize = MAX_AF_UN_PKT_LEN;
    }
  if (is_nonblocking ())
    flags |= O_NONBLOCK;
  mqd = mq_open (get_mqueue_name (), flags, mode, &attr);
  if (mqd == (mqd_t) -1)
    return -1;
  set_mqd_in (mqd);
  return 0;
}

mqd_t
fhandler_socket_unix::open_mqueue (const char *mqueue_name, bool nonblocking)
{
  int flags = O_WRONLY;
  if (nonblocking)
    flags |= O_NONBLOCK;
  return mq_open (mqueue_name, flags);
}

struct conn_wait_info_t
{
  fhandler_socket_unix *fh;
  mqd_t mqd;			/* Descriptor for listener's mqueue. */
};

/* Just hop to the wait_mqueue_thread method. */
DWORD WINAPI
connect_wait_func (LPVOID param)
{
  conn_wait_info_t *wait_info = (conn_wait_info_t *) param;
  return wait_info->fh->wait_mqueue_thread (wait_info->mqd);
}

/* Start a waiter thread to wait for the listener's mqueue to have space.
   In blocking mode, wait for the thread to finish.  In nonblocking mode
   just return with errno set to EINPROGRESS. */
int
fhandler_socket_unix::wait_mqueue (mqd_t mqd)
{
  conn_wait_info_t *wait_info;
  DWORD waitret, err;
  int ret = -1;
  HANDLE thr;
  PVOID param;

  if (!(cwt_termination_evt = create_event ()))
    return -1;
  wait_info = (conn_wait_info_t *) cmalloc (HEAP_3_FHANDLER, sizeof *wait_info);
  if (!wait_info)
    return -1;
  wait_info->fh = this;
  wait_info->mqd = mqd;
  cwt_param = (PVOID) wait_info;
  connect_wait_thr = CreateThread (NULL, PREFERRED_IO_BLKSIZE,
				   connect_wait_func, cwt_param, 0, NULL);
  if (!connect_wait_thr)
    {
      cfree (wait_info);
      __seterrno ();
      goto out;
    }
  if (is_nonblocking ())
    {
      set_errno (EINPROGRESS);
      goto out;
    }

  waitret = cygwait (connect_wait_thr, cw_infinite, cw_cancel | cw_sig_eintr);
  if (waitret == WAIT_OBJECT_0)
    GetExitCodeThread (connect_wait_thr, &err);
  else
    {
      SetEvent (cwt_termination_evt);
      NtWaitForSingleObject (connect_wait_thr, FALSE, NULL);
      GetExitCodeThread (connect_wait_thr, &err);
      waitret = WAIT_SIGNALED;
    }
  thr = InterlockedExchangePointer (&connect_wait_thr, NULL);
  if (thr)
    NtClose (thr);
  param = InterlockedExchangePointer (&cwt_param, NULL);
  if (param)
    cfree (param);
  switch (waitret)
    {
    case WAIT_CANCELED:
      pthread::static_cancel_self ();
      /*NOTREACHED*/
    case WAIT_SIGNALED:
      set_errno (EINTR);
      break;
    default:
      so_error (err);
      if (err)
	set_errno (err);
      else
	ret = 0;
      break;
    }
out:
  return ret;
}

int
fhandler_socket_unix::recv_peer_mqueue_name (bool set, bool timeout, mqd_t *mqd)
{
  af_unix_pkt_hdr_t *packet;
  size_t plen;
  mqd_t peer_mqd;
  int flags;
  ssize_t nr;
  timespec tm;

  plen = sizeof *packet + CYGWIN_MQUEUE_SOCKET_NAME_LEN + 1;
  packet = (af_unix_pkt_hdr_t *) alloca (plen);
  if (timeout)
    {
      set_mqueue_non_blocking (get_mqd_in (), false);
      clock_gettime (CLOCK_REALTIME, &tm);
      tm.tv_sec += AF_UNIX_CONNECT_TIMEOUT;
      nr = _mq_timedrecv (get_mqd_in (), (char *) packet, plen, &tm, 0);
      set_mqueue_non_blocking (get_mqd_in (), is_nonblocking ());
    }
  else
    nr = _mq_recv (get_mqd_in (), (char *) packet, plen, 0);
  if (nr < 0)
    {
      if (get_errno () == ETIMEDOUT)
	set_errno (ECONNABORTED);
      return -1;
    }
  flags = O_WRONLY;
  if (is_nonblocking ())
    flags |= O_NONBLOCK;
  peer_mqd = mq_open ((const char *) AF_UNIX_PKT_DATA (packet), flags);
  if (peer_mqd == (mqd_t) -1)
    return -1;
  if (set)
    set_mqd_out (peer_mqd);
  if (mqd)
    *mqd = peer_mqd;
  return 0;
}

/* A socket makes a connection request by sending its own mqueue name
   to the listener's mqueue, first creating its mqueue if necessary. */
int
fhandler_socket_unix::send_mqueue_name (mqd_t mqd, bool wait)
{
  size_t plen;
  size_t dlen = 0;
  af_unix_pkt_hdr_t *packet;
  const char *mqn = get_mqueue_name ();

  if (!mqn || !*mqn)
    {
      gen_mqueue_name ();
      mqn = get_mqueue_name ();
      if (get_mqd_in () == (mqd_t) -1 && create_mqueue () < 0)
	return -1;
    }
  dlen = CYGWIN_MQUEUE_SOCKET_NAME_LEN + 1;
  plen = sizeof *packet + dlen;
  packet = (af_unix_pkt_hdr_t *) alloca (plen);
  packet->init (true, _SHUT_NONE, 0, 0, dlen);
  memcpy (AF_UNIX_PKT_DATA (packet), mqn, dlen);
  if (!wait)
    return mq_send (mqd, (const char *) packet, packet->pckt_len,
		    af_un_prio_admin);
  timespec timeout;
  set_mqueue_non_blocking (mqd, false);
  clock_gettime (CLOCK_REALTIME, &timeout);
  timeout.tv_sec += AF_UNIX_CONNECT_TIMEOUT;
  return mq_timedsend (mqd, (const char *) packet, packet->pckt_len,
		       af_un_prio_admin, &timeout);
}

int
fhandler_socket_unix::connect_mqueue (const char *mqueue_name)
{
  int ret = -1;
  int error = 0;
  mqd_t mqd;

  mqd = mq_open (mqueue_name, O_WRONLY | O_NONBLOCK);

  if (mqd == (mqd_t) -1)
    return -1;
  /* Try sending my mqueue name.  If it doesn't work, wait for the
     listener's mqueue to become available. */
  ret = send_mqueue_name (mqd, false);
  if (ret < 0 && get_errno () == EAGAIN)
    return wait_mqueue (mqd);
  if (ret < 0)
    {
      error = get_errno ();
      goto out;
    }
  /* Wait for response, which should be peer's mqueue name. */
  ret = recv_peer_mqueue_name ();
  if (ret < 0)
    {
      error =get_errno ();
      goto out;
    }
  xchg_sock_info ();
out:
  so_error (error);
  mq_close (mqd);
  return ret;
}

ssize_t
fhandler_socket_unix::peek_mqueue (char *buf, size_t buflen, bool nonblocking)
{
  if (get_mqd_in () == (mqd_t) -1)
    {
      /* FIXME: Set appropriate errno. */
      return -1;
    }
  return _mq_peek (get_mqd_in (), buf, buflen, nonblocking);
}

int
fhandler_socket_unix::disconnect_pipe (HANDLE ph)
{
  NTSTATUS status;
  IO_STATUS_BLOCK io;

  status = NtFsControlFile (ph, NULL, NULL, NULL, &io, FSCTL_PIPE_DISCONNECT,
			    NULL, 0, NULL, 0);
  /* Short-lived.  Don't use cygwait.  We don't want to be interrupted. */
  if (status == STATUS_PENDING
      && NtWaitForSingleObject (ph, FALSE, NULL) == WAIT_OBJECT_0)
    status = io.Status;
  if (!NT_SUCCESS (status))
    {
      __seterrno_from_nt_status (status);
      return -1;
    }
  return 0;
}

void
fhandler_socket_unix::init_cred ()
{
  struct ucred *scred = shmem->sock_cred ();
  struct ucred *pcred = shmem->peer_cred ();
  scred->pid = pcred->pid = (pid_t) 0;
  scred->uid = pcred->uid = (uid_t) -1;
  scred->gid = pcred->gid = (gid_t) -1;
}

void
fhandler_socket_unix::set_cred ()
{
  struct ucred *scred = shmem->sock_cred ();
  scred->pid = myself->pid;
  scred->uid = myself->uid;
  scred->gid = myself->gid;
}

void
fhandler_socket_unix::fixup_helper ()
{
  if (shmem_handle)
    reopen_shmem ();
  connect_wait_thr = NULL;
  cwt_termination_evt = NULL;
  cwt_param = NULL;
  inc_ndesc ();
}

/* ========================== public methods ========================= */

void
fhandler_socket_unix::fixup_after_fork (HANDLE parent)
{
  fhandler_socket::fixup_after_fork (parent);
  if (backing_file_handle && backing_file_handle != INVALID_HANDLE_VALUE)
    fork_fixup (parent, backing_file_handle, "backing_file_handle");
  if (shmem_handle)
    fork_fixup (parent, shmem_handle, "shmem_handle");
  fixup_helper ();
}

void
fhandler_socket_unix::fixup_after_exec ()
{
  if (!close_on_exec ())
    fixup_helper ();
}

void
fhandler_socket_unix::set_close_on_exec (bool val)
{
  fhandler_base::set_close_on_exec (val);
  if (backing_file_handle && backing_file_handle != INVALID_HANDLE_VALUE)
    set_no_inheritance (backing_file_handle, val);
  if (shmem_handle)
    set_no_inheritance (shmem_handle, val);
}

fhandler_socket_unix::fhandler_socket_unix () :
  fhandler_socket (),
  mqd_in ((mqd_t) -1), mqd_out ((mqd_t) -1),
  shmem_handle (NULL), shmem (NULL), backing_file_handle (NULL),
  connect_wait_thr (NULL), cwt_termination_evt (NULL), cwt_param (NULL)
{
  need_fork_fixup (true);
}

fhandler_socket_unix::~fhandler_socket_unix ()
{
}

int
fhandler_socket_unix::dup (fhandler_base *child, int flags)
{
  if (get_flags () & O_PATH)
    /* We're viewing the socket as a disk file, but fhandler_base::dup
       suffices here. */
    return fhandler_base::dup (child, flags);

  if (fhandler_socket::dup (child, flags))
    {
      __seterrno ();
      return -1;
    }
  fhandler_socket_unix *fhs = (fhandler_socket_unix *) child;
  if (backing_file_handle && backing_file_handle != INVALID_HANDLE_VALUE
      && !DuplicateHandle (GetCurrentProcess (), backing_file_handle,
			    GetCurrentProcess (), &fhs->backing_file_handle,
			    0, TRUE, DUPLICATE_SAME_ACCESS))
    {
      __seterrno ();
      fhs->close ();
      return -1;
    }
  if (!DuplicateHandle (GetCurrentProcess (), shmem_handle,
			GetCurrentProcess (), &fhs->shmem_handle,
			0, TRUE, DUPLICATE_SAME_ACCESS))
    {
      __seterrno ();
      fhs->close ();
      return -1;
    }
  if (fhs->reopen_shmem () < 0)
    {
      __seterrno ();
      fhs->close ();
      return -1;
    }
  fhs->sun_path (sun_path ());
  fhs->peer_sun_path (peer_sun_path ());
  fhs->connect_wait_thr = NULL;
  fhs->cwt_termination_evt = NULL;
  fhs->cwt_param = NULL;
  inc_ndesc ();
  return 0;
}

/* Waiter thread method.  Here we wait for the listener's mqueue to
   become available and send our mqueue name to it, if so.  This
   function is running asynchronously if called on a non-blocking
   socket.  The important things to do:

   - Set the output mqueue descriptor if successful
   - Send own sun_path to peer if successful
   - Set connect_state
   - Set so_error for later call to select
*/
DWORD
fhandler_socket_unix::wait_mqueue_thread (mqd_t mqd)
{
  LONG error = 0;

  /* Try for up to AF_UNIX_CONNECT_TIMEOUT seconds to send my mqueue
     name to listening socket. */
  if (send_mqueue_name (mqd, true) < 0)
    {
      error = get_errno ();
      goto out;
    }
  /* Read response from peer, which should be its mqueue name. */
  if (recv_peer_mqueue_name () < 0)
    {
      error = get_errno ();
      goto out;
    }
  xchg_sock_info ();
  /* FIXME: Translate mq errors to socket errors. */
out:
  mq_close (mqd);
  PVOID param = InterlockedExchangePointer (&cwt_param, NULL);
  if (param)
    cfree (param);
  conn_lock ();
  state_lock ();
  so_error (error);
  connect_state (error ? connect_failed : connected);
  state_unlock ();
  conn_unlock ();
  return error;
}

int
fhandler_socket_unix::socket (int af, int type, int protocol, int flags)
{
  if (type != SOCK_STREAM && type != SOCK_DGRAM)
    {
      set_errno (EINVAL);
      return -1;
    }
  if (protocol != 0)
    {
      set_errno (EPROTONOSUPPORT);
      return -1;
    }
  if (create_shmem () < 0)
    return -1;
  /* rmem and wmem have no effect in mqueue implementation. */
  /* rmem (262144); */
  /* wmem (262144); */
  set_addr_family (AF_UNIX);
  set_socket_type (type);
  set_flags (O_RDWR | O_BINARY);
  if (flags & SOCK_NONBLOCK)
    set_nonblocking (true);
  if (flags & SOCK_CLOEXEC)
    set_close_on_exec (true);
  init_cred ();
  set_handle (NULL);
  set_unique_id ();
  set_ino (get_unique_id ());
  inc_ndesc ();
  return 0;
}

int
fhandler_socket_unix::socketpair (int af, int type, int protocol, int flags,
				  fhandler_socket *fh_out)
{
  mqd_t mqd;
  sun_name_t sun;
  fhandler_socket_unix *fh = (fhandler_socket_unix *) fh_out;

  if (type != SOCK_STREAM && type != SOCK_DGRAM)
    {
      set_errno (EINVAL);
      return -1;
    }
  if (protocol != 0)
    {
      set_errno (EPROTONOSUPPORT);
      return -1;
    }

  if (create_shmem () < 0)
    return -1;
  if (fh->create_shmem () < 0)
    goto fh_shmem_failed;
  /* socket() on both sockets */
  /* rmem (262144); */
  /* fh->rmem (262144); */
  /* wmem (262144); */
  /* fh->wmem (262144); */
  set_addr_family (AF_UNIX);
  fh->set_addr_family (AF_UNIX);
  set_socket_type (type);
  fh->set_socket_type (type);
  set_flags (O_RDWR | O_BINARY);
  fh->set_flags (O_RDWR | O_BINARY);
  if (flags & SOCK_NONBLOCK)
    {
      set_nonblocking (true);
      fh->set_nonblocking (true);
    }
  if (flags & SOCK_CLOEXEC)
    {
      set_close_on_exec (true);
      fh->set_close_on_exec (true);
    }
  set_cred ();
  fh->set_cred ();
  set_unique_id ();
  fh->set_unique_id ();
  set_ino (get_unique_id ());
  fh->set_ino (fh->get_unique_id ());
  /* Create and open mqueues. */
  gen_mqueue_name ();
  if (create_mqueue () < 0)
    goto create_mqueue_failed;
  mqd = fh->open_mqueue (get_mqueue_name (), is_nonblocking ());
  if (mqd == (mqd_t) -1)
    goto fh_open_mqueue_failed;
  fh->set_mqd_out (mqd);
  fh->gen_mqueue_name ();
  if (fh->create_mqueue () < 0)
    goto fh_create_mqueue_failed;
  mqd = open_mqueue (get_mqueue_name (), is_nonblocking ());
  if (mqd == (mqd_t) -1)
    goto open_mqueue_failed;
  set_mqd_out (mqd);
  /* bind 1st socket */
  sun_path (&sun);
  fh->peer_sun_path (&sun);
  connect_state (connected);
  /* connect 2nd socket, even for DGRAM.  There's no difference as far
     as socketpairs are concerned. */
  fh->connect_state (connected);
  return 0;
open_mqueue_failed:
  mq_close (fh->get_mqd_in ());
  mq_unlink (fh->get_mqueue_name ());
fh_create_mqueue_failed:
  mq_close (fh->get_mqd_out ());
fh_open_mqueue_failed:
  mq_close (get_mqd_in ());
  mq_unlink (get_mqueue_name ());
create_mqueue_failed:
  NtUnmapViewOfSection (NtCurrentProcess (), fh->shmem);
  NtClose (fh->shmem_handle);
fh_shmem_failed:
  NtUnmapViewOfSection (NtCurrentProcess (), shmem);
  NtClose (shmem_handle);
  return -1;
}

/* Bind creates the backing file, generates the mqueue name and sets
   bind_state.  On DGRAM sockets it also creates the mqueue.  On STREAM
   sockets either listen or connect will do that. */
int
fhandler_socket_unix::bind (const struct sockaddr *name, int namelen)
{
  sun_name_t sun (name, namelen);
  bool unnamed = (sun.un_len == sizeof sun.un.sun_family);

  if (sun.un.sun_family != AF_UNIX)
    {
      set_errno (EINVAL);
      return -1;
    }
  bind_lock ();
  if (binding_state () == bind_pending)
    {
      set_errno (EALREADY);
      bind_unlock ();
      return -1;
    }
  if (binding_state () == bound)
    {
      set_errno (EINVAL);
      bind_unlock ();
      return -1;
    }
  binding_state (bind_pending);
  bind_unlock ();
  gen_mqueue_name ();
  if (get_socket_type () == SOCK_DGRAM && create_mqueue () < 0)
    {
      binding_state (unbound);
      return -1;
    }
  backing_file_handle = unnamed ? autobind (&sun) : create_socket (&sun);
  if (!backing_file_handle)
    {
      if (get_mqd_in () != (mqd_t) -1)
	{
	  mq_close (get_mqd_in ());
	  mq_unlink (get_mqueue_name ());
	}
      binding_state (unbound);
      return -1;
    }
  state_lock ();
  sun_path (&sun);
  /* If we're already connected, send socket info to peer.  In this case
     send_sock_info calls state_unlock */
  if (connect_state () == connected)
    send_sock_info (true);
  else
    state_unlock ();
  binding_state (bound);
  return 0;
}

/* Create mqueue on non-DGRAM sockets and set conn_state to listener. */
int
fhandler_socket_unix::listen (int backlog)
{
  if (get_socket_type () == SOCK_DGRAM)
    {
      set_errno (EOPNOTSUPP);
      return -1;
    }
  bind_lock ();
  while (binding_state () == bind_pending)
    yield ();
  if (binding_state () == unbound)
    {
      set_errno (EDESTADDRREQ);
      bind_unlock ();
      return -1;
    }
  bind_unlock ();
  conn_lock ();
  if (connect_state () != unconnected && connect_state () != connect_failed)
    {
      set_errno (connect_state () == listener ? EADDRINUSE : EINVAL);
      conn_unlock ();
      return -1;
    }
  if (create_mqueue (true) < 0)
    {
      connect_state (unconnected);
      return -1;
    }
  state_lock ();
  set_cred ();
  state_unlock ();
  connect_state (listener);
  conn_unlock ();
  return 0;
}

int
fhandler_socket_unix::accept4 (struct sockaddr *peer, int *len, int flags)
{
  mqd_t peer_mqd;
  fhandler_socket_unix *sock;

  if (get_socket_type () != SOCK_STREAM)
    {
      set_errno (EOPNOTSUPP);
      return -1;
    }
  if (connect_state () != listener
      || (peer && (!len || *len < (int) sizeof (sa_family_t))))
    {
      set_errno (EINVAL);
      return -1;
    }

  if (recv_peer_mqueue_name (false, false, &peer_mqd) < 0)
    return -1;
  if (flags & SOCK_NONBLOCK)
    set_mqueue_non_blocking (peer_mqd, true);
  /* We now have an mqueue descriptor that the accepted socket can use
     for output.  Prepare new file descriptor. */
  int error = ENOBUFS;
  cygheap_fdnew fd;
  if (fd < 0)
    goto err;
  sock = (fhandler_socket_unix *) build_fh_dev (dev ());
  if (!sock)
    goto err;
  if (sock->create_shmem () < 0)
    goto create_shmem_failed;
  sock->set_addr_family (AF_UNIX);
  sock->set_socket_type (get_socket_type ());
  if (flags & SOCK_NONBLOCK)
    sock->set_nonblocking (true);
  if (flags & SOCK_CLOEXEC)
    sock->set_close_on_exec (true);
  sock->set_unique_id ();
  sock->set_ino (sock->get_unique_id ());
  sock->set_mqd_out (peer_mqd);
  if (sock->send_mqueue_name (peer_mqd, false) < 0)
    {
      error = get_errno ();
      goto send_mqueue_name_failed;
    }
  sock->connect_state (connected);
  sock->binding_state (binding_state ());
  sock->sun_path (sun_path ());
  sock->sock_cred (sock_cred ());
  /* Send this socket info to connecting socket. */
  sock->send_sock_info (false);
  /* Fetch the packet sent by send_sock_info called by connecting
     peer. */
  error = sock->recv_peer_info ();
  if (error == 0)
    {
      __try
	{
	  if (peer)
	    {
	      sun_name_t *sun = sock->peer_sun_path ();
	      if (sun)
		{
		  memcpy (peer, &sun->un, MIN (*len, sun->un_len));
		  *len = sun->un_len;
		}
	      else if (len)
		*len = 0;
	    }
	  fd = sock;
	  if (fd <= 2)
	    set_std_handle (fd);
	  return fd;
	}
      __except (NO_ERROR)
	{
	  error = EFAULT;
	}
      __endtry
    }
send_mqueue_name_failed:
  if (sock->get_mqd_in () != (mqd_t) -1)
    {
      mq_close (sock->get_mqd_in ());
      mq_unlink (sock->get_mqueue_name ());
    }
  NtUnmapViewOfSection (NtCurrentProcess (), sock->shmem);
  NtClose (sock->shmem_handle);
create_shmem_failed:
  delete sock;
err:
  set_errno (error);
  mq_close (peer_mqd);
  return -1;
}

int
fhandler_socket_unix::connect (const struct sockaddr *name, int namelen)
{
  sun_name_t sun (name, namelen);
  int peer_type;
  char mqueue_name[CYGWIN_MQUEUE_SOCKET_NAME_LEN + 1];
  HANDLE fh = NULL;

  /* Test and set connection state. */
  conn_lock ();
  if (connect_state () == connect_pending)
    {
      set_errno (EALREADY);
      conn_unlock ();
      return -1;
    }
  if (connect_state () == listener)
    {
      set_errno (EADDRINUSE);
      conn_unlock ();
      return -1;
    }
  if (connect_state () == connected && get_socket_type () != SOCK_DGRAM)
    {
      set_errno (EISCONN);
      conn_unlock ();
      return -1;
    }
  if (name->sa_family == AF_UNSPEC && get_socket_type () == SOCK_DGRAM)
    {
      connect_state (unconnected);
      peer_sun_path (NULL);
      conn_unlock ();
      return 0;
    }
  connect_state (connect_pending);
  conn_unlock ();
  /* Check if peer address exists. */
  fh = open_socket (&sun, peer_type, mqueue_name);
  if (!fh)
    {
      connect_state (unconnected);
      return -1;
    }
  if (peer_type != get_socket_type ())
    {
      set_errno (EINVAL);
      NtClose (fh);
      connect_state (unconnected);
      return -1;
    }
  peer_sun_path (&sun);
  if (get_socket_type () != SOCK_DGRAM && connect_mqueue (mqueue_name) < 0)
    {
      NtClose (fh);
      if (get_errno () != EINPROGRESS)
	{
	  peer_sun_path (NULL);
	  connect_state (connect_failed);
	}
      return -1;
    }
  NtClose (fh);
  connect_state (connected);
  return 0;
}

int
fhandler_socket_unix::getsockname (struct sockaddr *name, int *namelen)
{
  sun_name_t *sun = sun_path ();

  memcpy (name, sun, MIN (*namelen, sun->un_len));
  *namelen = sun->un_len;
  return 0;
}

int
fhandler_socket_unix::getpeername (struct sockaddr *name, int *namelen)
{
  if (connect_state () != connected)
    {
      set_errno (ENOTCONN);
      return -1;
    }

  sun_name_t *sun = peer_sun_path ();
  memcpy (name, sun, MIN (*namelen, sun->un_len));
  *namelen = sun->un_len;
  return 0;
}

int
fhandler_socket_unix::shutdown (int how)
{
  int ret;

  if (how < SHUT_RD || how > SHUT_RDWR)
    {
      set_errno (EINVAL);
      return -1;
    }
  if (connect_state () != connected)
    {
      set_errno (ENOTCONN);
      return -1;
    }
  /* Convert SHUT_RD/SHUT_WR/SHUT_RDWR to _SHUT_RECV/_SHUT_SEND bits. */
  ++how;
  state_lock ();
  int old_shutdown_mask = saw_shutdown ();
  int new_shutdown_mask = old_shutdown_mask | how;
  if (new_shutdown_mask != old_shutdown_mask)
    saw_shutdown (new_shutdown_mask);
  state_unlock ();
  if (new_shutdown_mask != old_shutdown_mask
      && get_socket_type () == SOCK_STREAM)
    {
      /* Send shutdown info to peer.  Note that it's not necessarily fatal
	 if the info isn't sent here.  The info will be reproduced by any
	 followup package sent to the peer. */
      af_unix_pkt_hdr_t packet (true, (shut_state) new_shutdown_mask, 0, 0, 0);
      io_lock ();
      set_mqueue_non_blocking (get_mqd_out (), true);
      ret = mq_send (get_mqd_out (), (const char *) &packet, packet.pckt_len,
		     af_un_prio_admin);
      set_mqueue_non_blocking (get_mqd_out (), is_nonblocking ());
      io_unlock ();
    }
  if (ret < 0)
    {
      debug_printf ("Couldn't send shutdown info, %E");
      if (get_errno () != EAGAIN)
	return -1;
    }
  return 0;
}

int
fhandler_socket_unix::open (int flags, mode_t mode)
{
  /* We don't support opening sockets unless O_PATH is specified. */
  if (flags & O_PATH)
    return open_fs (flags, mode);

  set_errno (EOPNOTSUPP);
  return 0;
}

int
fhandler_socket_unix::close ()
{
  int ret = 0;

  if (get_flags () & O_PATH)
    return fhandler_base::close ();

  HANDLE evt = InterlockedExchangePointer (&cwt_termination_evt, NULL);
  HANDLE thr = InterlockedExchangePointer (&connect_wait_thr, NULL);
  if (thr)
    {
      if (evt)
	SetEvent (evt);
      NtWaitForSingleObject (thr, FALSE, NULL);
      NtClose (thr);
    }
  if (evt)
    NtClose (evt);
  PVOID param = InterlockedExchangePointer (&cwt_param, NULL);
  if (param)
    cfree (param);
  HANDLE hdl = InterlockedExchangePointer (&get_handle (), NULL);
  if (hdl)
    NtClose (hdl);
  if (backing_file_handle && backing_file_handle != INVALID_HANDLE_VALUE)
    NtClose (backing_file_handle);
  HANDLE shm = InterlockedExchangePointer (&shmem_handle, NULL);
  if (shm)
    NtClose (shm);
  param = InterlockedExchangePointer ((PVOID *) &shmem, NULL);
  if (param)
    NtUnmapViewOfSection (NtCurrentProcess (), param);
  if (get_mqd_in () != (mqd_t) -1)
    ret = mq_close (get_mqd_in ());
  if (get_mqd_out () != (mqd_t) -1)
    ret |= mq_close (get_mqd_out ());
  if (dec_ndesc () <= 0)
    {
      shutdown (SHUT_RDWR);
      mq_unlink (get_mqueue_name ());
    }
  return ret;
}

int
fhandler_socket_unix::getpeereid (pid_t *pid, uid_t *euid, gid_t *egid)
{
  int ret = -1;

  if (get_socket_type () != SOCK_STREAM)
    {
      set_errno (EINVAL);
      return -1;
    }
  if (connect_state () != connected)
    set_errno (ENOTCONN);
  else
    {
      __try
	{
	  state_lock ();
	  struct ucred *pcred = peer_cred ();
	  if (pid)
	    *pid = pcred->pid;
	  if (euid)
	    *euid = pcred->uid;
	  if (egid)
	    *egid = pcred->gid;
	  state_unlock ();
	  ret = 0;
	}
      __except (EFAULT) {}
      __endtry
    }
  return ret;
}

ssize_t
fhandler_socket_unix::recvmsg (struct msghdr *msg, int flags)
{
  set_errno (EAFNOSUPPORT);
  return -1;
}

ssize_t
fhandler_socket_unix::recvfrom (void *ptr, size_t len, int flags,
				struct sockaddr *from, int *fromlen)
{
  struct iovec iov;
  struct msghdr msg;
  ssize_t ret;

  iov.iov_base = ptr;
  iov.iov_len = len;
  msg.msg_name = from;
  msg.msg_namelen = from && fromlen ? *fromlen : 0;
  msg.msg_iov = &iov;
  msg.msg_iovlen = 1;
  msg.msg_control = NULL;
  msg.msg_controllen = 0;
  msg.msg_flags = 0;
  ret = recvmsg (&msg, flags);
  if (ret >= 0 && from && fromlen)
    *fromlen = msg.msg_namelen;
  return ret;
}

void __reg3
fhandler_socket_unix::read (void *ptr, size_t& len)
{
  set_errno (EAFNOSUPPORT);
  len = 0;
  struct iovec iov;
  struct msghdr msg;

  iov.iov_base = ptr;
  iov.iov_len = len;
  msg.msg_name = NULL;
  msg.msg_namelen = 0;
  msg.msg_iov = &iov;
  msg.msg_iovlen = 1;
  msg.msg_control = NULL;
  msg.msg_controllen = 0;
  msg.msg_flags = 0;
  len = recvmsg (&msg, 0);
}

ssize_t __stdcall
fhandler_socket_unix::readv (const struct iovec *const iov, int iovcnt,
			     ssize_t tot)
{
  struct msghdr msg;

  msg.msg_name = NULL;
  msg.msg_namelen = 0;
  msg.msg_iov = (struct iovec *) iov;
  msg.msg_iovlen = iovcnt;
  msg.msg_control = NULL;
  msg.msg_controllen = 0;
  msg.msg_flags = 0;
  return recvmsg (&msg, 0);
}

bool
fhandler_socket_unix::create_cmsg_data (af_unix_pkt_hdr_t *packet,
					const struct msghdr *msg)
{
  return true;
}


ssize_t
fhandler_socket_unix::sendmsg (const struct msghdr *msg, int flags)
{
  tmp_pathbuf tp;
  char mqueue_name[CYGWIN_MQUEUE_SOCKET_NAME_LEN + 1];
  ssize_t ret = -1;
  int send_ret = -1;
  HANDLE fh = NULL;
  mqd_t mqd_dgram = (mqd_t) -1;
  mqd_t mqd_out;
  af_unix_pkt_hdr_t *packet;
  int err;

  __try
    {
      /* Valid flags: MSG_DONTWAIT, MSG_NOSIGNAL */
      if (flags & ~(MSG_DONTWAIT | MSG_NOSIGNAL))
	{
	  set_errno (EOPNOTSUPP);
	  __leave;
	}
      /* FIXME: Check this.  It's from Stevens, UNIX Network
	 Programming, discussion of select.  He doesn't say whether we
	 also clear so_error.*/
      err = so_error ();
      if (err)
	{
	  set_errno (err);
	  __leave;
	}
      if (get_socket_type () == SOCK_STREAM)
	{
	  if (msg->msg_namelen)
	    {
	      set_errno (connect_state () == connected ? EISCONN : EOPNOTSUPP);
	      __leave;
	    }
	  if (connect_state () != connected)
	    {
	      set_errno (ENOTCONN);
	      __leave;
	    }
	}
      else
	{
	  sun_name_t sun;
	  int peer_type;

	  if (msg->msg_namelen)
	    sun.set ((const struct sockaddr_un *) msg->msg_name,
		     msg->msg_namelen);
	  else
	    sun = *peer_sun_path ();
	  fh = open_socket (&sun, peer_type, mqueue_name);
	  if (!fh)
	    __leave;
	  NtClose (fh);
	  if (peer_type != SOCK_DGRAM)
	    {
	      set_errno (EPROTOTYPE);
	      __leave;
	    }
	  mqd_dgram = open_mqueue (mqueue_name,
			     is_nonblocking () || flags & MSG_DONTWAIT);
	  if (mqd_dgram == (mqd_t) -1)
	    __leave;
	}
      packet = (af_unix_pkt_hdr_t *) tp.w_get ();
      /* For STREAM sockets, always send shutdown info in case a
	 shutdown call failed. */
      shut_state shut_info =
	get_socket_type () == SOCK_STREAM
	? (shut_state) saw_shutdown ()
	: _SHUT_NONE;
      if (get_socket_type () == SOCK_DGRAM && binding_state () == bound)
	{
	  packet->init (false, shut_info, sun_path ()->un_len, 0, 0);
	  memcpy (AF_UNIX_PKT_NAME (packet), &sun_path ()->un,
		  sun_path ()->un_len);
	}
      else
	packet->init (false, shut_info, 0, 0, 0);
      if (!create_cmsg_data (packet, msg))
	__leave;
      for (int i = 0; i < msg->msg_iovlen; ++i)
	if (!AF_UNIX_PKT_DATA_APPEND (packet, msg->msg_iov[i].iov_base,
				      msg->msg_iov[i].iov_len))
	  {
	    if (packet->data_len == 0)
	      {
		set_errno (EMSGSIZE);
		__leave;
	      }
	    else
	      break;
	  }
      /* A packet can have 0 length only on a datagram socket. */
      if (packet->data_len == 0 && get_socket_type () == SOCK_STREAM)
	{
	  ret = 0;
	  __leave;
	}
      io_lock ();
      /* Handle MSG_DONTWAIT in blocking mode.  Already done in DGRAM case. */
      if (get_socket_type () == SOCK_STREAM && !is_nonblocking ()
	  && (flags & MSG_DONTWAIT))
	set_mqueue_non_blocking (get_mqd_out (), true);

      mqd_out = mqd_dgram != (mqd_t) -1 ? mqd_dgram : get_mqd_out ();
      bool nonblocking = is_nonblocking () || (flags & MSG_DONTWAIT);
      grab_admin_pkt ();
      bool shutdown = saw_shutdown_write ();
      if (!shutdown && nonblocking)
	send_ret = mq_send (mqd_out, (const char *) packet,
			    packet->pckt_len, 0);
      else
	{
	  /* FIXME: Is this reasonable? */
#define AF_UNIX_SEND_TIMEOUT 10 * NSPERSEC/MSPERSEC      /* 10 ms */
	  struct timespec timeout;
	  clock_gettime (CLOCK_REALTIME, &timeout);
	  while (!shutdown)
	    {
	      /* We don't want to block forever if the peer has shut
		 down.  FIXME: This might only be appropriate for
		 STREAM sockets. */
	      timeout.tv_nsec += AF_UNIX_SEND_TIMEOUT;
	      if (timeout.tv_nsec >= NSPERSEC)
		{
		  timeout.tv_nsec -= NSPERSEC;
		  ++timeout.tv_sec;
		}
	      send_ret = mq_timedsend (mqd_out, (const char *) packet,
				       packet->pckt_len, 0, &timeout);
	      if (send_ret >= 0 || get_errno () != ETIMEDOUT)
		break;
	      grab_admin_pkt ();
	      shutdown = saw_shutdown_write ();
	    }
	}
      if (get_socket_type () == SOCK_STREAM && !is_nonblocking ()
	  && (flags & MSG_DONTWAIT))
	set_mqueue_non_blocking (get_mqd_out (), false);
      io_unlock ();
      if (send_ret == 0)
	ret = packet->data_len;
      else if (shutdown && get_socket_type () == SOCK_STREAM)
	{
	  set_errno (EPIPE);
	  if (!(flags & MSG_NOSIGNAL))
	    raise (SIGPIPE);
	}
    }
  __except (EFAULT)
  __endtry
  if (mqd_dgram != (mqd_t) -1)
    mq_close (mqd_dgram);
  return ret;
}

ssize_t
fhandler_socket_unix::sendto (const void *in_ptr, size_t len, int flags,
			       const struct sockaddr *to, int tolen)
{
  struct iovec iov;
  struct msghdr msg;

  iov.iov_base = (void *) in_ptr;
  iov.iov_len = len;
  msg.msg_name = (void *) to;
  msg.msg_namelen = to ? tolen : 0;
  msg.msg_iov = &iov;
  msg.msg_iovlen = 1;
  msg.msg_control = NULL;
  msg.msg_controllen = 0;
  msg.msg_flags = 0;
  return sendmsg (&msg, flags);
}

ssize_t __stdcall
fhandler_socket_unix::write (const void *ptr, size_t len)
{
  struct iovec iov;
  struct msghdr msg;

  iov.iov_base = (void *) ptr;
  iov.iov_len = len;
  msg.msg_name = NULL;
  msg.msg_namelen = 0;
  msg.msg_iov = &iov;
  msg.msg_iovlen = 1;
  msg.msg_control = NULL;
  msg.msg_controllen = 0;
  msg.msg_flags = 0;
  return sendmsg (&msg, 0);
}

ssize_t __stdcall
fhandler_socket_unix::writev (const struct iovec *const iov, int iovcnt,
			      ssize_t tot)
{
  struct msghdr msg;

  msg.msg_name = NULL;
  msg.msg_namelen = 0;
  msg.msg_iov = (struct iovec *) iov;
  msg.msg_iovlen = iovcnt;
  msg.msg_control = NULL;
  msg.msg_controllen = 0;
  msg.msg_flags = 0;
  return sendmsg (&msg, 0);
}

int
fhandler_socket_unix::setsockopt (int level, int optname, const void *optval,
				   socklen_t optlen)
{
  /* Preprocessing setsockopt. */
  switch (level)
    {
    case SOL_SOCKET:
      switch (optname)
	{
	case SO_PASSCRED:
	  if (optlen < (socklen_t) sizeof (int))
	    {
	      set_errno (EINVAL);
	      return -1;
	    }

	  bool val;
	  val = !!*(int *) optval;
	  /* Using bind_lock here to make sure the autobind below is
	     covered.  This is the only place to set so_passcred anyway. */
	  bind_lock ();
	  if (val && binding_state () == unbound)
	    {
	      sun_name_t sun;

	      binding_state (bind_pending);
	      backing_file_handle = autobind (&sun);
	      if (!backing_file_handle)
		{
		  binding_state (unbound);
		  bind_unlock ();
		  return -1;
		}
	      sun_path (&sun);
	      binding_state (bound);
	    }
	  so_passcred (val);
	  bind_unlock ();
	  break;

	case SO_REUSEADDR:
	  if (optlen < (socklen_t) sizeof (int))
	    {
	      set_errno (EINVAL);
	      return -1;
	    }
	  reuseaddr (!!*(int *) optval);
	  break;

	case SO_RCVBUF:
	  if (optlen < (socklen_t) sizeof (int))
	    {
	      set_errno (EINVAL);
	      return -1;
	    }
	  rmem (*(int *) optval);
	  break;

	case SO_SNDBUF:
	  if (optlen < (socklen_t) sizeof (int))
	    {
	      set_errno (EINVAL);
	      return -1;
	    }
	  wmem (*(int *) optval);
	  break;

	case SO_RCVTIMEO:
	case SO_SNDTIMEO:
	  if (optlen < (socklen_t) sizeof (struct timeval))
	    {
	      set_errno (EINVAL);
	      return -1;
	    }
	  if (!timeval_to_ms ((struct timeval *) optval,
			      (optname == SO_RCVTIMEO) ? rcvtimeo ()
						       : sndtimeo ()))
	  {
	    set_errno (EDOM);
	    return -1;
	  }
	  break;

	default:
	  /* AF_UNIX sockets simply ignore all other SOL_SOCKET options. */
	  break;
	}
      break;

    default:
      set_errno (ENOPROTOOPT);
      return -1;
    }

  return 0;
}

int
fhandler_socket_unix::getsockopt (int level, int optname, const void *optval,
				   socklen_t *optlen)
{
  /* Preprocessing getsockopt.*/
  switch (level)
    {
    case SOL_SOCKET:
      switch (optname)
	{
	case SO_ERROR:
	  {
	    if (*optlen < (socklen_t) sizeof (int))
	      {
		set_errno (EINVAL);
		return -1;
	      }

	    int *e = (int *) optval;
	    LONG err;

	    err = so_error (0);
	    *e = err;
	    break;
	  }

	case SO_PASSCRED:
	  {
	    if (*optlen < (socklen_t) sizeof (int))
	      {
		set_errno (EINVAL);
		return -1;
	      }

	    int *e = (int *) optval;
	    *e = so_passcred ();
	    break;
	  }

	case SO_PEERCRED:
	  {
	    struct ucred *cred = (struct ucred *) optval;

	    if (*optlen < (socklen_t) sizeof *cred)
	      {
		set_errno (EINVAL);
		return -1;
	      }
	    int ret = getpeereid (&cred->pid, &cred->uid, &cred->gid);
	    if (!ret)
	      *optlen = (socklen_t) sizeof *cred;
	    return ret;
	  }

	case SO_REUSEADDR:
	  {
	    unsigned int *reuse = (unsigned int *) optval;

	    if (*optlen < (socklen_t) sizeof *reuse)
	      {
		set_errno (EINVAL);
		return -1;
	      }
	    *reuse = reuseaddr ();
	    *optlen = (socklen_t) sizeof *reuse;
	    break;
	  }

	case SO_RCVBUF:
	case SO_SNDBUF:
	  if (*optlen < (socklen_t) sizeof (int))
	    {
	      set_errno (EINVAL);
	      return -1;
	    }
	  *(int *) optval = (optname == SO_RCVBUF) ? rmem () : wmem ();
	  break;

	case SO_RCVTIMEO:
	case SO_SNDTIMEO:
	  {
	    struct timeval *time_out = (struct timeval *) optval;

	    if (*optlen < (socklen_t) sizeof *time_out)
	      {
		set_errno (EINVAL);
		return -1;
	      }
	    DWORD ms = (optname == SO_RCVTIMEO) ? rcvtimeo () : sndtimeo ();
	    if (ms == 0 || ms == INFINITE)
	      {
		time_out->tv_sec = 0;
		time_out->tv_usec = 0;
	      }
	    else
	      {
		time_out->tv_sec = ms / MSPERSEC;
		time_out->tv_usec = ((ms % MSPERSEC) * USPERSEC) / MSPERSEC;
	      }
	    *optlen = (socklen_t) sizeof *time_out;
	    break;
	  }

	case SO_TYPE:
	  {
	    if (*optlen < (socklen_t) sizeof (int))
	      {
		set_errno (EINVAL);
		return -1;
	      }
	    unsigned int *type = (unsigned int *) optval;
	    *type = get_socket_type ();
	    *optlen = (socklen_t) sizeof *type;
	    break;
	  }

	/* AF_UNIX sockets simply ignore all other SOL_SOCKET options. */

	case SO_LINGER:
	  {
	    if (*optlen < (socklen_t) sizeof (struct linger))
	      {
		set_errno (EINVAL);
		return -1;
	      }
	    struct linger *linger = (struct linger *) optval;
	    memset (linger, 0, sizeof *linger);
	    *optlen = (socklen_t) sizeof *linger;
	    break;
	  }

	default:
	  {
	    if (*optlen < (socklen_t) sizeof (int))
	      {
		set_errno (EINVAL);
		return -1;
	      }
	    unsigned int *val = (unsigned int *) optval;
	    *val = 0;
	    *optlen = (socklen_t) sizeof *val;
	    break;
	  }
	}
      break;

    default:
      set_errno (ENOPROTOOPT);
      return -1;
    }

  return 0;
}

int
fhandler_socket_unix::ioctl (unsigned int cmd, void *p)
{
  int ret = -1;

  switch (cmd)
    {
    case FIOASYNC:
#ifdef __x86_64__
    case _IOW('f', 125, int):
#endif
      break;
    case FIONREAD:
#ifdef __x86_64__
    case _IOR('f', 127, int):
#endif
    case FIONBIO:
      {
	const bool was_nonblocking = is_nonblocking ();
	set_nonblocking (*(int *) p);
	const bool now_nonblocking = is_nonblocking ();
	if (was_nonblocking != now_nonblocking)
	  set_pipe_non_blocking (now_nonblocking);
	ret = 0;
	break;
      }
    case SIOCATMARK:
      break;
    default:
      ret = fhandler_socket::ioctl (cmd, p);
      break;
    }
  return ret;
}

int
fhandler_socket_unix::fcntl (int cmd, intptr_t arg)
{
  if (get_flags () & O_PATH)
    /* We're viewing the socket as a disk file, but
       fhandler_base::fcntl suffices here. */
    return fhandler_base::fcntl (cmd, arg);

  int ret = -1;

  switch (cmd)
    {
    case F_SETOWN:
      break;
    case F_GETOWN:
      break;
    case F_SETFL:
      {
	const bool was_nonblocking = is_nonblocking ();
	const int allowed_flags = O_APPEND | O_NONBLOCK_MASK;
	int new_flags = arg & allowed_flags;
	if ((new_flags & OLD_O_NDELAY) && (new_flags & O_NONBLOCK))
	  new_flags &= ~OLD_O_NDELAY;
	set_flags ((get_flags () & ~allowed_flags) | new_flags);
	const bool now_nonblocking = is_nonblocking ();
	if (was_nonblocking != now_nonblocking)
	  set_pipe_non_blocking (now_nonblocking);
	ret = 0;
	break;
      }
    default:
      ret = fhandler_socket::fcntl (cmd, arg);
      break;
    }
  return ret;
}

int __reg2
fhandler_socket_unix::fstat (struct stat *buf)
{
  if (!dev ().isfs ())
    /* fstat called on a socket. */
    return fhandler_socket::fstat (buf);

  /* stat/lstat on a socket file or fstat on a socket opened w/ O_PATH. */
  int ret = fhandler_base::fstat_fs (buf);
  if (!ret)
    {
      buf->st_mode = (buf->st_mode & ~S_IFMT) | S_IFSOCK;
      buf->st_size = 0;
    }
  return ret;
}

int __reg2
fhandler_socket_unix::fstatvfs (struct statvfs *sfs)
{
  if (!dev ().isfs ())
    /* fstatvfs called on a socket. */
    return fhandler_socket::fstatvfs (sfs);

  /* statvfs on a socket file or fstatvfs on a socket opened w/ O_PATH. */
  if (get_flags () & O_PATH)
    /* We already have a handle. */
    {
      HANDLE h = get_handle ();
      if (h)
	return fstatvfs_by_handle (h, sfs);
    }
  fhandler_disk_file fh (pc);
  fh.get_device () = FH_FS;
  return fh.fstatvfs (sfs);
}

int
fhandler_socket_unix::fchmod (mode_t newmode)
{
  if (!dev ().isfs ())
    /* fchmod called on a socket. */
    return fhandler_socket::fchmod (newmode);

  /* chmod on a socket file.  [We won't get here if fchmod is called
     on a socket opened w/ O_PATH.] */
  fhandler_disk_file fh (pc);
  fh.get_device () = FH_FS;
  /* Kludge: Don't allow to remove read bit on socket files for
     user/group/other, if the accompanying write bit is set.  It would
     be nice to have exact permissions on a socket file, but it's
     necessary that somebody able to access the socket can always read
     the contents of the socket file to avoid spurious "permission
     denied" messages. */
  newmode |= (newmode & (S_IWUSR | S_IWGRP | S_IWOTH)) << 1;
  return fh.fchmod (S_IFSOCK | newmode);
}

int
fhandler_socket_unix::fchown (uid_t uid, gid_t gid)
{
  if (!dev ().isfs ())
    /* fchown called on a socket. */
    return fhandler_socket::fchown (uid, gid);

  /* chown/lchown on a socket file.  [We won't get here if fchown is
     called on a socket opened w/ O_PATH.] */
  fhandler_disk_file fh (pc);
  return fh.fchown (uid, gid);
}

int
fhandler_socket_unix::facl (int cmd, int nentries, aclent_t *aclbufp)
{
  if (!dev ().isfs ())
    /* facl called on a socket. */
    return fhandler_socket::facl (cmd, nentries, aclbufp);

  /* facl on a socket file.  [We won't get here if facl is called on a
     socket opened w/ O_PATH.] */
  fhandler_disk_file fh (pc);
  return fh.facl (cmd, nentries, aclbufp);
}

int
fhandler_socket_unix::link (const char *newpath)
{
  if (!dev ().isfs ())
    /* linkat w/ AT_EMPTY_PATH called on a socket not opened w/ O_PATH. */
    return fhandler_socket::link (newpath);
  /* link on a socket file or linkat w/ AT_EMPTY_PATH called on a
     socket opened w/ O_PATH. */
  fhandler_disk_file fh (pc);
  if (get_flags () & O_PATH)
    fh.set_handle (get_handle ());
  return fh.link (newpath);
}

#endif /* __WITH_AF_UNIX */