-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNSSocketPort.m
More file actions
2440 lines (2230 loc) · 57.5 KB
/
NSSocketPort.m
File metadata and controls
2440 lines (2230 loc) · 57.5 KB
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
/** Implementation of network port object based on TCP 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., 51 Franklin Street, Fifth Floor,
Boston, MA 02110 USA.
*/
#import "common.h"
#define EXPOSE_NSPort_IVARS 1
#define EXPOSE_NSSocketPort_IVARS 1
#import "GNUstepBase/GSLock.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSNotification.h"
#import "Foundation/NSNotificationQueue.h"
#import "Foundation/NSException.h"
#import "Foundation/NSRunLoop.h"
#import "Foundation/NSByteOrder.h"
#import "Foundation/NSData.h"
#import "Foundation/NSDate.h"
#import "Foundation/NSHost.h"
#import "Foundation/NSMapTable.h"
#import "Foundation/NSPortMessage.h"
#import "Foundation/NSPortNameServer.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSHost.h"
#import "Foundation/NSThread.h"
#import "Foundation/NSConnection.h"
#import "GSPortPrivate.h"
#import "GSPrivate.h"
#import "GSNetwork.h"
#include <stdio.h>
#ifdef _WIN32
#define close closesocket
#define OPTLEN int
#else
#define OPTLEN socklen_t
#include <sys/param.h> /* for MAXHOSTNAMELEN */
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h> /* for inet_ntoa() */
#endif /* !_WIN32 */
#include <ctype.h> /* for strchr() */
#if defined(HAVE_SYS_FCNTL_H)
# include <sys/fcntl.h>
#elif defined(HAVE_FCNTL_H)
# include <fcntl.h>
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <wininet.h>
#include <process.h>
#else
#include <sys/resource.h>
#include <netdb.h>
#include <sys/socket.h>
#if defined(HAVE_SYS_FILE_H)
# include <sys/file.h>
#endif
/*
* 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_H)
# include <sys/stropts.h>
# endif
#endif
#define SOCKET int
#define SOCKET_ERROR -1
#define INVALID_SOCKET -1
#endif /* !_WIN32 */
/*
* Largest chunk of data possible in DO
*/
static uint32_t maxDataLength = 32 * 1024 * 1024;
#if 0
#define M_LOCK(X) {NSDebugMLLog(@"GSTcpHandleLock",@"lock %@ in %@",X,[NSThread currentThread]); [X lock];}
#define M_UNLOCK(X) {NSDebugMLLog(@"GSTcpHandleLock",@"unlock %@ in %@",X,[NSThread currentThread]); [X unlock];}
#else
#define M_LOCK(X) {[X lock];}
#define M_UNLOCK(X) {[X unlock];}
#endif
#define GS_CONNECTION_MSG 0
#define NETBLOCK 8192
#ifndef INADDR_NONE
#define INADDR_NONE -1
#endif
/*
* Theory of operation
*
*
*/
/* Private interfaces */
/*
* 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 {
uint16_t num; /* TCP port num */
char addr[0]; /* host address */
} GSPortInfo;
/*
* 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 GSTcpHandle : NSObject <RunLoopEvents>
{
SOCKET 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. */
#ifdef _WIN32
WSAEVENT event; /* Win32 event associated to socket */
WSAEVENT eventTemp; /* Win32 event for asynchronous */
@public
BOOL inReplyMode; /* Indicate when have addEvent self */
BOOL readyToSend; /* Indicate when send */
#endif
@public
NSRecursiveLock *myLock; /* Lock for this handle. */
BOOL caller; /* Did we connect to other end? */
BOOL valid;
NSSocketPort *recvPort;
NSSocketPort *sendPort;
struct sockaddr sockAddr; /* Far end of connection. */
NSString *defaultAddress;
}
+ (GSTcpHandle*) handleWithDescriptor: (SOCKET)d;
- (BOOL) connectToPort: (NSSocketPort*)aPort beforeDate: (NSDate*)when;
- (int) descriptor;
#if defined(_WIN32)
- (int) eventHandle;
#endif
- (void) invalidate;
- (BOOL) isValid;
- (void) receivedEvent: (void*)data
type: (RunLoopEventType)type
extra: (void*)extra
forMode: (NSString*)mode;
- (void) receivedEventRead;
- (void) receivedEventWrite;
- (NSSocketPort*) recvPort;
- (BOOL) sendMessage: (NSArray*)components beforeDate: (NSDate*)when;
- (NSSocketPort*) sendPort;
- (void) setState: (GSHandleState)s;
- (GSHandleState) state;
@end
/*
* Utility functions for encoding and decoding ports.
*/
static NSSocketPort*
decodePort(NSData *data, NSString *defaultAddress)
{
GSPortItemHeader *pih;
GSPortInfo *pi;
NSString *addr;
uint16_t pnum;
NSHost *host;
unichar c;
pih = (GSPortItemHeader*)[data bytes];
NSCAssert(GSSwapBigI32ToHost(pih->type) == GSP_PORT,
NSInternalInconsistencyException);
pi = (GSPortInfo*)&pih[1];
pnum = GSSwapBigI16ToHost(pi->num);
if (strncmp(pi->addr, "VER", 3) == 0)
{
NSLog(@"Remote version of GNUstep at %s:%d is more recent than this one",
pi->addr, pnum);
return nil;
}
addr = [NSString stringWithUTF8String: pi->addr];
NSDebugFLLog(@"NSPort", @"Decoded port as '%@:%d'", addr, pnum);
/*
* Special case - the encoded port was on the host from which the
* message was sent.
*/
if ([addr length] == 0)
{
addr = defaultAddress;
}
c = [addr characterAtIndex: 0];
if (c >= '0' && c <= '9')
{
host = [NSHost hostWithAddress: addr];
}
else
{
host = [NSHost hostWithName: addr];
}
return [NSSocketPort portWithNumber: pnum
onHost: host
forceAddress: nil
listener: NO];
}
static NSData*
newDataWithEncodedPort(NSSocketPort *port)
{
GSPortItemHeader *pih;
GSPortInfo *pi;
NSMutableData *data;
unsigned plen;
NSString *addr;
uint16_t pnum;
pnum = [port portNumber];
addr = [port address];
if (addr == nil)
{
static NSHost *local = nil;
/*
* If the port is not forced to use a specific address ...
* 1. see if it is on the local host, and if so, encode as "".
* 2. see if it s a hostname and if so, use the name.
* 3. pick one of the host addresses.
* 4. use the localhost address.
*/
if (local == nil)
{
local = RETAIN([NSHost localHost]);
}
if ([[port host] isEqual: local] == YES)
{
addr = @"";
}
else if ((addr = [[port host] name]) == nil)
{
addr = [[port host] address];
if (addr == nil)
{
addr = @"127.0.0.1"; /* resign ourselves to this */
}
}
}
plen = [addr cStringLength] + 3;
data = [[NSMutableData alloc] initWithLength: sizeof(GSPortItemHeader)+plen];
pih = (GSPortItemHeader*)[data mutableBytes];
pih->type = GSSwapHostI32ToBig(GSP_PORT);
pih->length = GSSwapHostI32ToBig(plen);
pi = (GSPortInfo*)&pih[1];
pi->num = GSSwapHostI16ToBig(pnum);
[addr getCString: pi->addr];
NSDebugFLLog(@"NSPort", @"Encoded port as '%@:%d'", addr, pnum);
return data;
}
@implementation GSTcpHandle
static Class mutableArrayClass;
static Class mutableDataClass;
static Class portMessageClass;
static Class runLoopClass;
+ (id) allocWithZone: (NSZone*)zone
{
[NSException raise: NSGenericException
format: @"attempt to alloc a GSTcpHandle!"];
return nil;
}
+ (GSTcpHandle*) handleWithDescriptor: (SOCKET)d
{
GSTcpHandle *handle;
#ifdef _WIN32
unsigned long dummy;
#else
int e;
#endif /* _WIN32 */
#ifdef _WIN32
WSAEVENT ev;
int rc;
#endif
if (d == INVALID_SOCKET)
{
NSLog(@"illegal descriptor (%d) for Tcp Handle", d);
return nil;
}
#ifdef _WIN32
dummy = 1;
if (ioctlsocket(d, FIONBIO, &dummy) == SOCKET_ERROR)
{
NSLog(@"unable to set non-blocking mode on %d - %@",
d, [NSError _last]);
return nil;
}
#else /* !_WIN32 */
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;
}
#endif
handle = (GSTcpHandle*)NSAllocateObject(self, 0, NSDefaultMallocZone());
handle->desc = d;
handle->wMsgs = [NSMutableArray new];
handle->myLock = [NSRecursiveLock new];
#if defined(_WIN32)
ev = (WSAEVENT)CreateEvent(NULL,NO,NO,NULL);
if (ev == WSA_INVALID_EVENT)
{
NSLog(@"Invalid Event - '%d'", WSAGetLastError());
return nil;
}
rc = WSAEventSelect(handle->desc, ev, FD_ALL_EVENTS);
NSAssert(rc == 0, @"WSAEventSelect failed!");
handle->event = ev;
handle->inReplyMode = NO;
handle->readyToSend = YES;
#endif
handle->valid = YES;
return AUTORELEASE(handle);
}
+ (void) initialize
{
if (self == [GSTcpHandle class])
{
#ifdef _WIN32
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2, 0);
WSAStartup(wVersionRequested, &wsaData);
#endif
mutableArrayClass = [NSMutableArray class];
mutableDataClass = [NSMutableData class];
portMessageClass = [NSPortMessage class];
runLoopClass = [NSRunLoop class];
}
}
- (void) _add: (NSRunLoop*)l
{
#if defined(_WIN32)
[l addEvent: (void*)(uintptr_t)event
type: ET_HANDLE
watcher: self
forMode: NSConnectionReplyMode];
[l addEvent: (void*)(uintptr_t)event
type: ET_HANDLE
watcher: self
forMode: NSDefaultRunLoopMode];
inReplyMode = YES;
#else
[l addEvent: (void*)(uintptr_t)desc
type: ET_WDESC
watcher: self
forMode: NSConnectionReplyMode];
[l addEvent: (void*)(uintptr_t)desc
type: ET_EDESC
watcher: self
forMode: NSConnectionReplyMode];
[l addEvent: (void*)(uintptr_t)desc
type: ET_WDESC
watcher: self
forMode: NSDefaultRunLoopMode];
[l addEvent: (void*)(uintptr_t)desc
type: ET_EDESC
watcher: self
forMode: NSDefaultRunLoopMode];
#endif
}
- (void) _rem: (NSRunLoop*)l
{
#if defined(_WIN32)
[l removeEvent: (void*)(uintptr_t)event
type: ET_HANDLE
forMode: NSConnectionReplyMode
all: NO];
[l removeEvent: (void*)(uintptr_t)event
type: ET_HANDLE
forMode: NSDefaultRunLoopMode
all: NO];
inReplyMode = NO;
#else
[l removeEvent: (void*)(uintptr_t)desc
type: ET_WDESC
forMode: NSConnectionReplyMode
all: NO];
[l removeEvent: (void*)(uintptr_t)desc
type: ET_EDESC
forMode: NSConnectionReplyMode
all: NO];
[l removeEvent: (void*)(uintptr_t)desc
type: ET_WDESC
forMode: NSDefaultRunLoopMode
all: NO];
[l removeEvent: (void*)(uintptr_t)desc
type: ET_EDESC
forMode: NSDefaultRunLoopMode
all: NO];
#endif
}
- (BOOL) connectToPort: (NSSocketPort*)aPort beforeDate: (NSDate*)when
{
NSArray *addrs;
BOOL gotAddr = NO;
NSRunLoop *l;
M_LOCK(myLock);
NSDebugMLLog(@"GSTcpHandle",
@"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. */
}
/*
* Get an IP address to try to connect to.
* If the port has a 'forced' address, just use that. Otherwise we try
* each of the addresses for the host in turn.
*/
if ([aPort address] != nil)
{
addrs = [NSArray arrayWithObject: [aPort address]];
}
else
{
addrs = [[aPort host] addresses];
}
while (gotAddr == NO)
{
NSString *addr;
if (addrNum >= [addrs count])
{
NSLog(@"run out of addresses to try (tried %d) for port %@",
addrNum, aPort);
M_UNLOCK(myLock);
return NO;
}
addr = [addrs objectAtIndex: addrNum++];
if (NO == GSPrivateSockaddrSetup(addr,
[aPort portNumber], nil, nil, &sockAddr))
{
NSLog(@"bad address - '%@'", addr);
}
else
{
gotAddr = YES;
NSDebugMLLog(@"GSTcpHandle", @"Connecting to %@:%d using desc %d",
addr, [aPort portNumber], desc);
}
}
if (connect(desc, (struct sockaddr*)&sockAddr,
GSPrivateSockaddrLength(&sockAddr)) == SOCKET_ERROR)
{
if (!GSWOULDBLOCK)
{
NSLog(@"unable to make connection to %@ - %@",
GSPrivateSockaddrName(&sockAddr), [NSError _last]);
if (addrNum < [addrs count])
{
BOOL result;
result = [self connectToPort: aPort beforeDate: when];
M_UNLOCK(myLock);
return result;
}
else
{
M_UNLOCK(myLock);
return NO; /* Tried all addresses */
}
}
}
state = GS_H_TRYCON;
l = [NSRunLoop currentRunLoop];
[self _add: l];
while (valid == YES && state == GS_H_TRYCON
&& [when timeIntervalSinceNow] > 0)
{
M_UNLOCK(myLock);
NS_DURING
[l runMode: NSConnectionReplyMode beforeDate: when];
NS_HANDLER
M_LOCK(myLock);
[self _rem: l];
M_UNLOCK(myLock);
[localException raise];
NS_ENDHANDLER
M_LOCK(myLock);
}
[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)
{
if (addrNum < [addrs count] && [when timeIntervalSinceNow] > 0)
{
BOOL result;
/*
* The connection attempt failed, but there are still IP addresses
* that we haven't tried.
*/
result = [self connectToPort: aPort beforeDate: when];
M_UNLOCK(myLock);
return result;
}
addrNum = 0;
state = GS_H_UNCON;
M_UNLOCK(myLock);
return NO; /* connection failed */
}
else
{
int status = 1;
if (setsockopt(desc, SOL_SOCKET, SO_KEEPALIVE, (char*)&status,
(OPTLEN)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(defaultAddress);
DESTROY(rData);
DESTROY(rItems);
DESTROY(wMsgs);
DESTROY(myLock);
[super dealloc];
}
- (NSString*) description
{
return [NSString stringWithFormat: @"Handle (%d) to %@",
desc, GSPrivateSockaddrName(&sockAddr)];
}
- (int) descriptor
{
return desc;
}
#if defined(_WIN32)
- (int) eventHandle
{
return (int) (size_t) event;
}
#endif
- (void) finalize
{
[self invalidate];
#if defined(_WIN32)
if (event != WSA_INVALID_EVENT)
{
WSACloseEvent(event);
event = WSA_INVALID_EVENT;
}
#endif
if (desc >= 0)
{
(void)close(desc);
desc = -1;
}
}
- (void) invalidate
{
if (valid == YES)
{
M_LOCK(myLock);
if (valid == YES)
{
valid = NO;
NSDebugMLLog(@"GSTcpHandle",
@"invalidated 0x%"PRIxPTR, (NSUInteger)self);
[[self recvPort] removeHandle: self];
[[self sendPort] removeHandle: self];
}
M_UNLOCK(myLock);
}
}
- (BOOL) isValid
{
return valid;
}
- (NSSocketPort*) recvPort
{
if (recvPort == nil)
return nil;
else
return recvPort;
}
- (void) receivedEventRead
{
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 < rWant)
{
want = rWant;
[rData setLength: want];
}
if (want < NETBLOCK)
{
want = NETBLOCK;
[rData setLength: want];
}
}
/*
* Now try to fill the buffer with data.
*/
bytes = [rData mutableBytes];
res = recv(desc, bytes + rLength, want - rLength, 0);
if (res <= 0)
{
if (res == 0)
{
NSDebugMLLog(@"GSTcpHandle",
@"read eof on 0x%"PRIxPTR, (NSUInteger)self);
[self invalidate];
return;
}
#ifdef _WIN32
else if (WSAGetLastError()!= WSAEINTR
&& WSAGetLastError()!= WSAEWOULDBLOCK)
#else
else if (errno != EINTR && errno != EAGAIN)
#endif /* !_WIN32 */
{
NSDebugMLLog(@"GSTcpHandle",
@"read failed - %@ on 0x%p", [NSError _last], self);
[self invalidate];
return;
}
res = 0; /* Interrupted - continue */
}
NSDebugMLLog(@"GSTcpHandle",
@"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 > 128)
{
NSLog(@"%@ - unreasonable length (%u) for port",
self, l);
[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 (l > maxDataLength)
{
NSLog(@"%@ - unreasonable length (%u) for data",
self, l);
[self invalidate];
return;
}
/*
* 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 (l > maxDataLength)
{
NSLog(@"%@ - unreasonable length (%u) for data",
self, l);
[self invalidate];
return;
}
/*
* 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", self);
[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;