1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/socket/socks5_client_socket.h"
7 #include "base/basictypes.h"
8 #include "base/callback_helpers.h"
9 #include "base/compiler_specific.h"
10 #include "base/format_macros.h"
11 #include "base/strings/string_util.h"
12 #include "base/sys_byteorder.h"
13 #include "base/trace_event/trace_event.h"
14 #include "net/base/io_buffer.h"
15 #include "net/base/net_util.h"
16 #include "net/log/net_log.h"
17 #include "net/socket/client_socket_handle.h"
21 const unsigned int SOCKS5ClientSocket::kGreetReadHeaderSize
= 2;
22 const unsigned int SOCKS5ClientSocket::kWriteHeaderSize
= 10;
23 const unsigned int SOCKS5ClientSocket::kReadHeaderSize
= 5;
24 const uint8
SOCKS5ClientSocket::kSOCKS5Version
= 0x05;
25 const uint8
SOCKS5ClientSocket::kTunnelCommand
= 0x01;
26 const uint8
SOCKS5ClientSocket::kNullByte
= 0x00;
28 static_assert(sizeof(struct in_addr
) == 4, "incorrect system size of IPv4");
29 static_assert(sizeof(struct in6_addr
) == 16, "incorrect system size of IPv6");
31 SOCKS5ClientSocket::SOCKS5ClientSocket(
32 scoped_ptr
<ClientSocketHandle
> transport_socket
,
33 const HostResolver::RequestInfo
& req_info
)
34 : io_callback_(base::Bind(&SOCKS5ClientSocket::OnIOComplete
,
35 base::Unretained(this))),
36 transport_(transport_socket
.Pass()),
37 next_state_(STATE_NONE
),
38 completed_handshake_(false),
41 read_header_size(kReadHeaderSize
),
42 was_ever_used_(false),
43 host_request_info_(req_info
),
44 net_log_(transport_
->socket()->NetLog()) {
47 SOCKS5ClientSocket::~SOCKS5ClientSocket() {
51 int SOCKS5ClientSocket::Connect(const CompletionCallback
& callback
) {
52 DCHECK(transport_
.get());
53 DCHECK(transport_
->socket());
54 DCHECK_EQ(STATE_NONE
, next_state_
);
55 DCHECK(user_callback_
.is_null());
57 // If already connected, then just return OK.
58 if (completed_handshake_
)
61 net_log_
.BeginEvent(NetLog::TYPE_SOCKS5_CONNECT
);
63 next_state_
= STATE_GREET_WRITE
;
67 if (rv
== ERR_IO_PENDING
) {
68 user_callback_
= callback
;
70 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SOCKS5_CONNECT
, rv
);
75 void SOCKS5ClientSocket::Disconnect() {
76 completed_handshake_
= false;
77 transport_
->socket()->Disconnect();
79 // Reset other states to make sure they aren't mistakenly used later.
80 // These are the states initialized by Connect().
81 next_state_
= STATE_NONE
;
82 user_callback_
.Reset();
85 bool SOCKS5ClientSocket::IsConnected() const {
86 return completed_handshake_
&& transport_
->socket()->IsConnected();
89 bool SOCKS5ClientSocket::IsConnectedAndIdle() const {
90 return completed_handshake_
&& transport_
->socket()->IsConnectedAndIdle();
93 const BoundNetLog
& SOCKS5ClientSocket::NetLog() const {
97 void SOCKS5ClientSocket::SetSubresourceSpeculation() {
98 if (transport_
.get() && transport_
->socket()) {
99 transport_
->socket()->SetSubresourceSpeculation();
105 void SOCKS5ClientSocket::SetOmniboxSpeculation() {
106 if (transport_
.get() && transport_
->socket()) {
107 transport_
->socket()->SetOmniboxSpeculation();
113 bool SOCKS5ClientSocket::WasEverUsed() const {
114 return was_ever_used_
;
117 bool SOCKS5ClientSocket::UsingTCPFastOpen() const {
118 if (transport_
.get() && transport_
->socket()) {
119 return transport_
->socket()->UsingTCPFastOpen();
125 bool SOCKS5ClientSocket::WasNpnNegotiated() const {
126 if (transport_
.get() && transport_
->socket()) {
127 return transport_
->socket()->WasNpnNegotiated();
133 NextProto
SOCKS5ClientSocket::GetNegotiatedProtocol() const {
134 if (transport_
.get() && transport_
->socket()) {
135 return transport_
->socket()->GetNegotiatedProtocol();
138 return kProtoUnknown
;
141 bool SOCKS5ClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
142 if (transport_
.get() && transport_
->socket()) {
143 return transport_
->socket()->GetSSLInfo(ssl_info
);
149 void SOCKS5ClientSocket::GetConnectionAttempts(ConnectionAttempts
* out
) const {
153 // Read is called by the transport layer above to read. This can only be done
154 // if the SOCKS handshake is complete.
155 int SOCKS5ClientSocket::Read(IOBuffer
* buf
, int buf_len
,
156 const CompletionCallback
& callback
) {
157 DCHECK(completed_handshake_
);
158 DCHECK_EQ(STATE_NONE
, next_state_
);
159 DCHECK(user_callback_
.is_null());
160 DCHECK(!callback
.is_null());
162 int rv
= transport_
->socket()->Read(
164 base::Bind(&SOCKS5ClientSocket::OnReadWriteComplete
,
165 base::Unretained(this), callback
));
167 was_ever_used_
= true;
171 // Write is called by the transport layer. This can only be done if the
172 // SOCKS handshake is complete.
173 int SOCKS5ClientSocket::Write(IOBuffer
* buf
, int buf_len
,
174 const CompletionCallback
& callback
) {
175 DCHECK(completed_handshake_
);
176 DCHECK_EQ(STATE_NONE
, next_state_
);
177 DCHECK(user_callback_
.is_null());
178 DCHECK(!callback
.is_null());
180 int rv
= transport_
->socket()->Write(
182 base::Bind(&SOCKS5ClientSocket::OnReadWriteComplete
,
183 base::Unretained(this), callback
));
185 was_ever_used_
= true;
189 int SOCKS5ClientSocket::SetReceiveBufferSize(int32 size
) {
190 return transport_
->socket()->SetReceiveBufferSize(size
);
193 int SOCKS5ClientSocket::SetSendBufferSize(int32 size
) {
194 return transport_
->socket()->SetSendBufferSize(size
);
197 void SOCKS5ClientSocket::DoCallback(int result
) {
198 DCHECK_NE(ERR_IO_PENDING
, result
);
199 DCHECK(!user_callback_
.is_null());
201 // Since Run() may result in Read being called,
202 // clear user_callback_ up front.
203 base::ResetAndReturn(&user_callback_
).Run(result
);
206 void SOCKS5ClientSocket::OnIOComplete(int result
) {
207 DCHECK_NE(STATE_NONE
, next_state_
);
208 int rv
= DoLoop(result
);
209 if (rv
!= ERR_IO_PENDING
) {
210 net_log_
.EndEvent(NetLog::TYPE_SOCKS5_CONNECT
);
215 void SOCKS5ClientSocket::OnReadWriteComplete(const CompletionCallback
& callback
,
217 DCHECK_NE(ERR_IO_PENDING
, result
);
218 DCHECK(!callback
.is_null());
221 was_ever_used_
= true;
222 callback
.Run(result
);
225 int SOCKS5ClientSocket::DoLoop(int last_io_result
) {
226 DCHECK_NE(next_state_
, STATE_NONE
);
227 int rv
= last_io_result
;
229 State state
= next_state_
;
230 next_state_
= STATE_NONE
;
232 case STATE_GREET_WRITE
:
234 net_log_
.BeginEvent(NetLog::TYPE_SOCKS5_GREET_WRITE
);
237 case STATE_GREET_WRITE_COMPLETE
:
238 rv
= DoGreetWriteComplete(rv
);
239 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SOCKS5_GREET_WRITE
, rv
);
241 case STATE_GREET_READ
:
243 net_log_
.BeginEvent(NetLog::TYPE_SOCKS5_GREET_READ
);
246 case STATE_GREET_READ_COMPLETE
:
247 rv
= DoGreetReadComplete(rv
);
248 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SOCKS5_GREET_READ
, rv
);
250 case STATE_HANDSHAKE_WRITE
:
252 net_log_
.BeginEvent(NetLog::TYPE_SOCKS5_HANDSHAKE_WRITE
);
253 rv
= DoHandshakeWrite();
255 case STATE_HANDSHAKE_WRITE_COMPLETE
:
256 rv
= DoHandshakeWriteComplete(rv
);
257 net_log_
.EndEventWithNetErrorCode(
258 NetLog::TYPE_SOCKS5_HANDSHAKE_WRITE
, rv
);
260 case STATE_HANDSHAKE_READ
:
262 net_log_
.BeginEvent(NetLog::TYPE_SOCKS5_HANDSHAKE_READ
);
263 rv
= DoHandshakeRead();
265 case STATE_HANDSHAKE_READ_COMPLETE
:
266 rv
= DoHandshakeReadComplete(rv
);
267 net_log_
.EndEventWithNetErrorCode(
268 NetLog::TYPE_SOCKS5_HANDSHAKE_READ
, rv
);
271 NOTREACHED() << "bad state";
275 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
279 const char kSOCKS5GreetWriteData
[] = { 0x05, 0x01, 0x00 }; // no authentication
281 int SOCKS5ClientSocket::DoGreetWrite() {
282 // Since we only have 1 byte to send the hostname length in, if the
283 // URL has a hostname longer than 255 characters we can't send it.
284 if (0xFF < host_request_info_
.hostname().size()) {
285 net_log_
.AddEvent(NetLog::TYPE_SOCKS_HOSTNAME_TOO_BIG
);
286 return ERR_SOCKS_CONNECTION_FAILED
;
289 if (buffer_
.empty()) {
290 buffer_
= std::string(kSOCKS5GreetWriteData
,
291 arraysize(kSOCKS5GreetWriteData
));
295 next_state_
= STATE_GREET_WRITE_COMPLETE
;
296 size_t handshake_buf_len
= buffer_
.size() - bytes_sent_
;
297 handshake_buf_
= new IOBuffer(handshake_buf_len
);
298 memcpy(handshake_buf_
->data(), &buffer_
.data()[bytes_sent_
],
300 return transport_
->socket()
301 ->Write(handshake_buf_
.get(), handshake_buf_len
, io_callback_
);
304 int SOCKS5ClientSocket::DoGreetWriteComplete(int result
) {
308 bytes_sent_
+= result
;
309 if (bytes_sent_
== buffer_
.size()) {
312 next_state_
= STATE_GREET_READ
;
314 next_state_
= STATE_GREET_WRITE
;
319 int SOCKS5ClientSocket::DoGreetRead() {
320 next_state_
= STATE_GREET_READ_COMPLETE
;
321 size_t handshake_buf_len
= kGreetReadHeaderSize
- bytes_received_
;
322 handshake_buf_
= new IOBuffer(handshake_buf_len
);
323 return transport_
->socket()
324 ->Read(handshake_buf_
.get(), handshake_buf_len
, io_callback_
);
327 int SOCKS5ClientSocket::DoGreetReadComplete(int result
) {
332 net_log_
.AddEvent(NetLog::TYPE_SOCKS_UNEXPECTEDLY_CLOSED_DURING_GREETING
);
333 return ERR_SOCKS_CONNECTION_FAILED
;
336 bytes_received_
+= result
;
337 buffer_
.append(handshake_buf_
->data(), result
);
338 if (bytes_received_
< kGreetReadHeaderSize
) {
339 next_state_
= STATE_GREET_READ
;
343 // Got the greet data.
344 if (buffer_
[0] != kSOCKS5Version
) {
345 net_log_
.AddEvent(NetLog::TYPE_SOCKS_UNEXPECTED_VERSION
,
346 NetLog::IntegerCallback("version", buffer_
[0]));
347 return ERR_SOCKS_CONNECTION_FAILED
;
349 if (buffer_
[1] != 0x00) {
350 net_log_
.AddEvent(NetLog::TYPE_SOCKS_UNEXPECTED_AUTH
,
351 NetLog::IntegerCallback("method", buffer_
[1]));
352 return ERR_SOCKS_CONNECTION_FAILED
;
356 next_state_
= STATE_HANDSHAKE_WRITE
;
360 int SOCKS5ClientSocket::BuildHandshakeWriteBuffer(std::string
* handshake
)
362 DCHECK(handshake
->empty());
364 handshake
->push_back(kSOCKS5Version
);
365 handshake
->push_back(kTunnelCommand
); // Connect command
366 handshake
->push_back(kNullByte
); // Reserved null
368 handshake
->push_back(kEndPointDomain
); // The type of the address.
370 DCHECK_GE(static_cast<size_t>(0xFF), host_request_info_
.hostname().size());
372 // First add the size of the hostname, followed by the hostname.
373 handshake
->push_back(static_cast<unsigned char>(
374 host_request_info_
.hostname().size()));
375 handshake
->append(host_request_info_
.hostname());
377 uint16 nw_port
= base::HostToNet16(host_request_info_
.port());
378 handshake
->append(reinterpret_cast<char*>(&nw_port
), sizeof(nw_port
));
382 // Writes the SOCKS handshake data to the underlying socket connection.
383 int SOCKS5ClientSocket::DoHandshakeWrite() {
384 next_state_
= STATE_HANDSHAKE_WRITE_COMPLETE
;
386 if (buffer_
.empty()) {
387 int rv
= BuildHandshakeWriteBuffer(&buffer_
);
393 int handshake_buf_len
= buffer_
.size() - bytes_sent_
;
394 DCHECK_LT(0, handshake_buf_len
);
395 handshake_buf_
= new IOBuffer(handshake_buf_len
);
396 memcpy(handshake_buf_
->data(), &buffer_
[bytes_sent_
],
398 return transport_
->socket()
399 ->Write(handshake_buf_
.get(), handshake_buf_len
, io_callback_
);
402 int SOCKS5ClientSocket::DoHandshakeWriteComplete(int result
) {
406 // We ignore the case when result is 0, since the underlying Write
407 // may return spurious writes while waiting on the socket.
409 bytes_sent_
+= result
;
410 if (bytes_sent_
== buffer_
.size()) {
411 next_state_
= STATE_HANDSHAKE_READ
;
413 } else if (bytes_sent_
< buffer_
.size()) {
414 next_state_
= STATE_HANDSHAKE_WRITE
;
422 int SOCKS5ClientSocket::DoHandshakeRead() {
423 next_state_
= STATE_HANDSHAKE_READ_COMPLETE
;
425 if (buffer_
.empty()) {
427 read_header_size
= kReadHeaderSize
;
430 int handshake_buf_len
= read_header_size
- bytes_received_
;
431 handshake_buf_
= new IOBuffer(handshake_buf_len
);
432 return transport_
->socket()
433 ->Read(handshake_buf_
.get(), handshake_buf_len
, io_callback_
);
436 int SOCKS5ClientSocket::DoHandshakeReadComplete(int result
) {
440 // The underlying socket closed unexpectedly.
442 net_log_
.AddEvent(NetLog::TYPE_SOCKS_UNEXPECTEDLY_CLOSED_DURING_HANDSHAKE
);
443 return ERR_SOCKS_CONNECTION_FAILED
;
446 buffer_
.append(handshake_buf_
->data(), result
);
447 bytes_received_
+= result
;
449 // When the first few bytes are read, check how many more are required
450 // and accordingly increase them
451 if (bytes_received_
== kReadHeaderSize
) {
452 if (buffer_
[0] != kSOCKS5Version
|| buffer_
[2] != kNullByte
) {
453 net_log_
.AddEvent(NetLog::TYPE_SOCKS_UNEXPECTED_VERSION
,
454 NetLog::IntegerCallback("version", buffer_
[0]));
455 return ERR_SOCKS_CONNECTION_FAILED
;
457 if (buffer_
[1] != 0x00) {
458 net_log_
.AddEvent(NetLog::TYPE_SOCKS_SERVER_ERROR
,
459 NetLog::IntegerCallback("error_code", buffer_
[1]));
460 return ERR_SOCKS_CONNECTION_FAILED
;
463 // We check the type of IP/Domain the server returns and accordingly
464 // increase the size of the response. For domains, we need to read the
465 // size of the domain, so the initial request size is upto the domain
466 // size. Since for IPv4/IPv6 the size is fixed and hence no 'size' is
467 // read, we substract 1 byte from the additional request size.
468 SocksEndPointAddressType address_type
=
469 static_cast<SocksEndPointAddressType
>(buffer_
[3]);
470 if (address_type
== kEndPointDomain
)
471 read_header_size
+= static_cast<uint8
>(buffer_
[4]);
472 else if (address_type
== kEndPointResolvedIPv4
)
473 read_header_size
+= sizeof(struct in_addr
) - 1;
474 else if (address_type
== kEndPointResolvedIPv6
)
475 read_header_size
+= sizeof(struct in6_addr
) - 1;
477 net_log_
.AddEvent(NetLog::TYPE_SOCKS_UNKNOWN_ADDRESS_TYPE
,
478 NetLog::IntegerCallback("address_type", buffer_
[3]));
479 return ERR_SOCKS_CONNECTION_FAILED
;
482 read_header_size
+= 2; // for the port.
483 next_state_
= STATE_HANDSHAKE_READ
;
487 // When the final bytes are read, setup handshake. We ignore the rest
488 // of the response since they represent the SOCKSv5 endpoint and have
489 // no use when doing a tunnel connection.
490 if (bytes_received_
== read_header_size
) {
491 completed_handshake_
= true;
493 next_state_
= STATE_NONE
;
497 next_state_
= STATE_HANDSHAKE_READ
;
501 int SOCKS5ClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
502 return transport_
->socket()->GetPeerAddress(address
);
505 int SOCKS5ClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
506 return transport_
->socket()->GetLocalAddress(address
);