File: TCPConnection.m

package info (click to toggle)
pantomime 1.1.2.dfsg-8
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 1,608 kB
  • ctags: 388
  • sloc: objc: 15,433; ansic: 2,843; makefile: 87; sh: 4
file content (745 lines) | stat: -rw-r--r-- 15,407 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
/*
**  TCPConnection.m
**
**  Copyright (c) 2001, 2002, 2003
**
**  Author: Ludovic Marcotte <ludovic@Sophos.ca>
**
**  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.1 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

#include <Pantomime/TCPConnection.h>

#include <Pantomime/Constants.h>

#include <Foundation/NSDebug.h>
#include <Foundation/NSException.h>
#include <Foundation/NSValue.h>

#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/errno.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>	/* For read() and write() and close() */

#ifdef MACOSX
#include <sys/uio.h>	/* For read() and write() */
#endif

#ifndef FIONBIO
#include <sys/filio.h>   /* For FIONBIO on Solaris */
#endif

#define DEFAULT_TIMEOUT 60
#define READ_BUFFER     4096

@implementation TCPConnection

//
//
//
- (void) dealloc
{
  RELEASE(name);

  TEST_RELEASE(stopTarget);

  [super dealloc];
}


//
//
//
- (id) initWithName: (NSString *) theName
	       port: (int) thePort
{
  return [self initWithName: theName
	       port: thePort
	       connectionTimeout: DEFAULT_TIMEOUT
	       readTimeout: DEFAULT_TIMEOUT
	       writeTimeout: DEFAULT_TIMEOUT];
}


//
// This methods throws an exception if the connection timeout
// is exhausted and the connection hasn't been established yet.d
//
- (id) initWithName: (NSString *) theName
	       port: (int) thePort
  connectionTimeout: (int) theConnectionTimeout
	readTimeout: (int) theReadTimeout
       writeTimeout: (int) theWriteTimeout
{
  struct sockaddr_in server;
  struct hostent *host_info;
  int nonblock = 1;

  stopTarget = nil;

  if ( theName == nil || thePort <= 0 )
    {
      AUTORELEASE(self);
      NSDebugLog(@"TCPConnection: Attempted to initialize with a nil name or a negative or zero port value.");
      return nil;
    }
  
  // We set our ivars through our mutation methods
  [self setName: theName];
  [self setPort: thePort];
  [self setConnectionTimeout: theConnectionTimeout];
  [self setReadTimeout: theReadTimeout];
  [self setWriteTimeout: theWriteTimeout];
  
  // We get the file descriptor associated to a socket
  fd = socket(PF_INET, SOCK_STREAM, 0);

  if ( [self fd] == -1 ) 
    {
      AUTORELEASE(self);
      NSDebugLog(@"TCPConnection: An error occured while creating the endpoint for communications");
      return nil;
    }

  // We get our hostent structure for our server name
  host_info = gethostbyname([[self name] cString]);
  
  if ( !host_info )
    {
      AUTORELEASE(self);
      NSDebugLog(@"TCPConnection: Unable to get the hostent structure.");
      return nil;
    }

  server.sin_family = host_info->h_addrtype;
  memcpy((char *)&server.sin_addr, host_info->h_addr, host_info->h_length);
  server.sin_port = htons( [self port] );

  // We set the non-blocking I/O flag on [self fd]
  if ( ioctl([self fd], FIONBIO, &nonblock) == -1 )
    {
      AUTORELEASE(self);
      NSDebugLog(@"TCPConnection: Unable to set the non-blocking I/O flag on the socket");
      return nil;
    }
  
  // We initiate our connection to the socket
  if ( connect([self fd], (struct sockaddr *)&server, sizeof(server)) == -1 )
    {
      if ( errno == EINPROGRESS )
        {
          // The socket is non-blocking and the connection cannot be completed immediately.
          fd_set fdset;
          struct timeval timeout;
          int value;
          
          // We remove all descriptors from the set fdset
          FD_ZERO(&fdset);
          
          // We add the descriptor [self fd] to the fdset set
          FD_SET([self fd], &fdset);
	 
	  // We set the timeout for our connection
          timeout.tv_sec = [self connectionTimeout];
          timeout.tv_usec = 0;
          
          value = select ([self fd] + 1, NULL, &fdset, NULL, &timeout);

	  // An error occured..
          if ( value == -1 )
            {
	      AUTORELEASE(self);
              NSDebugLog(@"TCPConnection: An error occured while calling select().");
              return nil;
            }
	  // Our fdset has ready descriptors (for writability)
          else if ( value > 0 )
            {
              int soError, size;
              
	      size = sizeof(soError);
             
              // We get the options at the socket level (so we use SOL_SOCKET)
              // returns -1 on error, 0 on success
              if ( getsockopt([self fd], SOL_SOCKET, SO_ERROR, &soError, &size) == -1 )
                {
		  AUTORELEASE(self);
                  NSDebugLog(@"TCPConnection: An error occured while trying to get the socket options.");
                  return nil;
                }

              if ( soError != 0)
                {
		  AUTORELEASE(self);
                  NSDebugLog(@"TCPConnection: connect failed.");
                  return nil;
                }
            }
	  // select() has returned 0 which means that the timeout has expired.
          else
            {
	      AUTORELEASE(self);
              NSDebugLog(@"TCPConnection: The connection timeout has expired.");
              return nil;
            }
        } // if ( errno == EINPROGRESS ) ...
      else
        {
	  AUTORELEASE(self);
          NSDebugLog(@"TCPConnection: A general socket error occured.");
          return nil;
        }
    } // if ( connect(...) )
  
  return self;
}


//
// access / mutation methods
//

- (NSString *) name
{
  return name;
}

- (void) setName: (NSString *) theName
{
  RELEASE(name);
  RETAIN(theName);
  name = theName;
}

- (int) port
{
  return port;
}

- (void) setPort: (int) thePort
{
  port = thePort;
}

- (int) connectionTimeout
{
  return connectionTimeout;
}

- (void) setConnectionTimeout: (int) theConnectionTimeout
{
  if ( theConnectionTimeout > 0 )
    {
      connectionTimeout = theConnectionTimeout;
    }
  else
    {
      connectionTimeout = DEFAULT_TIMEOUT;
    }
}

- (int) readTimeout
{
  return readTimeout;
}

- (void) setReadTimeout: (int) theReadTimeout
{
  if ( theReadTimeout > 0 )
    {
      readTimeout = theReadTimeout;
    }
  else
    {
      readTimeout = DEFAULT_TIMEOUT;
    }
}

- (int) writeTimeout
{
  return writeTimeout;
}

- (void) setWriteTimeout: (int) theWriteTimeout
{
  if ( theWriteTimeout > 0 )
    {
      writeTimeout = theWriteTimeout;
    }
  else
    {
      writeTimeout = DEFAULT_TIMEOUT;
    }
}


//
// This method is used to return the file descriptor
// associated with our socket.
//
- (int) fd
{
  return fd;
}


//
// other methods
//
- (void) close
{
  if ( close([self fd]) < 0 )
    {
      NSDebugLog(@"TCPConnection: An error occured while closing the file descriptor associated with the socket");
    }
}


//
// Read "theLength" bytes.
//
- (NSData *) readDataOfLength: (int) theLength
{
  NSData *aData;
  char *buf;
  int len;
  
  [self _performStopSelector];

  buf = (char *) malloc( theLength * sizeof(char));
  memset(buf, 0, theLength);
  len = theLength;
  
  [self _readBytes: buf
	length: &len];

  aData = [[NSData alloc] initWithBytesNoCopy: buf  
			  length: theLength
			  freeWhenDone: YES];

  if ( [aData length] == 0 )
    {
      RELEASE(aData);
      return nil;
    }
  
  return AUTORELEASE(aData);
}


//
//
//
- (NSData *) readDataToEndOfLine
{
  NSData *aData;
 
  char *buf;
  int len;
  
  buf = (char *) malloc( READ_BUFFER * sizeof(char));
 
  [self _readBytesBySkippingCR: NO  
	buf: &buf  
	length: &len];

  aData = [NSData dataWithBytesNoCopy: buf
    		  length: len
		  freeWhenDone: YES];
  
  return aData;
}


//
// Read a string of size theLenght (excluding the null char).
//
- (NSString *) readStringOfLength: (int) theLength
{
  NSString *aString;
  char *buf;
  int len;

  [self _performStopSelector];

  buf = (char *) malloc( (theLength + 1) * sizeof(char));
  memset(buf, 0, theLength + 1);
  len = theLength;
  
  [self _readBytes: buf
	length: &len];
  
  aString = [NSString stringWithCString: buf];
  free(buf);
  
  //NSLog(@"R: |%@|", aString);
  
  if ( [aString length] == 0 )
    {
      return nil;
    }
 
  return aString;
}


//
// The current line length limit that we read from a socket is 4096 bytes (READ_BUFFER)
// including the null char.
//
- (NSString *) readStringToEndOfLine
{
  return [self readStringToEndOfLineSkippingCR: NO];
}


//
//
//
- (NSString *) readStringToEndOfLineSkippingCR: (BOOL) aBOOL
{
  NSString *aString;

  char *buf;
  int len;
  
  buf = (char *) malloc( READ_BUFFER * sizeof(char));
 
  [self _readBytesBySkippingCR: aBOOL
	buf: &buf
	length: &len];

  aString = [NSString stringWithCString: buf];
  free(buf);

  //NSLog(@"R: |%@| %d", aString, len);

  if (aString == nil || [aString length] == 0)
    {
      return nil;
    }
  else
    {
      return aString;
    }
}


//
// Write a 'line' to the socket. A line is a simple string object
// terminated by a CRLF.
//
- (BOOL) writeLine: (NSString *) theLine
{
  return [self writeString: [NSString stringWithFormat: @"%@\r\n", theLine] ];
}


//
// Write a string to the socket. We currently write the cString representation
// of a Unicode string.
//
- (BOOL) writeString: (NSString *) theString
{
  char *cString;
  int len;

  //NSLog(@"S: |%@|", theString);

  [self _performStopSelector];

  cString = (char *)[theString cString];
  len = strlen( cString );
  
  [self _writeBytes: cString
	length: &len];

  return YES;
}


//
// Write bytes to the socket.
//
- (BOOL) writeData: (NSData *) theData
{
  char *bytes;
  int len;

  [self _performStopSelector];

  bytes = (char*)[theData bytes];
  len = [theData length];
  
  [self _writeBytes: bytes
	length: &len]; 
  
  return YES;
}


//
//
//
- (void) setStopTarget: (id) theTarget
{
  if ( theTarget )
    {
      RETAIN(theTarget);
      RELEASE(stopTarget);
      stopTarget = theTarget;
    }
}


//
//
//
- (void) setStopSelector: (SEL) theSelector
{
  stopSelector = theSelector;
}

@end


//
// private methods
// 
@implementation TCPConnection (Private)

- (void) _readBytes: (char *) theBytes
	     length: (int *) theLength
{
  int tot, bytes;
  
  tot = bytes = 0;

  while ( tot < *theLength )
    {
      [self _performStopSelector];
      
      if ( (bytes = read([self fd], theBytes + tot, *theLength - tot)) == -1 )
	{    
	  // The socket is non-blocking and there was no data immediately available for reading.
	  if ( errno == EAGAIN )
	    {
	      fd_set fdset;
	      struct timeval timeout;
	      int value;
	      
	      // We remove all descriptors from the set fdset
	      FD_ZERO(&fdset);
	      
	      // We add the descriptor [self fd] to the fdset set
	      FD_SET([self fd], &fdset);
	      
	      // We set the timeout for our connection
	      timeout.tv_sec = [self readTimeout];
	      timeout.tv_usec = 0;
	      
	      value = select([self fd] + 1, &fdset, NULL, NULL, &timeout);
	      
	      // An error has occrured, we generate our read exception
	      if ( value == -1 )
		{
		  NSDebugLog(@"Error occured for read()");
		}
	      // Our fdset has ready descriptors (for readability)
	      else if ( value > 0 )
		{	  
		  bytes = read([self fd], theBytes + tot, *theLength - tot);
		  tot += bytes;
		}
	      // select() has returned 0 which means that the timeout has expired.
	      // We generate an exception.
	      else 
		{
		  NSException *anException;
		  
		  NSDebugLog(@"Timeout has expired for read()");
		  
		  anException = [NSException exceptionWithName: PantomimeReadTimeoutException
					     reason: @"Timeout has expired for read()"
					     userInfo: nil];
		  [anException raise];
		  
		}
	    } // if ( errno == EAGAIN )
	}
      else
	{
	  tot += bytes;
	}
    } // while (...)
}


//
//
//
- (void) _readBytesBySkippingCR: (BOOL) aBOOL
			    buf: (char **) buf
			 length: (int *) theLength
{
  int i, len, size;
  char c;

  memset(*buf, 0, READ_BUFFER);
  size = READ_BUFFER;
  len = 1;  
  i = 0;

  while ( YES )
    {
      [self _performStopSelector];
      
      [self _readBytes: &c
	    length: &len];

      // We verify if we must expand our buffer
      if ( (i+1) == (size - 2) )
	{
	  size += READ_BUFFER;
	  *buf = realloc(*buf, size); 
	  memset(*buf+READ_BUFFER, 0, READ_BUFFER);
	}

      if ( !aBOOL )
        {
          (*buf)[i] = c;
          i++;
        }

      if (c == '\n')
        {
          break;
        }
     
      // We skip the \r
      if (aBOOL && c != '\r' )
        {
          (*buf)[i] = c;
          i++;
        }
    }

  *theLength = i;
}


//
//
//
- (void) _writeBytes: (char *) theBytes
	      length: (int *) theLength
{
  int tot, bytes;
  
  tot = bytes = 0;

  while ( tot < *theLength )
    {
      [self _performStopSelector];

      if ( (bytes = write([self fd], theBytes + tot, *theLength - tot)) == -1 )
	{
	  // The socket is non-blocking and there was no room in the socket
	  // connected to fd to write the data immediately.
	  if ( errno == EAGAIN )
	    {
	      fd_set fdset;
	      struct timeval timeout;
	      int value;
	      
	      // We remove all descriptors from the set fdset
	      FD_ZERO(&fdset);
	      
	      // We add the descriptor [self fd] to the fdset set
	      FD_SET([self fd], &fdset);
	      
	      // We set the timeout for our connection
	      timeout.tv_sec = [self writeTimeout];
	      timeout.tv_usec = 0;
	      
	      value = select([self fd] + 1, NULL, &fdset, NULL, &timeout);
	      
	      // An error has occrured, we generate our write exception
	      if ( value == -1 )
		{
		  NSDebugLog(@"Error occured for write()");
		}
	      // Our fdset has ready descriptors (for writability)
	      else if ( value > 0 )
		{
		  bytes = write([self fd], theBytes + tot, *theLength - tot);
		  tot += bytes;
		}
	      // select() has returned 0 which means that the timeout has expired.
	      // We generate an exception.
	      else 
		{
		  NSException *anException;
		 
		  NSDebugLog(@"Timeout has expired for write()");
		  
		  anException = [NSException exceptionWithName: PantomimeWriteTimeoutException
					     reason: @"Timeout has expired for write()"
					     userInfo: nil];
		  [anException raise];
		}
	    } // if ( errno == EAGAIN )
	}
      else
	{
	  tot += bytes;
	}
    } // while (...)
}


//
//
//
- (void) _performStopSelector
{
  if ( stopTarget && [stopTarget respondsToSelector: stopSelector] )
    {
      NSNumber *aNumber;

      aNumber = [stopTarget performSelector: stopSelector];

      if (aNumber && [aNumber boolValue])
	{	  
	  NSException *anException;
	  
	  NSDebugLog(@"TCPConnection: Stopping all network operations.");
 
	  anException = [NSException exceptionWithName: PantomimeStopException
				     reason: @"..."
				     userInfo: nil];
	  [anException raise];
	}
    }
}

@end