ObjFW  Check-in [c5c4d38220]

Overview
Comment:OFTCPSocket: Implement sync connect via async
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: c5c4d38220881a9077f98592c4d525b90d752f1510a8391cc080c60e83c7911c
User & Date: js on 2018-10-06 19:36:27
Other Links: manifest | tags
Context
2018-10-06
19:41
OFTCPSocket: -[setBlocking:] on new connections check-in: 02073abe82 user: js tags: trunk
19:36
OFTCPSocket: Implement sync connect via async check-in: c5c4d38220 user: js tags: trunk
18:39
OFSystemInfo: Fix signedness in comparison check-in: 9723036211 user: js tags: trunk
Changes

Modified src/Makefile from [a4eb0eb187] to [d620634847].

198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
198
199
200
201
202
203
204

205
206
207
208
209
210
211







-







SRCS_FILES += OFSettings_INIFile.m	\
	      OFURLHandler_file.m
SRCS_SOCKETS += OFKernelEventObserver.m			\
		${OFKERNELEVENTOBSERVER_EPOLL_M}	\
		${OFKERNELEVENTOBSERVER_KQUEUE_M}	\
		${OFKERNELEVENTOBSERVER_POLL_M}		\
		${OFKERNELEVENTOBSERVER_SELECT_M}	\
		OFTCPSocket+SOCKS5.m			\
		OFURLHandler_HTTP.m

OBJS_EXTRA = ${RUNTIME_RUNTIME_A}	\
	     ${EXCEPTIONS_EXCEPTIONS_A} \
	     ${ENCODINGS_ENCODINGS_A}	\
	     ${FORWARDING_FORWARDING_A}	\
	     ${INVOCATION_INVOCATION_A}

Deleted src/OFTCPSocket+SOCKS5.h version [be2dcebc93].

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



































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
/*
 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017,
 *               2018
 *   Jonathan Schleifer <js@heap.zone>
 *
 * All rights reserved.
 *
 * This file is part of ObjFW. It may be distributed under the terms of the
 * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
 * the packaging of this file.
 *
 * Alternatively, it may be distributed under the terms of the GNU General
 * Public License, either version 2 or 3, which can be found in the file
 * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
 * file.
 */

#import "OFTCPSocket.h"

OF_ASSUME_NONNULL_BEGIN

#ifdef __cplusplus
extern "C" {
#endif
extern int _OFTCPSocket_SOCKS5_reference;
#ifdef __cplusplus
}
#endif

@interface OFTCPSocket (SOCKS5)
- (void)OF_SOCKS5ConnectToHost: (OFString *)host
			  port: (uint16_t)port;
@end

OF_ASSUME_NONNULL_END

Deleted src/OFTCPSocket+SOCKS5.m version [9396f7978b].

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






































































































































































































-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
/*
 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017,
 *               2018
 *   Jonathan Schleifer <js@heap.zone>
 *
 * All rights reserved.
 *
 * This file is part of ObjFW. It may be distributed under the terms of the
 * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
 * the packaging of this file.
 *
 * Alternatively, it may be distributed under the terms of the GNU General
 * Public License, either version 2 or 3, which can be found in the file
 * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
 * file.
 */

#include "config.h"

#include <errno.h>

#import "OFTCPSocket+SOCKS5.h"
#import "OFData.h"

#import "OFConnectionFailedException.h"
#import "OFOutOfRangeException.h"
#import "OFReadFailedException.h"
#import "OFWriteFailedException.h"

#import "socket_helpers.h"

/* Reference for static linking */
int _OFTCPSocket_SOCKS5_reference;

static void
sendOrThrow(OFTCPSocket *self, of_socket_t sock, char *buffer, int length)
{
#ifndef OF_WINDOWS
	ssize_t bytesWritten;
#else
	int bytesWritten;
#endif

	if ((bytesWritten = send(sock, (const void *)buffer, length, 0)) < 0)
		@throw [OFWriteFailedException
		    exceptionWithObject: self
			requestedLength: length
			   bytesWritten: 0
				  errNo: of_socket_errno()];

	if ((int)bytesWritten != length)
		@throw [OFWriteFailedException exceptionWithObject: self
						   requestedLength: length
						      bytesWritten: bytesWritten
							     errNo: 0];
}

static void
recvExact(OFTCPSocket *self, of_socket_t sock, char *buffer, int length)
{
	while (length > 0) {
		ssize_t ret = recv(sock, (void *)buffer, length, 0);

		if (ret < 0)
			@throw [OFReadFailedException
			    exceptionWithObject: self
				requestedLength: length
					  errNo: of_socket_errno()];

		buffer += ret;
		length -= ret;
	}
}

@implementation OFTCPSocket (SOCKS5)
- (void)OF_SOCKS5ConnectToHost: (OFString *)host
			  port: (uint16_t)port
{
	char request[] = { 5, 1, 0, 3 };
	char reply[256];
	void *pool;
	OFMutableData *connectRequest;

	if ([host UTF8StringLength] > 255)
		@throw [OFOutOfRangeException exception];

	/* 5 1 0 -> no authentication */
	sendOrThrow(self, _socket, request, 3);

	recvExact(self, _socket, reply, 2);

	if (reply[0] != 5 || reply[1] != 0) {
		[self close];
		@throw [OFConnectionFailedException
		    exceptionWithHost: host
				 port: port
			       socket: self
				errNo: EPROTONOSUPPORT];
	}

	/* CONNECT request */
	pool = objc_autoreleasePoolPush();
	connectRequest = [OFMutableData data];

	[connectRequest addItems: request
			   count: 4];

	request[0] = [host UTF8StringLength];
	[connectRequest addItem: request];
	[connectRequest addItems: [host UTF8String]
			   count: request[0]];

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

	if ([connectRequest count] > INT_MAX)
		@throw [OFOutOfRangeException exception];

	sendOrThrow(self, _socket,
	    [connectRequest items], (int)[connectRequest count]);

	objc_autoreleasePoolPop(pool);

	recvExact(self, _socket, reply, 4);

	if (reply[0] != 5 || reply[2] != 0) {
		[self close];
		@throw [OFConnectionFailedException
		    exceptionWithHost: host
				 port: port
			       socket: self
				errNo: EPROTONOSUPPORT];
	}

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

		[self close];

		switch (reply[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 = 0;
			break;
		}

		@throw [OFConnectionFailedException exceptionWithHost: host
								 port: port
							       socket: self
								errNo: errNo];
	}

	/* Skip the rest of the reply */
	switch (reply[3]) {
	case 1: /* IPv4 */
		recvExact(self, _socket, reply, 4);
		break;
	case 3: /* Domain name */
		recvExact(self, _socket, reply, 1);
		recvExact(self, _socket, reply, reply[0]);
		break;
	case 4: /* IPv6 */
		recvExact(self, _socket, reply, 16);
		break;
	default:
		[self close];
		@throw [OFConnectionFailedException
		    exceptionWithHost: host
				 port: port
			       socket: self
				errNo: EPROTONOSUPPORT];
	}

	recvExact(self, _socket, reply, 2);
}
@end

Modified src/OFTCPSocket.m from [1071039b7f] to [b569f752f9].

28
29
30
31
32
33
34
35

36
37
38
39
40
41
42
28
29
30
31
32
33
34

35
36
37
38
39
40
41
42







-
+








#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif

#import "OFTCPSocket.h"
#import "OFTCPSocket+Private.h"
#import "OFTCPSocket+SOCKS5.h"
#import "OFDate.h"
#import "OFDNSResolver.h"
#import "OFData.h"
#import "OFRunLoop.h"
#import "OFRunLoop+Private.h"
#import "OFString.h"
#import "OFThread.h"
#import "OFTimer.h"
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
55
56
57
58
59
60
61







62
63
64
65
66
67

68
69
70
71
72
73
74
75







-
-
-
-
-
-
-


+



-
+







#import "OFOutOfRangeException.h"
#import "OFSetOptionFailedException.h"

#import "socket.h"
#import "socket_helpers.h"
#import "resolver.h"

/* References for static linking */
void
_references_to_categories_of_OFTCPSocket(void)
{
	_OFTCPSocket_SOCKS5_reference = 1;
}

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_ConnectContext: OFObject
@interface OFTCPSocket_AsyncConnectContext: OFObject
{
	OFTCPSocket *_socket;
	OFString *_host;
	uint16_t _port;
	OFString *_SOCKS5Host;
	uint16_t _SOCKS5Port;
	id _target;
147
148
149
150
151
152
153












154

155
156
157
158
159
160
161
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







+
+
+
+
+
+
+
+
+
+
+
+
-
+







-		(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 _connected;
	id _exception;
}

- (void)socketDidConnect: (OFTCPSocket *)sock
		 context: (id)context
	       exception: (id)exception;
@end

@implementation OFTCPSocket_ConnectContext
@implementation OFTCPSocket_AsyncConnectContext
- (instancetype)initWithSocket: (OFTCPSocket *)sock
			  host: (OFString *)host
			  port: (uint16_t)port
		    SOCKS5Host: (OFString *)SOCKS5Host
		    SOCKS5Port: (uint16_t)SOCKS5Port
			target: (id)target
		      selector: (SEL)selector
631
632
633
634
635
636
637



















638
639
640
641
642
643
644
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







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







			      target: self
			    selector: @selector(socket:didReadSOCKS5Address:
					  length:context:exception:)
			     context: nil];
	return false;
}
@end

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

	[super dealloc];
}

- (void)socketDidConnect: (OFTCPSocket *)sock
		 context: (id)context
	       exception: (id)exception
{
	if (exception != nil)
		_exception = [exception retain];

	_connected = true;
}
@end

@implementation OFTCPSocket
@synthesize SOCKS5Host = _SOCKS5Host, SOCKS5Port = _SOCKS5Port;

+ (void)setSOCKS5Host: (OFString *)host
{
	id old = defaultSOCKS5Host;
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
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







-
-
-
-
-
-
-
-
+
+
+
+
-
-
-
-
-
-
+
+
-
-
+
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
+
+
-
-
-
-
-
+
+
-
-
-
-
+
-
-
-
-
+
-

-
-
-
-
+
-
-
-
-
-
+
+
+
+
-
-
+
-
-
-
-
-

-
-
-
+








	return errNo;
}

- (void)connectToHost: (OFString *)host
		 port: (uint16_t)port
{
	OFString *destinationHost = host;
	uint16_t destinationPort = port;
	of_resolver_result_t **results, **iter;
	int errNo = 0;

	if (_socket != INVALID_SOCKET)
		@throw [OFAlreadyConnectedException exceptionWithSocket: self];

	void *pool = objc_autoreleasePoolPush();
	OFTCPSocket_ConnectContext *context =
	    [[[OFTCPSocket_ConnectContext alloc] init] autorelease];
	OFRunLoop *runLoop = [OFRunLoop currentRunLoop];
	if (_SOCKS5Host != nil) {
		/* Connect to the SOCKS5 proxy instead */
		host = _SOCKS5Host;
		port = _SOCKS5Port;
	}


	[self asyncConnectToHost: host
	results = of_resolve_host(host, port, SOCK_STREAM);

			    port: port
	for (iter = results; *iter != NULL; iter++) {
		of_resolver_result_t *result = *iter;
		of_socket_address_t address;

		     runLoopMode: connectRunLoopMode
		switch (result->family) {
		case AF_INET:
			address.family = OF_SOCKET_ADDRESS_FAMILY_IPV4;
			break;
#ifdef AF_INET6
		case AF_INET6:
			address.family = OF_SOCKET_ADDRESS_FAMILY_IPV6;
			break;
#endif
		default:
			errNo = EAFNOSUPPORT;
			continue;
			  target: context
		}

			selector: @selector(socketDidConnect:context:exception:)
			 context: nil];
		if (result->addressLength > sizeof(address)) {
			errNo = EOVERFLOW;
			continue;
		}


	while (!context->_connected)
		address.length = result->addressLength;
		memcpy(&address.sockaddr.sockaddr, result->address,
		    result->addressLength);

		[runLoop runMode: connectRunLoopMode
		if (![self of_createSocketForAddress: &address
					       errNo: &errNo])
			continue;

		      beforeDate: nil];
		_blocking = true;

		if (![self of_connectSocketToAddress: &address
					       errNo: &errNo]) {
			[self of_closeSocket];
			continue;
	/* Cleanup */
		}

		break;
	}

	[runLoop runMode: connectRunLoopMode
	      beforeDate: [OFDate date]];

	if (context->_exception != nil)
	of_resolver_free(results);

		@throw context->_exception;
	if (_socket == INVALID_SOCKET)
		@throw [OFConnectionFailedException exceptionWithHost: host
								 port: port
							       socket: self
								errNo: errNo];

	if (_SOCKS5Host != nil)
		[self OF_SOCKS5ConnectToHost: destinationHost
					port: destinationPort];
	objc_autoreleasePoolPop(pool);
}

- (void)asyncConnectToHost: (OFString *)host
		      port: (uint16_t)port
		    target: (id)target
		  selector: (SEL)selector
		   context: (id)context
833
834
835
836
837
838
839
840

841
842
843
844
845
846
847
813
814
815
816
817
818
819

820
821
822
823
824
825
826
827







-
+







	       runLoopMode: (of_run_loop_mode_t)runLoopMode
		    target: (id)target
		  selector: (SEL)selector
		   context: (id)context
{
	void *pool = objc_autoreleasePoolPush();

	[[[[OFTCPSocket_ConnectContext alloc]
	[[[[OFTCPSocket_AsyncConnectContext alloc]
	    initWithSocket: self
		      host: host
		      port: port
		SOCKS5Host: _SOCKS5Host
		SOCKS5Port: _SOCKS5Port
		    target: target
		  selector: selector
865
866
867
868
869
870
871
872

873
874
875
876
877
878
879
845
846
847
848
849
850
851

852
853
854
855
856
857
858
859







-
+







- (void)asyncConnectToHost: (OFString *)host
		      port: (uint16_t)port
	       runLoopMode: (of_run_loop_mode_t)runLoopMode
		     block: (of_tcp_socket_async_connect_block_t)block
{
	void *pool = objc_autoreleasePoolPush();

	[[[[OFTCPSocket_ConnectContext alloc]
	[[[[OFTCPSocket_AsyncConnectContext alloc]
	    initWithSocket: self
		      host: host
		      port: port
		SOCKS5Host: _SOCKS5Host
		SOCKS5Port: _SOCKS5Port
		     block: block] autorelease]
	    startWithRunLoopMode: runLoopMode];