ObjFW  Diff

Differences From Artifact [44b284db49]:

To Artifact [df6639e5af]:

  • File src/OFTCPSocket.m — part of check-in [d16ad96cbd] at 2018-12-07 01:33:47 on branch trunk — OFStream: Use a delegate for async operations

    The target / selector approach had several drawbacks:

    * It was inconvenient to use, as for every read or write, a target,
    selector and context would need to be specified.
    * It lacked any kind of type-safety and would not even warn about using
    a callback method with the wrong number of parameters.
    * It encouraged using a different callback method for each read or
    write call, which results in code that is hard to follow and also
    slower (as it needs to recreate the async operation with a new
    callback every time). (user: js, size: 26324) [annotate] [blame] [check-ins using]


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

Class of_tls_socket_class = Nil;

static of_run_loop_mode_t connectRunLoopMode = @"of_tcp_socket_connect_mode";
static OFString *defaultSOCKS5Host = nil;
static uint16_t defaultSOCKS5Port = 1080;

@interface OFTCPSocket_AsyncConnectContext: OFObject
{
	OFTCPSocket *_socket;
	OFString *_host;
	uint16_t _port;
	OFString *_SOCKS5Host;
	uint16_t _SOCKS5Port;
	id _target;
	SEL _selector;
	id _context;
#ifdef OF_HAVE_BLOCKS
	of_tcp_socket_async_connect_block_t _block;
#endif
	id _exception;
	OFData *_socketAddresses;
	size_t _socketAddressesIndex;








	/* Longest read is domain name (max 255 bytes) + port */
	unsigned char _buffer[257];

}

- (instancetype)initWithSocket: (OFTCPSocket *)sock
			  host: (OFString *)host
			  port: (uint16_t)port
		    SOCKS5Host: (OFString *)SOCKS5Host
		    SOCKS5Port: (uint16_t)SOCKS5Port







|















>
>
>
>
>
>
>
>


>







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

Class of_tls_socket_class = Nil;

static of_run_loop_mode_t connectRunLoopMode = @"of_tcp_socket_connect_mode";
static OFString *defaultSOCKS5Host = nil;
static uint16_t defaultSOCKS5Port = 1080;

@interface OFTCPSocket_AsyncConnectContext: OFObject <OFStreamDelegate>
{
	OFTCPSocket *_socket;
	OFString *_host;
	uint16_t _port;
	OFString *_SOCKS5Host;
	uint16_t _SOCKS5Port;
	id _target;
	SEL _selector;
	id _context;
#ifdef OF_HAVE_BLOCKS
	of_tcp_socket_async_connect_block_t _block;
#endif
	id _exception;
	OFData *_socketAddresses;
	size_t _socketAddressesIndex;
	enum {
		SOCKS5_STATE_SEND_AUTHENTICATION = 1,
		SOCKS5_STATE_READ_VERSION,
		SOCKS5_STATE_SEND_REQUEST,
		SOCKS5_STATE_READ_RESPONSE,
		SOCKS5_STATE_READ_ADDRESS,
		SOCKS5_STATE_READ_ADDRESS_LENGTH,
	} _SOCKS5State;
	/* Longest read is domain name (max 255 bytes) + port */
	unsigned char _buffer[257];
	OFMutableData *_request;
}

- (instancetype)initWithSocket: (OFTCPSocket *)sock
			  host: (OFString *)host
			  port: (uint16_t)port
		    SOCKS5Host: (OFString *)SOCKS5Host
		    SOCKS5Port: (uint16_t)SOCKS5Port
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
-	(void)resolver: (OFDNSResolver *)resolver
  didResolveDomainName: (OFString *)domainName
       socketAddresses: (OFData *)socketAddresses
	       context: (id)context
	     exception: (id)exception;
- (void)startWithRunLoopMode: (of_run_loop_mode_t)runLoopMode;
- (void)sendSOCKS5Request;
-	       (size_t)socket: (OFTCPSocket *)sock
  didSendSOCKS5Authentication: (const void *)request
		 bytesWritten: (size_t)bytesWritten
		      context: (id)context
		    exception: (id)exception;
-	 (bool)socket: (OFTCPSocket *)sock
  didReadSOCKSVersion: (unsigned char *)SOCKSVersion
	       length: (size_t)length
	      context: (id)context
	    exception: (id)exception;
-	(size_t)socket: (OFTCPSocket *)sock
  didSendSOCKS5Request: (const void *)request
	  bytesWritten: (size_t)bytesWritten
	       context: (id)context
	     exception: (id)exception;
-	   (bool)socket: (OFTCPSocket *)sock
  didReadSOCKS5Response: (unsigned char *)response
		 length: (size_t)length
		context: (id)context
	      exception: (id)exception;
-	  (bool)socket: (OFTCPSocket *)sock
  didReadSOCKS5Address: (unsigned char *)address
		length: (size_t)length
	       context: (id)context
	     exception: (id)exception;
-		(bool)socket: (OFTCPSocket *)sock
  didReadSOCKS5AddressLength: (unsigned char *)addressLength
		      length: (size_t)length
		     context: (id)context
		   exception: (id)exception;
@end

@interface OFTCPSocket_ConnectContext: OFObject
{
@public
	bool _done;
	id _exception;







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







117
118
119
120
121
122
123






























124
125
126
127
128
129
130
-	(void)resolver: (OFDNSResolver *)resolver
  didResolveDomainName: (OFString *)domainName
       socketAddresses: (OFData *)socketAddresses
	       context: (id)context
	     exception: (id)exception;
- (void)startWithRunLoopMode: (of_run_loop_mode_t)runLoopMode;
- (void)sendSOCKS5Request;






























@end

@interface OFTCPSocket_ConnectContext: OFObject
{
@public
	bool _done;
	id _exception;
173
174
175
176
177
178
179


180
181
182
183
184
185
186
		_host = [host copy];
		_port = port;
		_SOCKS5Host = [SOCKS5Host copy];
		_SOCKS5Port = SOCKS5Port;
		_target = [target retain];
		_selector = selector;
		_context = [context retain];


	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}







>
>







152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
		_host = [host copy];
		_port = port;
		_SOCKS5Host = [SOCKS5Host copy];
		_SOCKS5Port = SOCKS5Port;
		_target = [target retain];
		_selector = selector;
		_context = [context retain];

		[_socket setDelegate: self];
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}
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

	return self;
}
#endif

- (void)dealloc
{



	[_socket release];
	[_host release];
	[_SOCKS5Host release];
	[_target release];
	[_context release];
#ifdef OF_HAVE_BLOCKS
	[_block release];
#endif
	[_exception release];
	[_socketAddresses release];


	[super dealloc];
}

- (void)didConnect
{


	if (_exception == nil)
		[_socket setBlocking: true];

#ifdef OF_HAVE_BLOCKS
	if (_block != NULL)
		_block(_socket, _exception);
	else {







>
>
>










>






>
>







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

	return self;
}
#endif

- (void)dealloc
{
	if ([_socket delegate] == self)
		[_socket setDelegate: nil];

	[_socket release];
	[_host release];
	[_SOCKS5Host release];
	[_target release];
	[_context release];
#ifdef OF_HAVE_BLOCKS
	[_block release];
#endif
	[_exception release];
	[_socketAddresses release];
	[_request release];

	[super dealloc];
}

- (void)didConnect
{
	[_socket setDelegate: nil];

	if (_exception == nil)
		[_socket setBlocking: true];

#ifdef OF_HAVE_BLOCKS
	if (_block != NULL)
		_block(_socket, _exception);
	else {
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
						    socketAddresses:context:
						    exception:)
				       context: nil];
}

- (void)sendSOCKS5Request
{

	[_socket asyncWriteBuffer: "\x05\x01\x00"
			   length: 3
		      runLoopMode: [[OFRunLoop currentRunLoop] currentMode]
			   target: self
			 selector: @selector(socket:didSendSOCKS5Authentication:
				       bytesWritten:context:exception:)
			  context: nil];
}

-	       (size_t)socket: (OFTCPSocket *)sock
  didSendSOCKS5Authentication: (const void *)request
		 bytesWritten: (size_t)bytesWritten
		      context: (id)context
		    exception: (id)exception
{
	if (exception != nil) {
		_exception = [exception retain];
		[self didConnect];
		return 0;
	}

	[_socket asyncReadIntoBuffer: _buffer
			 exactLength: 2
			 runLoopMode: [[OFRunLoop currentRunLoop] currentMode]
			      target: self
			    selector: @selector(socket:didReadSOCKSVersion:
					  length:context:exception:)
			     context: nil];

	return 0;
}

-	 (bool)socket: (OFTCPSocket *)sock
  didReadSOCKSVersion: (unsigned char *)SOCKSVersion
	       length: (size_t)length
	      context: (id)context
	    exception: (id)exception
{
	OFMutableData *request;
	uint8_t hostLength;
	unsigned char port[2];

	if (exception != nil) {
		_exception = [exception retain];
		[self didConnect];
		return false;
	}




	if (SOCKSVersion[0] != 5 || SOCKSVersion[1] != 0) {
		_exception = [[OFConnectionFailedException alloc]
		    initWithHost: _host
			    port: _port
			  socket: self
			   errNo: EPROTONOSUPPORT];
		[self didConnect];
		return false;
	}


	request = [OFMutableData data];

	[request addItems: "\x05\x01\x00\x03"
		    count: 4];

	hostLength = (uint8_t)[_host UTF8StringLength];
	[request addItem: &hostLength];
	[request addItems: [_host UTF8String]
		    count: hostLength];

	port[0] = _port >> 8;
	port[1] = _port & 0xFF;
	[request addItems: port
		    count: 2];

	/* Use request as context to retain it */
	[_socket asyncWriteBuffer: [request items]
			   length: [request count]
		      runLoopMode: [[OFRunLoop currentRunLoop] currentMode]
			   target: self
			 selector: @selector(socket:didSendSOCKS5Request:
				       bytesWritten:context:exception:)
			  context: request];

	return false;
}

-	(size_t)socket: (OFTCPSocket *)sock
  didSendSOCKS5Request: (const void *)request
	  bytesWritten: (size_t)bytesWritten
	       context: (id)context
	     exception: (id)exception
{
	if (exception != nil) {
		_exception = [exception retain];
		[self didConnect];
		return 0;
	}

	[_socket asyncReadIntoBuffer: _buffer
			 exactLength: 4
			 runLoopMode: [[OFRunLoop currentRunLoop] currentMode]
			      target: self
			    selector: @selector(socket:didReadSOCKS5Response:
					  length:context:exception:)
			     context: nil];

	return 0;
}

-	   (bool)socket: (OFTCPSocket *)sock
  didReadSOCKS5Response: (unsigned char *)response
		 length: (size_t)length
		context: (id)context
	      exception: (id)exception
{
	of_run_loop_mode_t runLoopMode;

	if (exception != nil) {
		_exception = [exception retain];
		[self didConnect];
		return false;
	}

	if (response[0] != 5 || response[2] != 0) {
		_exception = [[OFConnectionFailedException alloc]
		    initWithHost: _host
			    port: _port
			  socket: self
			   errNo: EPROTONOSUPPORT];
		[self didConnect];
		return false;
	}

	if (response[1] != 0) {
		int errNo;

		switch (response[1]) {
		case 0x02:
			errNo = EACCES;
			break;
		case 0x03:
			errNo = ENETUNREACH;
			break;
		case 0x04:
			errNo = EHOSTUNREACH;
			break;
		case 0x05:
			errNo = ECONNREFUSED;
			break;
		case 0x06:
			errNo = ETIMEDOUT;
			break;
		case 0x07:
			errNo = EPROTONOSUPPORT;
			break;
		case 0x08:
			errNo = EAFNOSUPPORT;
			break;
		default:
			errNo = EPROTO;
			break;
		}

		_exception = [[OFConnectionFailedException alloc]
		    initWithHost: _host
			    port: _port
			  socket: _socket
			   errNo: errNo];
		[self didConnect];
		return false;
	}

	runLoopMode = [[OFRunLoop currentRunLoop] currentMode];

	/* Skip the rest of the response */
	switch (response[3]) {
	case 1: /* IPv4 */

		[_socket asyncReadIntoBuffer: _buffer
				 exactLength: 4 + 2
				 runLoopMode: runLoopMode
				      target: self
				    selector: @selector(socket:
						  didReadSOCKS5Address:length:
						  context:exception:)
				     context: nil];
		return false;
	case 3: /* Domain name */

		[_socket asyncReadIntoBuffer: _buffer
				 exactLength: 1
				 runLoopMode: runLoopMode
				      target: self
				    selector: @selector(socket:
						  didReadSOCKS5AddressLength:
						  length:context:exception:)
				     context: nil];
		return false;
	case 4: /* IPv6 */

		[_socket asyncReadIntoBuffer: _buffer
				 exactLength: 16 + 2
				 runLoopMode: runLoopMode
				      target: self
				    selector: @selector(socket:
						  didReadSOCKS5Address:length:
						  context:exception:)
				     context: nil];
		return false;
	default:
		_exception = [[OFConnectionFailedException alloc]
		    initWithHost: _host
			    port: _port
			  socket: self
			   errNo: EPROTONOSUPPORT];
		[self didConnect];
		return false;
	}

	return false;





}










-	  (bool)socket: (OFTCPSocket *)sock
  didReadSOCKS5Address: (unsigned char *)address


		length: (size_t)length
	       context: (id)context
	     exception: (id)exception
{
	_exception = [exception retain];
	[self didConnect];
	return false;


}



-		(bool)socket: (OFTCPSocket *)sock
  didReadSOCKS5AddressLength: (unsigned char *)addressLength
		      length: (size_t)length
		     context: (id)context
		   exception: (id)exception
{
	if (exception != nil) {
		_exception = [exception retain];
		[self didConnect];
		return false;



	}

	[_socket asyncReadIntoBuffer: _buffer
			 exactLength: addressLength[0] + 2
			 runLoopMode: [[OFRunLoop currentRunLoop] currentMode]
			      target: self
			    selector: @selector(socket:didReadSOCKS5Address:
					  length:context:exception:)
			     context: nil];


	return false;








}
@end

@implementation OFTCPSocket_ConnectContext
- (void)dealloc
{
	[_exception release];







>


|
<
<
<
<


|
|
|
<
<

<
<
<
<
<
|
<
<
|
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<


|
<
<
<
<
|
>
>
>

|
|
|
|
|
|
|
|
|

>
|
>
|
|

|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
|
<
|
<
<
<
<
<
<
<
|
<
<
<
<
<

|
|
|
|
|
|
|
|
|

|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|

<
<
|
|
|
>
|
|
|
<
<
<
<
<
|
|
>
|
|
|
<
<
<
<
<
|
|
>
|

|
<
<
<
<
<
|
|
|
|
|
|
|
|
|
|

|
>
>
>
>
>
|
>
>
>
>
>
>
>
>
|
>
|
<
>
>
|
<
<

<
<
<
>
>
|
>
|
>
|
<
|
|
<
<
<
<
<
|
>
>
>
|
|
|
|
|
|
<
<
<
>
>
|
>
>
>
>
>
>
>
>







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
						    socketAddresses:context:
						    exception:)
				       context: nil];
}

- (void)sendSOCKS5Request
{
	_SOCKS5State = SOCKS5_STATE_SEND_AUTHENTICATION;
	[_socket asyncWriteBuffer: "\x05\x01\x00"
			   length: 3
		      runLoopMode: [[OFRunLoop currentRunLoop] currentMode]];




}

-      (bool)stream: (OF_KINDOF(OFStream *))sock
  didReadIntoBuffer: (void *)buffer
	     length: (size_t)length


{





	of_run_loop_mode_t runLoopMode =


	    [[OFRunLoop currentRunLoop] currentMode];









	unsigned char *SOCKSVersion;





	uint8_t hostLength;
	unsigned char port[2];
	unsigned char *response, *addressLength;





	switch (_SOCKS5State) {
	case SOCKS5_STATE_READ_VERSION:
		SOCKSVersion = buffer;

		if (SOCKSVersion[0] != 5 || SOCKSVersion[1] != 0) {
			_exception = [[OFConnectionFailedException alloc]
			    initWithHost: _host
				    port: _port
				  socket: self
				   errNo: EPROTONOSUPPORT];
			[self didConnect];
			return false;
		}

		[_request release];
		_request = [[OFMutableData alloc] init];

		[_request addItems: "\x05\x01\x00\x03"
			     count: 4];

		hostLength = (uint8_t)[_host UTF8StringLength];
		[_request addItem: &hostLength];
		[_request addItems: [_host UTF8String]
			     count: hostLength];
























		port[0] = _port >> 8;
		port[1] = _port & 0xFF;
		[_request addItems: port
			    count: 2];

		_SOCKS5State = SOCKS5_STATE_SEND_REQUEST;
		[_socket asyncWriteBuffer: [_request items]
				   length: [_request count]
			      runLoopMode: runLoopMode];





		return false;

	case SOCKS5_STATE_READ_RESPONSE:







		response = buffer;






		if (response[0] != 5 || response[2] != 0) {
			_exception = [[OFConnectionFailedException alloc]
			    initWithHost: _host
				    port: _port
				  socket: self
				   errNo: EPROTONOSUPPORT];
			[self didConnect];
			return false;
		}

		if (response[1] != 0) {
			int errNo;

			switch (response[1]) {
			case 0x02:
				errNo = EACCES;
				break;
			case 0x03:
				errNo = ENETUNREACH;
				break;
			case 0x04:
				errNo = EHOSTUNREACH;
				break;
			case 0x05:
				errNo = ECONNREFUSED;
				break;
			case 0x06:
				errNo = ETIMEDOUT;
				break;
			case 0x07:
				errNo = EPROTONOSUPPORT;
				break;
			case 0x08:
				errNo = EAFNOSUPPORT;
				break;
			default:
				errNo = EPROTO;
				break;
			}

			_exception = [[OFConnectionFailedException alloc]
			    initWithHost: _host
				    port: _port
				  socket: _socket
				   errNo: errNo];
			[self didConnect];
			return false;
		}



		/* Skip the rest of the response */
		switch (response[3]) {
		case 1: /* IPv4 */
			_SOCKS5State = SOCKS5_STATE_READ_ADDRESS;
			[_socket asyncReadIntoBuffer: _buffer
					 exactLength: 4 + 2
					 runLoopMode: runLoopMode];





			return false;
		case 3: /* Domain name */
			_SOCKS5State = SOCKS5_STATE_READ_ADDRESS_LENGTH;
			[_socket asyncReadIntoBuffer: _buffer
					 exactLength: 1
					 runLoopMode: runLoopMode];





			return false;
		case 4: /* IPv6 */
			_SOCKS5State = SOCKS5_STATE_READ_ADDRESS;
			[_socket asyncReadIntoBuffer: _buffer
				 exactLength: 16 + 2
				 runLoopMode: runLoopMode];





			return false;
		default:
			_exception = [[OFConnectionFailedException alloc]
			    initWithHost: _host
				    port: _port
				  socket: self
				   errNo: EPROTONOSUPPORT];
			[self didConnect];
			return false;
		}

		return false;
	case SOCKS5_STATE_READ_ADDRESS:
		[self didConnect];
		return false;
	case SOCKS5_STATE_READ_ADDRESS_LENGTH:
		addressLength = buffer;

		_SOCKS5State = SOCKS5_STATE_READ_ADDRESS;
		[_socket asyncReadIntoBuffer: _buffer
				 exactLength: addressLength[0] + 2
				 runLoopMode: runLoopMode];
		return false;
	default:
		assert(0);
		return false;
	}
}


- (size_t)stream: (OF_KINDOF(OFStream *))sock
  didWriteBuffer: (const void **)buffer
	  length: (size_t)length


{



	of_run_loop_mode_t runLoopMode =
	    [[OFRunLoop currentRunLoop] currentMode];

	switch (_SOCKS5State) {
	case SOCKS5_STATE_SEND_AUTHENTICATION:
		_SOCKS5State = SOCKS5_STATE_READ_VERSION;
		[_socket asyncReadIntoBuffer: _buffer

				 exactLength: 2
				 runLoopMode: runLoopMode];





		return 0;
	case SOCKS5_STATE_SEND_REQUEST:
		[_request release];
		_request = nil;

		_SOCKS5State = SOCKS5_STATE_READ_RESPONSE;
		[_socket asyncReadIntoBuffer: _buffer
				 exactLength: 4
				 runLoopMode: runLoopMode];
		return 0;



	default:
		assert(0);
		return 0;
	}
}

-	  (void)stream: (OF_KINDOF(OFStream *))sock
  didFailWithException: (id)exception
{
	_exception = [exception retain];
	[self didConnect];
}
@end

@implementation OFTCPSocket_ConnectContext
- (void)dealloc
{
	[_exception release];