File: CWTCPConnection.m

package info (click to toggle)
pantomime 1.4.0%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,288 kB
  • sloc: objc: 22,039; makefile: 11; sh: 4
file content (502 lines) | stat: -rw-r--r-- 10,023 bytes parent folder | download
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
/*
**  CWTCPConnection.m
**
**  Copyright (c) 2001-2007 Ludovic Marcotte
**  Copyright (C) 2016-2020 Riccardo Mottola
**
**  Author: Ludovic Marcotte <ludovic@Sophos.ca>
**          Riccardo Mottola <rm@gnu.org>
**
**  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 General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#import <Pantomime/CWTCPConnection.h>

#import <Pantomime/io.h>
#import <Pantomime/CWConstants.h>
#import <Pantomime/CWDNSManager.h>

#import <Foundation/NSException.h>
#import <Foundation/NSRunLoop.h> //test
#import <Foundation/NSValue.h>

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

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

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

#define DEFAULT_TIMEOUT 600

//
//
//
@interface CWTCPConnection (Private)

- (void) _DNSResolutionCompleted: (NSNotification *) theNotification;
- (void) _DNSResolutionFailed: (NSNotification *) theNotification;

@end


//
//
//
@implementation CWTCPConnection

+ (void) initialize
{
  SSL_library_init();
  SSL_load_error_strings();
}

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


//
// This methods throws an exception if the connection timeout
// is exhausted and the connection hasn't been established yet.
//
- (id) initWithName: (NSString *) theName
	       port: (unsigned int) thePort
  connectionTimeout: (unsigned int) theConnectionTimeout
	readTimeout: (unsigned int) theReadTimeout
       writeTimeout: (unsigned int) theWriteTimeout
	 background: (BOOL) theBOOL
{
  NSArray *addresses;

  struct sockaddr_in server;
#ifdef __MINGW32__
  u_long nonblock = 1;
#else
  int nonblock = 1;
#endif

  if (theName == nil || thePort <= 0)
    {
      AUTORELEASE(self);
      return nil;
    }

  self = [super init];
  if (self)
    {
  _connectionTimeout = theConnectionTimeout;
 
  ASSIGN(_name, theName);
  _port = thePort;

  _dns_resolution_completed = ssl_handshaking = NO;
  _ssl = NULL;
 
  // We get the file descriptor associated to a socket
  _fd = socket(PF_INET, SOCK_STREAM, 0);

  if (_fd == -1) 
    {
      AUTORELEASE(self);
      return nil;
    }
  
  [[NSNotificationCenter defaultCenter]
    addObserver: self
    selector: @selector(_DNSResolutionCompleted:)
    name: PantomimeDNSResolutionCompleted
    object: nil];

  [[NSNotificationCenter defaultCenter]
    addObserver: self
    selector: @selector(_DNSResolutionFailed:)
    name: PantomimeDNSResolutionFailed
    object: nil];

  if (!theBOOL)
    {
      addresses = [[CWDNSManager singleInstance] addressesForName: theName  background: NO];
      
      if (!addresses)
	{
	  safe_close(_fd);
	  AUTORELEASE(self);
	  return nil;
	}

      _dns_resolution_completed = YES;

      server.sin_family = AF_INET;
      server.sin_addr.s_addr = [(NSNumber *)[addresses objectAtIndex: 0] unsignedIntValue];
      server.sin_port = htons(thePort);
      
      // If we don't connect in background, we must try to connect right away
      // and return on any errors.
      if (connect(_fd, (struct sockaddr *)&server, sizeof(server)) != 0)
	{
	  AUTORELEASE(self);
	  return nil;
	}
    }
  
  // We set the non-blocking I/O flag on _fd
#ifdef __MINGW32__
  if (ioctlsocket(_fd, FIONBIO, &nonblock) == -1)
#else
  if (ioctl(_fd, FIONBIO, &nonblock) == -1)
#endif
    {
      safe_close(_fd);
      AUTORELEASE(self);
      return nil;
    }

  if (theBOOL) [[CWDNSManager singleInstance] addressesForName: theName  background: YES];
    }
  return self;
}


//
//
//
- (void) dealloc
{
  //NSLog(@"TCPConnection: -dealloc");
  [[NSNotificationCenter defaultCenter] removeObserver: self];
  RELEASE(_name);

  if (_ssl)
    {
      SSL_free(_ssl);    
    }

  if (_ctx)
    {
      SSL_CTX_free(_ctx);
    }
  
  [super dealloc];
}


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


//
//
//
- (BOOL) isConnected
{
  struct timeval timeout;
  fd_set fdset;
  int value;

  if (!_dns_resolution_completed)
    {
      return NO;
    }

  // We remove all descriptors from the set fdset
  FD_ZERO(&fdset);
  
  // We add the descriptor _fd to the fdset set
  FD_SET(_fd, &fdset);
  
  // We set the timeout for our connection
  timeout.tv_sec = 0;
  timeout.tv_usec = 1;
  
  value = select(_fd + 1, NULL, &fdset, NULL, &timeout);
  
  // An error occured..
  if (value == -1)
    {
      return NO;
    }
  // Our fdset has ready descriptors (for writability)
  else if (value > 0)
    {
#ifdef __MINGW32__
      int size;
#else
      socklen_t size;
#endif
      int error;
      
      size = sizeof(error);
      
      // We get the options at the socket level (so we use SOL_SOCKET)
      // returns -1 on error, 0 on success
      if (getsockopt(_fd, SOL_SOCKET, SO_ERROR, &error, &size) == -1)
	{
	  return NO;
	}
      
      if (error != 0)
	{
#warning handle right way in CWService tick if the port was incorrectly specified
	  return NO;
	}
    }
  // select() has returned 0 which means that the timeout has expired.
  else
    {
      return NO;
    }

  return YES;
}


//
//
//
- (BOOL) isSSL
{
  return (_ssl ? YES : NO);
}


//
// other methods
//
- (void) close
{
  //NSLog(@"TCPConnection: -close");

  if (_ssl)
    {
      SSL_shutdown(_ssl);
    }

  safe_close(_fd);
  _fd = -1;
}


//
//
//
- (ssize_t) read: (char *) buf
      length: (size_t) len
{
  if (ssl_handshaking)
    {
      return 0;
    }

  if (_ssl)
    {
      return SSL_read(_ssl, buf, (int)len);
    }

  return safe_recv(_fd, buf, len, 0);
}


//
//
//
- (ssize_t) write: (char *) buf
       length: (size_t) len
{
  if (ssl_handshaking)
    {
      return 0;
    }

  if (_ssl)
    {
      return SSL_write(_ssl, buf, (int)len);
    }

  return send(_fd, buf, len, 0);
}


//
// 0  -> success
// -1 ->
// -2 -> handshake error
//
- (int) startSSL
{
  int ret;
  
  // For now, we do not verify the certificates...
  _ctx = SSL_CTX_new(SSLv23_client_method());
  SSL_CTX_set_verify(_ctx, SSL_VERIFY_NONE, NULL);
  SSL_CTX_set_mode(_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);

  // We then connect the SSL socket
  _ssl = SSL_new(_ctx);
  SSL_set_fd(_ssl, _fd);
  ret = SSL_connect(_ssl);

  if (ret != 1)
    {
      int rc;

      rc = SSL_get_error(_ssl, ret);

      if ((rc != SSL_ERROR_WANT_READ) && (rc != SSL_ERROR_WANT_WRITE))
	{
	  // SSL handshake error...
	  //NSLog(@"SSL handshake error.");
	  return -2;
	}
      else
	{
	  NSDate *limit;

	  //NSLog(@"SSL handshaking... %d", rc);
	  ssl_handshaking = YES; 
	  limit = [[NSDate alloc] initWithTimeIntervalSinceNow: DEFAULT_TIMEOUT];

	  while ((rc == SSL_ERROR_WANT_READ || rc == SSL_ERROR_WANT_WRITE)
		 && [limit timeIntervalSinceNow] > 0.0)
	    {
	      [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.1]];
	      ret = SSL_connect(_ssl);
	      //NSLog(@"ret = %d", ret);
	      if (ret != 1)
		{
		  //int e = errno;
		  rc = SSL_get_error(_ssl, ret);
		  //NSLog(@"%s  errno = %s", ERR_error_string(rc, NULL), strerror(e));
		}
	      else
		{
		  rc = SSL_ERROR_NONE;
		}
	      
	      //NSLog(@"rc = %d", rc);
	    }

	  RELEASE(limit);

	  if (rc != SSL_ERROR_NONE)
	    {
	      //NSLog(@"ERROR DURING HANDSHAKING...");
	      //NSLog(@"unable to make SSL connection: %s", ERR_error_string(rc, NULL));
	      //ERR_print_errors_fp(stderr);
	      ssl_handshaking = NO;
	      SSL_free(_ssl);
	      _ssl = NULL;
	      return -2;
	    }
	  
	  // We are done with handshaking
	  ssl_handshaking = NO;
	}
    }

  // Everything went all right, let's tell our caller.
  return 0;
}

@end

//
//
//
@implementation CWTCPConnection (Private)

- (void) _DNSResolutionCompleted: (NSNotification *) theNotification
{
  struct sockaddr_in server;

  if (![[[theNotification userInfo] objectForKey: @"Name"] isEqualToString: _name])
    {
      return;
    }

  NSDebugLog(@"DNS resolution completed for name |%@|", [[theNotification userInfo] objectForKey: @"Name"]);
  [[NSNotificationCenter defaultCenter] removeObserver: self];
  _dns_resolution_completed = YES;

  server.sin_family = AF_INET;
  server.sin_addr.s_addr = [[[theNotification userInfo] objectForKey: @"Address"] unsignedIntValue];
  server.sin_port = htons(_port);

  // We initiate our connection to the socket
  if (connect(_fd, (struct sockaddr *)&server, sizeof(server)) == -1)
    {
#ifdef __MINGW32__
      if (WSAGetLastError() == WSAEWOULDBLOCK)
#else
      if (errno == EINPROGRESS)
#endif
	{
	  return;
	} // if ( errno == EINPROGRESS ) ...
      else
	{
	  NSLog(@"Failed to connect asynchronously.");
	  safe_close(_fd);
	}
    } // if ( connect(...) )
}

//
//
//
- (void) _DNSResolutionFailed: (NSNotification *) theNotification
{
  NSDebugLog(@"DNS resolution failed!");
 
  _dns_resolution_completed = YES;
  safe_close(_fd);

  [[NSNotificationCenter defaultCenter] removeObserver: self];
}

@end