File: NSMessagePort.m

package info (click to toggle)
gnustep-base 1.31.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,580 kB
  • sloc: objc: 239,446; ansic: 36,519; cpp: 122; sh: 112; makefile: 100; xml: 32
file content (1950 lines) | stat: -rw-r--r-- 47,289 bytes parent folder | download | duplicates (2)
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
/** Implementation of network port object based on unix domain sockets
   Copyright (C) 2000 Free Software Foundation, Inc.

   Written by:  Richard Frith-Macdonald <richard@brainstorm.co.uk>
   Based on code by:  Andrew Kachites McCallum <mccallum@gnu.ai.mit.edu>

   This file is part of the GNUstep Base Library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 31 Milk Street #960789 Boston, MA 02196 USA.
   */

#import "common.h"
#define	EXPOSE_NSPort_IVARS	1
#define	EXPOSE_NSMessagePort_IVARS	1
#import "Foundation/NSArray.h"
#import "Foundation/NSAutoreleasePool.h"
#import "Foundation/NSNotification.h"
#import "Foundation/NSException.h"
#import "Foundation/NSRunLoop.h"
#import "Foundation/NSByteOrder.h"
#import "Foundation/NSData.h"
#import "Foundation/NSDate.h"
#import "Foundation/NSMapTable.h"
#import "Foundation/NSPortMessage.h"
#import "Foundation/NSPortNameServer.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSConnection.h"
#import "Foundation/NSPathUtilities.h"
#import "Foundation/NSValue.h"
#import "Foundation/NSFileManager.h"
#import "Foundation/NSProcessInfo.h"

#import "GSPrivate.h"
#import "GSNetwork.h"
#import "GSPortPrivate.h"

#include <stdio.h>

#include <sys/param.h>		/* for MAXHOSTNAMELEN */
#include <sys/types.h>
#include <sys/un.h>
#include <arpa/inet.h>		/* for inet_ntoa() */
#include <ctype.h>		/* for strchr() */

#if	defined(HAVE_SYS_FCNTL_H)
#  include	<sys/fcntl.h>
#elif	defined(HAVE_FCNTL_H)
#  include	<fcntl.h>
#endif

#include <sys/time.h>
#include <sys/resource.h>
#include <netdb.h>
#include <sys/socket.h>

#if	defined(HAVE_SYS_FILE_H)
#  include	<sys/file.h>
#endif

#include <sys/stat.h>

/*
 *	Stuff for setting the sockets into non-blocking mode.
 */
#if defined(__POSIX_SOURCE)\
        || defined(__EXT_POSIX1_198808)\
        || defined(O_NONBLOCK)
#define NBLK_OPT     O_NONBLOCK
#else
#define NBLK_OPT     FNDELAY
#endif

#include <netinet/in.h>
#include <net/if.h>
#if	!defined(SIOCGIFCONF) || defined(__CYGWIN__)
#include <sys/ioctl.h>
#ifndef	SIOCGIFCONF
#include <sys/sockio.h>
#endif
#endif

#if	defined(__svr4__)
#  if defined(HAVE_SYS_STROPTS)
#    include <sys/stropts.h>
#  endif
#endif

@interface NSProcessInfo (private)
+ (BOOL) _exists: (int)pid;
@end

#if 0
#define	M_LOCK(X) {NSDebugMLLog(@"NSMessagePort",@"lock %@",X); [X lock];}
#define	M_UNLOCK(X) {NSDebugMLLog(@"NSMessagePort",@"unlock %@",X); [X unlock];}
#else
#define	M_LOCK(X) {[X lock];}
#define	M_UNLOCK(X) {[X unlock];}
#endif


/*
 * The GSPortItemType constant is used to identify the type of data in
 * each packet read.  All data transmitted is in a packet, each packet
 * has an initial packet type and packet length.
 */
typedef	enum {
  GSP_NONE,
  GSP_PORT,		/* Simple port item.			*/
  GSP_DATA,		/* Simple data item.			*/
  GSP_HEAD		/* Port message header + initial data.	*/
} GSPortItemType;

/*
 * The GSPortItemHeader structure defines the header for each item transmitted.
 * Its contents are transmitted in network byte order.
 */
typedef struct {
  uint32_t	type;	/* A GSPortItemType as a 4-byte number.		*/
  uint32_t	length;	/* The length of the item (excluding header).	*/
} GSPortItemHeader;

/*
 * The GSPortMsgHeader structure is at the start of any item of type GSP_HEAD.
 * Its contents are transmitted in network byte order.
 * Any additional data in the item is an NSData object.
 * NB. additional data counts as part of the same item.
 */
typedef struct {
  uint32_t	mId;	/* The ID for the message starting with this.	*/
  uint32_t	nItems;	/* Number of items (including this one).	*/
} GSPortMsgHeader;

typedef	struct {
  unsigned char	version;
  unsigned char	addr[0];	/* name of the port on the local host	*/
} GSPortInfo;

/*
 * Utility functions for encoding and decoding ports.
 */
static NSMessagePort*
decodePort(NSData *data)
{
  GSPortItemHeader	*pih;
  GSPortInfo		*pi;

  pih = (GSPortItemHeader*)[data bytes];
  NSCAssert(GSSwapBigI32ToHost(pih->type) == GSP_PORT,
    NSInternalInconsistencyException);
  pi = (GSPortInfo*)&pih[1];
  if (pi->version != 0)
    {
      NSLog(@"Remote version of GNUstep is more recent than this one (%i)",
	pi->version);
      return nil;
    }

  NSDebugFLLog(@"NSMessagePort", @"Decoded port as '%s'", pi->addr);

  return [NSMessagePort _portWithName: pi->addr
			     listener: NO];
}

static NSData*
newDataWithEncodedPort(NSMessagePort *port)
{
  GSPortItemHeader	*pih;
  GSPortInfo		*pi;
  NSMutableData		*data;
  unsigned		plen;
  const unsigned char	*name = [port _name];

  plen = 2 + strlen((char*)name);

  data = [[NSMutableData alloc] initWithLength: sizeof(GSPortItemHeader)+plen];
  pih = (GSPortItemHeader*)[data mutableBytes];
  pih->type = GSSwapHostI32ToBig(GSP_PORT);
  pih->length = GSSwapHostI32ToBig(plen);
  pi = (GSPortInfo*)&pih[1];
  strncpy((char*)pi->addr, (char*)name, strlen((char*)name) + 1);

  NSDebugFLLog(@"NSMessagePort", @"Encoded port as '%s'", pi->addr);

  return data;
}

/* Older systems (Solaris) compatibility */
#ifndef AF_LOCAL
#define AF_LOCAL AF_UNIX
#define PF_LOCAL PF_UNIX
#endif
#ifndef SUN_LEN
#define SUN_LEN(su) \
	(sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
#endif

#define	GS_CONNECTION_MSG	0
#define	NETBLOCK	8192

/*
 * Theory of operation
 *
 *
 */


/* Private interfaces */

/*
 * Here is how data is transmitted over a socket -
 * Initially the process making the connection sends an item of type
 * GSP_PORT to tell the remote end what port is connecting to it.
 * Therafter, all communication is via port messages.  Each port message
 * consists of an item of type GSP_HEAD followed by zero or more items
 * of type GSP_PORT or GSP_DATA.  The number of items in a port message
 * is encoded in the 'nItems' field of the header.
 */

typedef enum {
  GS_H_UNCON = 0,	// Currently idle and unconnected.
  GS_H_TRYCON,		// Trying connection (outgoing).
  GS_H_ACCEPT,		// Making initial connection (incoming).
  GS_H_CONNECTED	// Currently connected.
} GSHandleState;

@interface GSMessageHandle : NSObject <RunLoopEvents>
{
  int			desc;		/* File descriptor for I/O.	*/
  unsigned		wItem;		/* Index of item being written.	*/
  NSMutableData		*wData;		/* Data object being written.	*/
  unsigned		wLength;	/* Ammount written so far.	*/
  NSMutableArray	*wMsgs;		/* Message in progress.		*/
  NSMutableData		*rData;		/* Buffer for incoming data	*/
  uint32_t		rLength;	/* Amount read so far.		*/
  uint32_t		rWant;		/* Amount desired.		*/
  NSMutableArray	*rItems;	/* Message in progress.		*/
  GSPortItemType	rType;		/* Type of data being read.	*/
  uint32_t		rId;		/* Id of incoming message.	*/
  unsigned		nItems;		/* Number of items to be read.	*/
  GSHandleState		state;		/* State of the handle.		*/
  unsigned int		addrNum;	/* Address number within host.	*/
@public
  NSRecursiveLock	*myLock;	/* Lock for this handle.	*/
  BOOL			caller;		/* Did we connect to other end?	*/
  BOOL			valid;
  NSMessagePort		*recvPort;
  NSMessagePort		*sendPort;
  struct sockaddr_un 	sockAddr;	/* Far end of connection.	*/
}

+ (GSMessageHandle*) handleWithDescriptor: (int)d;
- (BOOL) connectToPort: (NSMessagePort*)aPort beforeDate: (NSDate*)when;
- (int) descriptor;
- (void) invalidate;
- (BOOL) isValid;
- (void) receivedEvent: (void*)data
                  type: (RunLoopEventType)type
		 extra: (void*)extra
	       forMode: (NSString*)mode;
- (NSMessagePort*) recvPort;
- (BOOL) sendMessage: (NSArray*)components beforeDate: (NSDate*)when;
- (NSMessagePort*) sendPort;
- (void) setState: (GSHandleState)s;
- (GSHandleState) state;
@end



@implementation	GSMessageHandle

static Class	mutableArrayClass;
static Class	mutableDataClass;
static Class	portMessageClass;
static Class	runLoopClass;


+ (id) allocWithZone: (NSZone*)zone
{
  [NSException raise: NSGenericException
	      format: @"attempt to alloc a GSMessageHandle!"];
  return nil;
}

+ (GSMessageHandle*) handleWithDescriptor: (int)d
{
  GSMessageHandle	*handle;
  int		e;

  if (d < 0)
    {
      NSLog(@"illegal descriptor (%d) for message handle", d);
      return nil;
    }
  if ((e = fcntl(d, F_GETFL, 0)) >= 0)
    {
      e |= NBLK_OPT;
      if (fcntl(d, F_SETFL, e) < 0)
	{
	  NSLog(@"unable to set non-blocking mode on %d - %@",
	    d, [NSError _last]);
	  return nil;
	}
    }
  else
    {
      NSLog(@"unable to get non-blocking mode on %d - %@",
	d, [NSError _last]);
      return nil;
    }
  handle = (GSMessageHandle*)NSAllocateObject(self, 0, NSDefaultMallocZone());
  handle->desc = d;
  handle->wMsgs = [NSMutableArray new];
  handle->myLock = [NSRecursiveLock new];
  handle->valid = YES;
  return AUTORELEASE(handle);
}

+ (void) initialize
{
  if (self == [GSMessageHandle class])
    {
      mutableArrayClass = [NSMutableArray class];
      mutableDataClass = [NSMutableData class];
      portMessageClass = [NSPortMessage class];
      runLoopClass = [NSRunLoop class];
    }
}

- (void) _add: (NSRunLoop*)l
{
  [l addEvent: (void*)(uintptr_t)desc
	 type: ET_WDESC
      watcher: self
      forMode: NSConnectionReplyMode];
  [l addEvent: (void*)(uintptr_t)desc
	 type: ET_WDESC
      watcher: self
      forMode: NSDefaultRunLoopMode];
}

- (void) _rem: (NSRunLoop*)l
{
  [l removeEvent: (void*)(uintptr_t)desc
	    type: ET_WDESC
	 forMode: NSConnectionReplyMode
	     all: NO];
  [l removeEvent: (void*)(uintptr_t)desc
	    type: ET_WDESC
	 forMode: NSDefaultRunLoopMode
	     all: NO];
}

- (BOOL) connectToPort: (NSMessagePort*)aPort beforeDate: (NSDate*)when
{
  NSRunLoop		*l;
  const unsigned char *name;

  M_LOCK(myLock);
  NSDebugMLLog(@"NSMessagePort",
    @"Connecting on 0x%"PRIxPTR" before %@", (NSUInteger)self, when);
  if (state != GS_H_UNCON)
    {
      BOOL	result;

      if (state == GS_H_CONNECTED)	/* Already connected.	*/
	{
	  NSLog(@"attempting connect on connected handle");
	  result = YES;
	}
      else if (state == GS_H_ACCEPT)	/* Impossible.	*/
	{
	  NSLog(@"attempting connect with accepting handle");
	  result = NO;
	}
      else				/* Already connecting.	*/
	{
	  NSLog(@"attempting connect while connecting");
	  result = NO;
	}
      M_UNLOCK(myLock);
      return result;
    }

  if (recvPort == nil || aPort == nil)
    {
      NSLog(@"attempting connect with port(s) unset");
      M_UNLOCK(myLock);
      return NO;	/* impossible.		*/
    }

  name = [aPort _name];
  memset(&sockAddr, '\0', sizeof(sockAddr));
  sockAddr.sun_family = AF_LOCAL;
  strncpy(sockAddr.sun_path, (char*)name, sizeof(sockAddr.sun_path) - 1);

  if (connect(desc, (struct sockaddr*)&sockAddr, SUN_LEN(&sockAddr)) < 0)
    {
      long	eno = GSNETERROR;

      if (!GSWOULDBLOCK(eno))
	{
	  NSLog(@"unable to make connection to %s - %@",
	    sockAddr.sun_path, [NSError _last]);
	  M_UNLOCK(myLock);
	  return NO;
	}
    }

  state = GS_H_TRYCON;
  l = [NSRunLoop currentRunLoop];
  [self _add: l];

  while (valid == YES && state == GS_H_TRYCON
    && [when timeIntervalSinceNow] > 0)
    {
      [l runMode: NSConnectionReplyMode beforeDate: when];
    }

  [self _rem: l];

  if (state == GS_H_TRYCON)
    {
      state = GS_H_UNCON;
      addrNum = 0;
      M_UNLOCK(myLock);
      return NO;	/* Timed out 	*/
    }
  else if (state == GS_H_UNCON)
    {
      addrNum = 0;
      state = GS_H_UNCON;
      M_UNLOCK(myLock);
      return NO;
    }
  else
    {
      int	status = 1;

      if (setsockopt(desc, SOL_SOCKET, SO_KEEPALIVE, (char*)&status,
	sizeof(status)) < 0)
        {
          NSLog(@"failed to turn on keepalive for connected socket %d", desc);
        }
      addrNum = 0;
      caller = YES;
      [aPort addHandle: self forSend: YES];
      M_UNLOCK(myLock);
      return YES;
    }
}

- (void) dealloc
{
  [self finalize];
  DESTROY(rData);
  DESTROY(rItems);
  DESTROY(wMsgs);
  DESTROY(myLock);
  [super dealloc];
}

- (NSString*) description
{
  return [NSString stringWithFormat: @"<GSMessageHandle %p (%d) to %s>",
    self, desc, sockAddr.sun_path];
}

- (int) descriptor
{
  return desc;
}

- (void) finalize
{
  [self invalidate];
  (void)close(desc);
  desc = -1;
}

- (void) invalidate
{
  if (valid == YES)
    {
      M_LOCK(myLock);
      if (valid == YES)
	{
	  NSRunLoop	*l;

	  valid = NO;
	  l = [runLoopClass currentRunLoop];
	  [l removeEvent: (void*)(uintptr_t)desc
		    type: ET_RDESC
		 forMode: nil
		     all: YES];
	  [l removeEvent: (void*)(uintptr_t)desc
		    type: ET_WDESC
		 forMode: nil
		     all: YES];
	  NSDebugMLLog(@"NSMessagePort",
	    @"invalidated 0x%"PRIxPTR, (NSUInteger)self);
	  [[self recvPort] removeHandle: self];
	  [[self sendPort] removeHandle: self];
	}
      M_UNLOCK(myLock);
    }
}

- (BOOL) isValid
{
  return valid;
}

- (NSMessagePort*) recvPort
{
  if (recvPort == nil)
    return nil;
  else
    return recvPort;
}

- (void) receivedEvent: (void*)data
                  type: (RunLoopEventType)type
		 extra: (void*)extra
	       forMode: (NSString*)mode
{
  NSDebugMLLog(@"NSMessagePort_details",
    @"received %s event on 0x%"PRIxPTR,
    type != ET_WDESC ? "read" : "write", (NSUInteger)self);
  /*
   * If we have been invalidated (desc < 0) then we should ignore this
   * event and remove ourself from the runloop.
   */
  if (desc < 0)
    {
      NSRunLoop	*l = [runLoopClass currentRunLoop];

      [l removeEvent: data
		type: ET_WDESC
	     forMode: mode
		 all: YES];
      return;
    }

  M_LOCK(myLock);

  if (type != ET_WDESC)
    {
      unsigned	want;
      void	*bytes;
      int	res;

      /*
       * Make sure we have a buffer big enough to hold all the data we are
       * expecting, or NETBLOCK bytes, whichever is greater.
       */
      if (rData == nil)
	{
	  rData = [[mutableDataClass alloc] initWithLength: NETBLOCK];
	  rWant = sizeof(GSPortItemHeader);
	  rLength = 0;
	  want = NETBLOCK;
	}
      else
	{
	  want = [rData length];
	  if (want < MAX(rWant, NETBLOCK))
	    {
	      want = MAX(rWant, NETBLOCK);
	      NS_DURING
		{
		  [rData setLength: want];
		}
	      NS_HANDLER
		{
		  M_UNLOCK(myLock);
		  [self invalidate];
		  [localException raise];
		}
	      NS_ENDHANDLER
	    }
	}

      /*
       * Now try to fill the buffer with data.
       */
      bytes = [rData mutableBytes];
      res = read(desc, bytes + rLength, want - rLength);
      if (res <= 0)
	{
	  if (res == 0)
	    {
	      NSDebugMLLog(@"NSMessagePort",
	        @"read eof on 0x%"PRIxPTR, (NSUInteger)self);
	      M_UNLOCK(myLock);
	      [self invalidate];
	      return;
	    }
	  else if (errno != EINTR && errno != EAGAIN)
	    {
	      NSDebugMLLog(@"NSMessagePort",
		@"read failed - %@ on 0x%p", [NSError _last], self);
	      M_UNLOCK(myLock);
	      [self invalidate];
	      return;
	    }
	  res = 0;	/* Interrupted - continue	*/
	}
      NSDebugMLLog(@"NSMessagePort_details",
	@"read %d bytes on 0x%"PRIxPTR, res, (NSUInteger)self);
      rLength += res;

      while (valid == YES && rLength >= rWant)
	{
	  BOOL	shouldDispatch = NO;

	  switch (rType)
	    {
	      case GSP_NONE:
		{
		  GSPortItemHeader	*h;
		  unsigned		l;

		  /*
		   * We have read an item header - set up to read the
		   * remainder of the item.
		   */
		  h = (GSPortItemHeader*)bytes;
		  rType = GSSwapBigI32ToHost(h->type);
		  l = GSSwapBigI32ToHost(h->length);
		  if (rType == GSP_PORT)
		    {
		      if (l > 512)
			{
			  NSLog(@"%@ - unreasonable length (%u) for port",
			    self, l);
			  M_UNLOCK(myLock);
			  [self invalidate];
			  return;
			}
		      /*
		       * For a port, we leave the item header in the data
		       * so that our decode function can check length info.
		       */
		      rWant += l;
		    }
		  else if (rType == GSP_DATA)
		    {
		      if (l == 0)
			{
			  NSData	*d;

			  /*
			   * For a zero-length data chunk, we create an empty
			   * data object and add it to the current message.
			   */
			  rType = GSP_NONE;	/* ready for a new item	*/
			  rLength -= rWant;
			  if (rLength > 0)
			    {
			      memmove(bytes, bytes + rWant, rLength);
			    }
			  rWant = sizeof(GSPortItemHeader);
			  d = [mutableDataClass new];
			  [rItems addObject: d];
			  RELEASE(d);
			  if (nItems == [rItems count])
			    {
			      shouldDispatch = YES;
			    }
			}
		      else
			{
			  /*
			   * If not a port or zero length data,
			   * we discard the data read so far and fill the
			   * data object with the data item from the msg.
			   */
			  rLength -= rWant;
			  if (rLength > 0)
			    {
			      memmove(bytes, bytes + rWant, rLength);
			    }
			  rWant = l;
			}
		    }
		  else if (rType == GSP_HEAD)
		    {
		      /*
		       * If not a port or zero length data,
		       * we discard the data read so far and fill the
		       * data object with the data item from the msg.
		       */
		      rLength -= rWant;
		      if (rLength > 0)
			{
			  memmove(bytes, bytes + rWant, rLength);
			}
		      rWant = l;
		    }
		  else
		    {
		      NSLog(@"%@ - bad data received on port handle, rType=%i",
			self, rType);
		      M_UNLOCK(myLock);
		      [self invalidate];
		      return;
		    }
		}
		break;

	      case GSP_HEAD:
		{
		  GSPortMsgHeader	*h;

		  rType = GSP_NONE;	/* ready for a new item	*/
		  /*
		   * We have read a message header - set up to read the
		   * remainder of the message.
		   */
		  h = (GSPortMsgHeader*)bytes;
		  rId = GSSwapBigI32ToHost(h->mId);
		  nItems = GSSwapBigI32ToHost(h->nItems);
		  NSAssert(nItems >0, NSInternalInconsistencyException);
		  rItems
		    = [mutableArrayClass allocWithZone: NSDefaultMallocZone()];
		  rItems = [rItems initWithCapacity: nItems];
		  if (rWant > sizeof(GSPortMsgHeader))
		    {
		      NSData	*d;

		      /*
		       * The first data item of the message was included in
		       * the header - so add it to the rItems array.
		       */
		      rWant -= sizeof(GSPortMsgHeader);
		      d = [mutableDataClass alloc];
		      d = [d initWithBytes: bytes + sizeof(GSPortMsgHeader)
				    length: rWant];
		      [rItems addObject: d];
		      RELEASE(d);
		      rWant += sizeof(GSPortMsgHeader);
		      rLength -= rWant;
		      if (rLength > 0)
			{
			  memmove(bytes, bytes + rWant, rLength);
			}
		      rWant = sizeof(GSPortItemHeader);
		      if (nItems == 1)
			{
			  shouldDispatch = YES;
			}
		    }
		  else
		    {
		      /*
		       * want to read another item
		       */
		      rLength -= rWant;
		      if (rLength > 0)
			{
			  memmove(bytes, bytes + rWant, rLength);
			}
		      rWant = sizeof(GSPortItemHeader);
		    }
		}
		break;

	      case GSP_DATA:
		{
		  NSData	*d;

		  rType = GSP_NONE;	/* ready for a new item	*/
		  d = [mutableDataClass allocWithZone: NSDefaultMallocZone()];
		  d = [d initWithBytes: bytes length: rWant];
		  [rItems addObject: d];
		  RELEASE(d);
		  rLength -= rWant;
		  if (rLength > 0)
		    {
		      memmove(bytes, bytes + rWant, rLength);
		    }
		  rWant = sizeof(GSPortItemHeader);
		  if (nItems == [rItems count])
		    {
		      shouldDispatch = YES;
		    }
		}
		break;

	      case GSP_PORT:
		{
		  NSMessagePort	*p;

		  rType = GSP_NONE;	/* ready for a new item	*/
		  p = decodePort(rData);
		  if (p == nil)
		    {
		      NSLog(@"%@ - unable to decode remote port", self);
		      M_UNLOCK(myLock);
		      [self invalidate];
		      return;
		    }
		  /*
		   * Set up to read another item header.
		   */
		  rLength -= rWant;
		  if (rLength > 0)
		    {
		      memmove(bytes, bytes + rWant, rLength);
		    }
		  rWant = sizeof(GSPortItemHeader);

		  if (state == GS_H_ACCEPT)
		    {
		      /*
		       * This is the initial port information on a new
		       * connection - set up port relationships.
		       */
		      state = GS_H_CONNECTED;
		      [p addHandle: self forSend: YES];
		    }
		  else
		    {
		      /*
		       * This is a port within a port message - add
		       * it to the message components.
		       */
		      [rItems addObject: p];
		      if (nItems == [rItems count])
			{
			  shouldDispatch = YES;
			}
		    }
		}
		break;
	    }

	  if (shouldDispatch == YES)
	    {
	      NSPortMessage	*pm;
	      NSMessagePort		*rp = [self recvPort];

	      pm = [portMessageClass allocWithZone: NSDefaultMallocZone()];
	      pm = [pm initWithSendPort: [self sendPort]
			    receivePort: rp
			     components: rItems];
	      [pm setMsgid: rId];
	      rId = 0;
	      DESTROY(rItems);
	      NSDebugMLLog(@"NSMessagePort_details",
		@"got message %@ on 0x%"PRIxPTR, pm, (NSUInteger)self);
	      IF_NO_ARC([rp retain];)
	      M_UNLOCK(myLock);
	      NS_DURING
		{
		  [rp handlePortMessage: pm];
		}
	      NS_HANDLER
		{
		  M_LOCK(myLock);
		  RELEASE(pm);
		  RELEASE(rp);
		  [localException raise];
		}
	      NS_ENDHANDLER
	      M_LOCK(myLock);
	      RELEASE(pm);
	      RELEASE(rp);
	      bytes = [rData mutableBytes];
	    }
	}
    }
  else
    {
      if (state == GS_H_TRYCON)	/* Connection attempt.	*/
	{
	  int	   res = 0;
	  unsigned len = sizeof(res);

/* Currently gnu hurd doesn't support getsockopt on local domain sockets
 * and fails with a 'protocol not supported' error.
 * We therefore just hope the connect was a success.
 */
#if !defined(__gnu_hurd__)
	  if (getsockopt(desc, SOL_SOCKET, SO_ERROR, (char*)&res, &len) != 0)
	    {
	      state = GS_H_UNCON;
	      NSLog(@"connect attempt failed - %@", [NSError _last]);
	    }
	  else if (res != 0)
	    {
	      state = GS_H_UNCON;
	      NSLog(@"connect attempt failed - %@",
	        [NSError _systemError: res]);
	    }
	  else
#endif
	    {
	      NSData	*d = newDataWithEncodedPort([self recvPort]);

	      len = write(desc, [d bytes], [d length]);
	      if (len == (int)[d length])
		{
		  NSDebugMLLog(@"NSMessagePort_details",
		    @"wrote %d bytes on 0x%"PRIxPTR, len, (NSUInteger)self);
		  state = GS_H_CONNECTED;
		}
	      else
		{
		  state = GS_H_UNCON;
		  NSLog(@"connect write attempt failed - %@",
		    [NSError _last]);
		}
	      RELEASE(d);
	    }
	}
      else
	{
	  int		res;
	  unsigned	l;
	  const void	*b;

	  if (wData == nil)
	    {
	      if ([wMsgs count] > 0)
		{
		  NSArray	*components = [wMsgs objectAtIndex: 0];

		  wData = [components objectAtIndex: wItem++];
		  wLength = 0;
		}
	      else
		{
// NSLog(@"No messages to write on 0x%"PRIxPTR".", (NSUInteger)self);
		  M_UNLOCK(myLock);
		  return;
		}
	    }
	  b = [wData bytes];
	  l = [wData length];
	  res = write(desc, b + wLength,  l - wLength);
	  if (res < 0)
	    {
	      if (errno != EINTR && errno != EAGAIN)
		{
		  NSLog(@"write attempt failed - %@", [NSError _last]);
		  M_UNLOCK(myLock);
		  [self invalidate];
		  return;
		}
	    }
	  else
	    {
	      NSDebugMLLog(@"NSMessagePort_details",
		@"wrote %d bytes on 0x%"PRIxPTR, res, (NSUInteger)self);
	      wLength += res;
	      if (wLength == l)
		{
		  NSArray	*components;

		  /*
		   * We have completed a data item so see what is
		   * left of the message components.
		   */
		  components = [wMsgs objectAtIndex: 0];
		  wLength = 0;
		  if ([components count] > wItem)
		    {
		      /*
		       * More to write - get next item.
		       */
		      wData = [components objectAtIndex: wItem++];
		    }
		  else
		    {
		      /*
		       * message completed - remove from list.
		       */
		      NSDebugMLLog(@"NSMessagePort_details",
			@"completed 0x%"PRIxPTR" on 0x%"PRIxPTR,
			(NSUInteger)components, (NSUInteger)self);
		      wData = nil;
		      wItem = 0;
		      [wMsgs removeObjectAtIndex: 0];
		    }
		}
	    }
	}
    }

  M_UNLOCK(myLock);
}

- (BOOL) sendMessage: (NSArray*)components beforeDate: (NSDate*)when
{
  NSRunLoop	*l;
  BOOL		sent = NO;

  NSAssert([components count] > 0, NSInternalInconsistencyException);
  NSDebugMLLog(@"NSMessagePort_details",
    @"Sending message 0x%"PRIxPTR" %@ on 0x%"PRIxPTR"(%d) before %@",
    (NSUInteger)components, components, (NSUInteger)self, desc, when);
  M_LOCK(myLock);
  [wMsgs addObject: components];

  l = [runLoopClass currentRunLoop];

  IF_NO_ARC(RETAIN(self);)

  [self _add: l];

  while (valid == YES
    && [wMsgs indexOfObjectIdenticalTo: components] != NSNotFound
    && [when timeIntervalSinceNow] > 0)
    {
      M_UNLOCK(myLock);
      [l runMode: NSConnectionReplyMode beforeDate: when];
      M_LOCK(myLock);
    }

  [self _rem: l];

  if ([wMsgs indexOfObjectIdenticalTo: components] == NSNotFound)
    {
      sent = YES;
    }
  else
    {
      [wMsgs removeObjectIdenticalTo: components];
    }
  M_UNLOCK(myLock);
  NSDebugMLLog(@"NSMessagePort_details",
    @"Message send 0x%"PRIxPTR" on 0x%"PRIxPTR" status %d",
    (NSUInteger)components, (NSUInteger)self, sent);
  RELEASE(self);
  return sent;
}

- (NSMessagePort*) sendPort
{
  if (sendPort == nil)
    return nil;
  else if (caller == YES)
    return sendPort;	// We called, so port is not retained.
  else
    return sendPort;	// Retained port.
}

- (void) setState: (GSHandleState)s
{
  state = s;
}

- (GSHandleState) state
{
  return state;
}

@end



@interface NSMessagePort (RunLoop) <RunLoopEvents>
- (void) receivedEvent: (void*)data
                  type: (RunLoopEventType)type
		 extra: (void*)extra
	       forMode: (NSString*)mode;
@end


@implementation	NSMessagePort

static NSRecursiveLock	*messagePortLock = nil;

/*
 * Maps port name to NSMessagePort objects.
 */
static NSMapTable	*messagePortMap = 0;
static Class		messagePortClass;


+ (void) atExit
{
  NSMessagePort		*port;
  NSData		*name;
  NSMapEnumerator	mEnum;
  NSAutoreleasePool	*arp = [NSAutoreleasePool new];

  mEnum = NSEnumerateMapTable(messagePortMap);
  while (NSNextMapEnumeratorPair(&mEnum, (void *)&name, (void *)&port))
    {
      if ([port _listener] != -1)
	unlink([name bytes]);
    }
  NSEndMapTableEnumeration(&mEnum);
  DESTROY(messagePortMap);
  DESTROY(messagePortLock);
  [arp drain];
}

typedef	struct {
  NSData                *_name;
  NSRecursiveLock       *_myLock;
  NSMapTable            *_handles;       /* Handles indexed by socket.   */
  int                   _listener;       /* Descriptor to listen on.     */
} internal;
#define	name	((internal*)_internal)->_name
#define	myLock	((internal*)_internal)->_myLock
#define	handles	((internal*)_internal)->_handles
#define	lDesc	((internal*)_internal)->_listener


+ (void) initialize
{
  if (self == [NSMessagePort class])
    {
      NSAutoreleasePool *pool = [NSAutoreleasePool new];
      NSFileManager	*mgr;
      NSString		*path;
      NSString		*pref;
      NSString		*file;
      NSEnumerator	*files;

      messagePortClass = self;
      messagePortMap = NSCreateMapTable(NSNonRetainedObjectMapKeyCallBacks,
	NSNonOwnedPointerMapValueCallBacks, 0);

      messagePortLock = [NSRecursiveLock new];

      /* It's possible that an old process, with the same process ID as
       * this one, got forcibly killed or crashed so that clean_up_sockets
       * was never called.
       * To deal with that unlikely situation, we need to remove all such
       * ports which have been left over.
       */
      path = NSTemporaryDirectory();
      path = [path stringByAppendingPathComponent: @"NSMessagePort"];
      path = [path stringByAppendingPathComponent: @"ports"];
      pref = [NSString stringWithFormat: @"%i.",
	[[NSProcessInfo processInfo] processIdentifier]];
      mgr = [NSFileManager defaultManager];
      files = [[mgr directoryContentsAtPath: path] objectEnumerator];
      while ((file = [files nextObject]) != nil)
	{
          NSString	*old = [path stringByAppendingPathComponent: file];

	  if (YES == [file hasPrefix: pref])
	    {
	      NSDebugMLLog(@"NSMessagePort", @"Removing old port %@", old);
	      [mgr removeFileAtPath: old handler: nil];
	    }
	  else
	    {
	      int	pid = [file intValue];

	      if (pid > 0)
		{
		  if (NO == [NSProcessInfo _exists: pid])
		    {
		      NSDebugMLLog(@"NSMessagePort",
		        @"Removing old port %@ for process %d", old, pid);
		      [mgr removeFileAtPath: old handler: nil];
		    }
		}
	    }
	}
      [pool release];
      [self registerAtExit];
    }
}

+ (id) new
{
  static int unique_index = 0;
  NSString	*path;
  NSDictionary	*attr;

  if (nil == (path = NSTemporaryDirectory()))
    {
      return nil;
    }

  attr = [NSDictionary dictionaryWithObject: [NSNumber numberWithInt: 0700]
				     forKey: NSFilePosixPermissions];

  path = [path stringByAppendingPathComponent: @"NSMessagePort"];
  [[NSFileManager defaultManager] createDirectoryAtPath: path
                            withIntermediateDirectories: YES
                                             attributes: attr
                                                  error: NULL];

  path = [path stringByAppendingPathComponent: @"ports"];
  [[NSFileManager defaultManager] createDirectoryAtPath: path
                            withIntermediateDirectories: YES
                                             attributes: attr
                                                  error: NULL];

  M_LOCK(messagePortLock);
  path = [path stringByAppendingPathComponent:
   [NSString stringWithFormat: @"%i.%i",
	[[NSProcessInfo processInfo] processIdentifier], unique_index++]];
  M_UNLOCK(messagePortLock);

  return RETAIN([self _portWithName:
    (unsigned char*)[path fileSystemRepresentation] listener: YES]);
}

/*
 * This is the preferred initialisation method for NSMessagePort
 *
 * 'socketName' is the name of the socket in the port directory
 */
+ (NSMessagePort*) _portWithName: (const unsigned char *)socketName
			listener: (BOOL)shouldListen
{
  unsigned		i;
  NSMessagePort		*port = nil;
  NSData		*theName;

  theName = [[NSData alloc] initWithBytes: socketName
				   length: strlen((char*)socketName)+1];

  M_LOCK(messagePortLock);

  /*
   * First try to find a pre-existing port.
   */
  port = (NSMessagePort*)NSMapGet(messagePortMap, theName);

  if (port == nil)
    {
      port = (NSMessagePort*)NSAllocateObject(self, 0, NSDefaultMallocZone());
      port->_internal = (internal*)NSZoneMalloc(NSDefaultMallocZone(),
	  sizeof(internal));
      ((internal*)(port->_internal))->_name = theName;
      ((internal*)(port->_internal))->_listener = -1;
      ((internal*)(port->_internal))->_handles
	= NSCreateMapTable(NSIntegerMapKeyCallBacks,
	NSObjectMapValueCallBacks, 0);
      ((internal*)(port->_internal))->_myLock = [NSRecursiveLock new];
      port->_is_valid = YES;

      if (shouldListen == YES)
	{
	  int	desc;
	  struct sockaddr_un	sockAddr;

	  /*
           * Need size of buffer for getsockbyname() later.
	   */
	  i = sizeof(sockAddr);

	  /*
	   * Creating a new port on the local host - so we must create a
	   * listener socket to accept incoming connections.
	   */
	  memset(&sockAddr, '\0', sizeof(sockAddr));
	  sockAddr.sun_family = AF_LOCAL;
	  strncpy(sockAddr.sun_path, (char*)socketName,
	    sizeof(sockAddr.sun_path) - 1);
	  if ((desc = socket(PF_LOCAL, SOCK_STREAM, PF_UNSPEC)) < 0)
	    {
	      NSLog(@"unable to create socket - %@", [NSError _last]);
	      desc = -1;
	    }
	  else if (bind(desc, (struct sockaddr *)&sockAddr,
	    SUN_LEN(&sockAddr)) < 0)
	    {
	      if (connect(desc, (struct sockaddr*)&sockAddr,
		SUN_LEN(&sockAddr)) < 0)
		{
		  NSDebugLLog(@"NSMessagePort", @"not live, resetting");
		  unlink((const char*)socketName);
		  close(desc);
		  if ((desc = socket(PF_LOCAL, SOCK_STREAM, PF_UNSPEC)) < 0)
		    {
		      NSLog(@"unable to create socket - %@",
			[NSError _last]);
		      desc = -1;
		    }
		  else if (bind(desc, (struct sockaddr *)&sockAddr,
		    SUN_LEN(&sockAddr)) < 0)
		    {
		      NSLog(@"unable to bind to %s - %@",
			sockAddr.sun_path, [NSError _last]);
		      (void) close(desc);
		      desc = -1;
		    }
		}
	      else
		{
		  NSLog(@"unable to bind to %s - %@",
		    sockAddr.sun_path, [NSError _last]);
		  (void) close(desc);
		  desc = -1;
		}
	    }

	  if (desc == -1)
	    {
              DESTROY(port);
	    }
	  else if (listen(desc, GSBACKLOG) < 0)
	    {
	      NSLog(@"unable to listen on port - %@", [NSError _last]);
	      (void) close(desc);
	      DESTROY(port);
	    }
	  else if (getsockname(desc, (struct sockaddr*)&sockAddr, &i) < 0)
	    {
	      NSLog(@"unable to get socket name - %@", [NSError _last]);
	      (void) close(desc);
	      DESTROY(port);
	    }
	  else
	    {
	      /*
	       * Set up the listening descriptor and the actual message port
	       * number (which will have been set to a real port number when
	       * we did the 'bind' call.
	       */
	      ((internal*)port->_internal)->_listener = desc;
	      /*
	       * Make sure we have the map table for this port.
	       */
	      NSMapInsert(messagePortMap, (void*)theName, (void*)port);
	      NSDebugMLLog(@"NSMessagePort", @"Created listening port: %@",
		port);
	    }
	}
      else
	{
	  /*
	   * Make sure we have the map table for this port.
	   */
	  NSMapInsert(messagePortMap, (void*)theName, (void*)port);
	  NSDebugMLLog(@"NSMessagePort", @"Created speaking port: %@", port);
	}
    }
  else
    {
      RELEASE(theName);
      IF_NO_ARC([port retain];)
      NSDebugMLLog(@"NSMessagePort", @"Using pre-existing port: %@", port);
    }
  IF_NO_ARC(AUTORELEASE(port);)

  M_UNLOCK(messagePortLock);
  return port;
}

- (void) addHandle: (GSMessageHandle*)handle forSend: (BOOL)send
{
  M_LOCK(myLock);
  if (send == YES)
    {
      if (handle->caller == YES)
	handle->sendPort = self;
      else
	ASSIGN(handle->sendPort, self);
    }
  else
    {
      handle->recvPort = self;
    }
  NSMapInsert(handles, (void*)(uintptr_t)[handle descriptor], (void*)handle);
  M_UNLOCK(myLock);
}

- (id) copyWithZone: (NSZone*)zone
{
  return RETAIN(self);
}

- (void) dealloc
{
  [self finalize];
  [super dealloc];
}

- (NSString*) description
{
  NSString	*desc;

  desc = [NSString stringWithFormat:
    @"<%s %p file name %s>",
    GSClassNameFromObject(self), self, (char*)[name bytes]];
  return desc;
}

- (void) finalize
{
  NSDebugMLLog(@"NSMessagePort",
    @"NSMessagePort 0x%"PRIxPTR" finalized", (NSUInteger)self);
  [self invalidate];
  if (_internal != 0)
    {
      DESTROY(name);
      NSFreeMapTable(handles);
      RELEASE(myLock);
      NSZoneFree(NSDefaultMallocZone(), _internal);
    }
}

/*
 * This is a callback method used by the NSRunLoop class to determine which
 * descriptors to watch for the port.
 */
- (void) getFds: (NSInteger*)fds count: (NSInteger*)count
{
  NSInteger             limit = *count;
  NSInteger             pos = 0;
  NSMapEnumerator	me;
  void			*sock;
  GSMessageHandle	*handle;
  id			recvSelf;

  M_LOCK(myLock);

  /*
   * Put in our listening socket.
   */
  if (lDesc >= 0)
    {
      if (pos < limit)
        {
          fds[pos] = lDesc;
        }
      pos++;
    }

  /*
   * Enumerate all our socket handles, and put them in as long as they
   * are to be used for receiving.
   */
  recvSelf = self;
  me = NSEnumerateMapTable(handles);
  while (NSNextMapEnumeratorPair(&me, &sock, (void**)&handle))
    {
      if (handle->recvPort == recvSelf)
        {
          if (pos < limit)
            {
              fds[pos] = (int)(intptr_t)sock;
            }
          pos++;
        }
    }
  NSEndMapTableEnumeration(&me);
  M_UNLOCK(myLock);
  *count = pos;
}

- (id) conversation: (NSPort*)recvPort
{
  NSMapEnumerator	me;
  void			*dummy;
  GSMessageHandle	*handle = nil;

  M_LOCK(myLock);
  /*
   * Enumerate all our socket handles, and look for one with port.
   */
  me = NSEnumerateMapTable(handles);
  while (NSNextMapEnumeratorPair(&me, &dummy, (void**)&handle))
    {
      if ((NSPort*) [handle recvPort] == recvPort)
	{
	  IF_NO_ARC([handle retain];)
	  NSEndMapTableEnumeration(&me);
	  M_UNLOCK(myLock);
	  return AUTORELEASE(handle);
	}
    }
  NSEndMapTableEnumeration(&me);
  M_UNLOCK(myLock);
  return nil;
}

- (GSMessageHandle*) handleForPort: (NSMessagePort*)recvPort
			beforeDate: (NSDate*)when
{
  NSMapEnumerator	me;
  int			sock;
  void			*dummy;
  GSMessageHandle	*handle = nil;

  M_LOCK(myLock);
  /*
   * Enumerate all our socket handles, and look for one with port.
   */
  me = NSEnumerateMapTable(handles);
  while (NSNextMapEnumeratorPair(&me, &dummy, (void**)&handle))
    {
      if ([handle recvPort] == recvPort)
	{
	  M_UNLOCK(myLock);
	  NSEndMapTableEnumeration(&me);
	  return handle;
	}
    }
  NSEndMapTableEnumeration(&me);

  /*
   * Not found ... create a new handle.
   */
  handle = nil;
  sock = socket(PF_LOCAL, SOCK_STREAM, PF_UNSPEC);
  if (sock < 0)
    {
      NSLog(@"unable to create socket - %@", [NSError _last]);
    }
  else if ((handle = [GSMessageHandle handleWithDescriptor: sock]) == nil)
    {
      (void)close(sock);
      NSLog(@"unable to create GSMessageHandle - %@", [NSError _last]);
    }
  else
    {
      [recvPort addHandle: handle forSend: NO];
    }
  M_UNLOCK(myLock);
  /*
   * If we succeeded in creating a new handle - connect to remote host.
   */
  if (handle != nil)
    {
      if ([handle connectToPort: self beforeDate: when] == NO)
	{
	  [handle invalidate];
	  handle = nil;
	}
    }
  return handle;
}

- (void) handlePortMessage: (NSPortMessage*)m
{
  id	d = [self delegate];

  if (d == nil)
    {
      NSDebugMLLog(@"NSMessagePort",
	@"%@", @"No delegate to handle incoming message");
      return;
    }
  if ([d respondsToSelector: @selector(handlePortMessage:)] == NO)
    {
      NSDebugMLLog(@"NSMessagePort",
	@"%@", @"delegate doesn't handle messages");
      return;
    }
  [d handlePortMessage: m];
}

- (NSUInteger) hash
{
  return [name hash];
}

- (id) init
{
  DESTROY(self);
  self = [messagePortClass new];
  return self;
}

- (void) invalidate
{
  if ([self isValid] == YES)
    {
      IF_NO_ARC(RETAIN(self);)
      M_LOCK(myLock);

      if ([self isValid] == YES)
	{
	  NSArray	*handleArray;
	  unsigned	i;

	  M_LOCK(messagePortLock);
	  NSMapRemove(messagePortMap, (void*)name);
	  M_UNLOCK(messagePortLock);
	  if (lDesc >= 0)
	    {
	      (void) close(lDesc);
	      unlink([name bytes]);
	      lDesc = -1;
	    }

	  handleArray = NSAllMapTableValues(handles);
	  i = [handleArray count];
	  while (i-- > 0)
	    {
	      GSMessageHandle	*handle;

	      handle = [handleArray objectAtIndex: i];
	      [handle invalidate];
	    }

	  [[NSMessagePortNameServer sharedInstance] removePort: self];
	  [super invalidate];
	}
      M_UNLOCK(myLock);
      RELEASE(self);
    }
}

- (BOOL) isEqual: (id)anObject
{
  if (anObject == self)
    {
      return YES;
    }
  if ([anObject class] == [self class] && [self isValid] && [anObject isValid])
    {
      NSMessagePort	*o = (NSMessagePort*)anObject;

      return [((internal*)o->_internal)->_name isEqual: name];
    }
  return NO;
}

- (void) receivedEvent: (void*)data
                  type: (RunLoopEventType)type
		 extra: (void*)extra
	       forMode: (NSString*)mode
{
  int		desc = (int)(uintptr_t)extra;
  GSMessageHandle	*handle;

  if (desc == lDesc)
    {
      struct sockaddr_un	sockAddr;
      unsigned			size = sizeof(sockAddr);

      desc = accept(lDesc, (struct sockaddr*)&sockAddr, &size);
      if (desc < 0)
        {
	  NSDebugMLLog(@"NSMessagePort",
	    @"accept failed - handled in other thread?");
        }
      else
	{
	  int	status = 1;

	  if (setsockopt(desc, SOL_SOCKET, SO_KEEPALIVE, (char*)&status,
	    sizeof(status)) < 0)
            {
              NSLog(@"failed to turn on keepalive for accepted socket %d",
                desc);
            }
	  /*
	   * Create a handle for the socket and set it up so we are its
	   * receiving port, and it's waiting to get the port name from
	   * the other end.
	   */
	  handle = [GSMessageHandle handleWithDescriptor: desc];
	  memcpy(&handle->sockAddr, &sockAddr, sizeof(sockAddr));

	  [handle setState: GS_H_ACCEPT];
	  [self addHandle: handle forSend: NO];
	}
    }
  else
    {
      M_LOCK(myLock);
      handle = (GSMessageHandle*)NSMapGet(handles, (void*)(uintptr_t)desc);
      IF_NO_ARC(AUTORELEASE(RETAIN(handle));)
      M_UNLOCK(myLock);
      if (handle == nil)
	{
	  const char	*t;

	  if (type == ET_RDESC) t = "rdesc";
	  else if (type == ET_WDESC) t = "wdesc";
	  else if (type == ET_RPORT) t = "rport";
	  else t = "unknown";
	  NSLog(@"No handle for event %s on descriptor %d", t, desc);
	}
      else
	{
	  [handle receivedEvent: data type: type extra: extra forMode: mode];
	}
    }
}

- (oneway void) release
{
  M_LOCK(messagePortLock);
  if (_internal != 0 && 1 == [self retainCount])
    {
      NSMapRemove(messagePortMap, (void*)name);
    }
  M_UNLOCK(messagePortLock);
  [super release];
}

- (void) removeHandle: (GSMessageHandle*)handle
{
  IF_NO_ARC(RETAIN(self);)
  M_LOCK(myLock);
  if ([handle sendPort] == self)
    {
      if (handle->caller != YES)
	{
	  /*
	   * This is a handle for a send port, and the handle was not formed
	   * by calling the remote process, so this port object must have
	   * been created to deal with an incoming connection and will have
	   * been retained - we must therefore release this port since the
	   * handle no longer uses it.
	   */
	  IF_NO_ARC([self autorelease];)
	}
      handle->sendPort = nil;
    }
  if ([handle recvPort] == self)
    {
      handle->recvPort = nil;
    }
  NSMapRemove(handles, (void*)(uintptr_t)[handle descriptor]);
  if (lDesc < 0 && NSCountMapTable(handles) == 0)
    {
      [self invalidate];
    }
  M_UNLOCK(myLock);
  RELEASE(self);
}

/*
 * This returns the amount of space that a port coder should reserve at the
 * start of its encoded data so that the NSMessagePort can insert header info
 * into the data.
 * The idea is that a message consisting of a single data item with space at
 * the start can be written directly without having to copy data to another
 * buffer etc.
 */
- (NSUInteger) reservedSpaceLength
{
  return sizeof(GSPortItemHeader) + sizeof(GSPortMsgHeader);
}

- (BOOL) sendBeforeDate: (NSDate*)when
		  msgid: (NSInteger)msgId
             components: (NSMutableArray*)components
                   from: (NSPort*)receivingPort
               reserved: (NSUInteger)length
{
  BOOL		sent = NO;
  GSMessageHandle	*h;
  unsigned	rl;

  if ([self isValid] == NO)
    {
      return NO;
    }
  if ([components count] == 0)
    {
      NSLog(@"empty components sent");
      return NO;
    }
  /*
   * If the reserved length in the first data object is wrong - we have to
   * fail, unless it's zero, in which case we can insert a data object for
   * the header.
   */
  rl = [self reservedSpaceLength];
  if (length != 0 && length != rl)
    {
      NSLog(@"bad reserved length - %"PRIuPTR, length);
      return NO;
    }
  if ([receivingPort isKindOfClass: messagePortClass] == NO)
    {
      NSLog(@"woah there - receiving port is not the correct type");
      return NO;
    }

  h = [self handleForPort: (NSMessagePort*)receivingPort beforeDate: when];
  if (h != nil)
    {
      NSMutableData	*header;
      unsigned		hLength;
      unsigned		l;
      GSPortItemHeader	*pih;
      GSPortMsgHeader	*pmh;
      unsigned		c = [components count];
      unsigned		i;
      BOOL		pack = YES;

      /*
       * Ok - ensure we have space to insert header info.
       */
      if (length == 0 && rl != 0)
	{
	  header = [[mutableDataClass alloc] initWithCapacity: NETBLOCK];

	  [header setLength: rl];
	  [components insertObject: header atIndex: 0];
	  RELEASE(header);
	}

      header = [components objectAtIndex: 0];
      /*
       * The Item header contains the item type and the length of the
       * data in the item (excluding the item header itself).
       */
      hLength = [header length];
      l = hLength - sizeof(GSPortItemHeader);
      pih = (GSPortItemHeader*)[header mutableBytes];
      pih->type = GSSwapHostI32ToBig(GSP_HEAD);
      pih->length = GSSwapHostI32ToBig(l);

      /*
       * The message header contains the message Id and the original count
       * of components in the message (excluding any extra component added
       * simply to hold the header).
       */
      pmh = (GSPortMsgHeader*)&pih[1];
      pmh->mId = GSSwapHostI32ToBig(msgId);
      pmh->nItems = GSSwapHostI32ToBig(c);

      /*
       * Now insert item header information as required.
       * Pack as many items into the initial data object as possible, up to
       * a maximum of NETBLOCK bytes.  This is to try to get a single,
       * efficient write operation if possible.
       */
      c = [components count];
      for (i = 1; i < c; i++)
	{
	  id	o = [components objectAtIndex: i];

	  if ([o isKindOfClass: [NSData class]])
	    {
	      GSPortItemHeader	*pih;
	      unsigned		h = sizeof(GSPortItemHeader);
	      unsigned		l = [o length];
	      void		*b;

	      if (pack == YES && hLength + l + h <= NETBLOCK)
		{
		  [header setLength: hLength + l + h];
		  b = [header mutableBytes];
		  b += hLength;
#if NEED_WORD_ALIGNMENT
		  /*
		   * When packing data, an item may not be aligned on a
		   * word boundary, so we work with an aligned buffer
		   * and use memcmpy()
		   */
		  if ((hLength % __alignof__(uint32_t)) != 0)
		    {
		      GSPortItemHeader	itemHeader;

		      pih = (GSPortItemHeader*)&itemHeader;
		      pih->type = GSSwapHostI32ToBig(GSP_DATA);
		      pih->length = GSSwapHostI32ToBig(l);
		      memcpy(b, (void*)pih, h);
		    }
		  else
		    {
		      pih = (GSPortItemHeader*)b;
		      pih->type = GSSwapHostI32ToBig(GSP_DATA);
		      pih->length = GSSwapHostI32ToBig(l);
		    }
#else
		  pih = (GSPortItemHeader*)b;
		  pih->type = GSSwapHostI32ToBig(GSP_DATA);
		  pih->length = GSSwapHostI32ToBig(l);
#endif
		  memcpy(b+h, [o bytes], l);
		  [components removeObjectAtIndex: i--];
		  c--;
		  hLength += l + h;
		}
	      else
		{
		  NSMutableData	*d;

		  pack = NO;
		  d = [[NSMutableData alloc] initWithLength: l + h];
		  b = [d mutableBytes];
		  pih = (GSPortItemHeader*)b;
		  memcpy(b+h, [o bytes], l);
		  pih->type = GSSwapHostI32ToBig(GSP_DATA);
		  pih->length = GSSwapHostI32ToBig(l);
		  [components replaceObjectAtIndex: i
					withObject: d];
		  RELEASE(d);
		}
	    }
	  else if ([o isKindOfClass: messagePortClass])
	    {
	      NSData	*d = newDataWithEncodedPort(o);
	      unsigned	dLength = [d length];

	      if (pack == YES && hLength + dLength <= NETBLOCK)
		{
		  void	*b;

		  [header setLength: hLength + dLength];
		  b = [header mutableBytes];
		  b += hLength;
		  hLength += dLength;
		  memcpy(b, [d bytes], dLength);
		  [components removeObjectAtIndex: i--];
		  c--;
		}
	      else
		{
		  pack = NO;
		  [components replaceObjectAtIndex: i withObject: d];
		}
	      RELEASE(d);
	    }
	}

      /*
       * Now send the message.
       */
      sent = [h sendMessage: components beforeDate: when];
    }
  return sent;
}

- (const unsigned char *) _name
{
  return [name bytes];
}

- (int) _listener
{
  return lDesc;
}

@end