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/socks_client_socket.h"
7 #include "base/basictypes.h"
9 #include "base/callback_helpers.h"
10 #include "base/compiler_specific.h"
11 #include "base/sys_byteorder.h"
12 #include "net/base/io_buffer.h"
13 #include "net/base/net_util.h"
14 #include "net/log/net_log.h"
15 #include "net/socket/client_socket_handle.h"
19 // Every SOCKS server requests a user-id from the client. It is optional
20 // and we send an empty string.
21 static const char kEmptyUserId
[] = "";
23 // For SOCKS4, the client sends 8 bytes plus the size of the user-id.
24 static const unsigned int kWriteHeaderSize
= 8;
26 // For SOCKS4 the server sends 8 bytes for acknowledgement.
27 static const unsigned int kReadHeaderSize
= 8;
29 // Server Response codes for SOCKS.
30 static const uint8 kServerResponseOk
= 0x5A;
31 static const uint8 kServerResponseRejected
= 0x5B;
32 static const uint8 kServerResponseNotReachable
= 0x5C;
33 static const uint8 kServerResponseMismatchedUserId
= 0x5D;
35 static const uint8 kSOCKSVersion4
= 0x04;
36 static const uint8 kSOCKSStreamRequest
= 0x01;
38 // A struct holding the essential details of the SOCKS4 Server Request.
39 // The port in the header is stored in network byte order.
40 struct SOCKS4ServerRequest
{
46 static_assert(sizeof(SOCKS4ServerRequest
) == kWriteHeaderSize
,
47 "socks4 server request struct has incorrect size");
49 // A struct holding details of the SOCKS4 Server Response.
50 struct SOCKS4ServerResponse
{
56 static_assert(sizeof(SOCKS4ServerResponse
) == kReadHeaderSize
,
57 "socks4 server response struct has incorrect size");
59 SOCKSClientSocket::SOCKSClientSocket(
60 scoped_ptr
<ClientSocketHandle
> transport_socket
,
61 const HostResolver::RequestInfo
& req_info
,
62 RequestPriority priority
,
63 HostResolver
* host_resolver
)
64 : transport_(transport_socket
.Pass()),
65 next_state_(STATE_NONE
),
66 completed_handshake_(false),
69 was_ever_used_(false),
70 host_resolver_(host_resolver
),
71 host_request_info_(req_info
),
73 net_log_(transport_
->socket()->NetLog()) {}
75 SOCKSClientSocket::~SOCKSClientSocket() {
79 int SOCKSClientSocket::Connect(const CompletionCallback
& callback
) {
80 DCHECK(transport_
.get());
81 DCHECK(transport_
->socket());
82 DCHECK_EQ(STATE_NONE
, next_state_
);
83 DCHECK(user_callback_
.is_null());
85 // If already connected, then just return OK.
86 if (completed_handshake_
)
89 next_state_
= STATE_RESOLVE_HOST
;
91 net_log_
.BeginEvent(NetLog::TYPE_SOCKS_CONNECT
);
94 if (rv
== ERR_IO_PENDING
) {
95 user_callback_
= callback
;
97 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SOCKS_CONNECT
, rv
);
102 void SOCKSClientSocket::Disconnect() {
103 completed_handshake_
= false;
104 host_resolver_
.Cancel();
105 transport_
->socket()->Disconnect();
107 // Reset other states to make sure they aren't mistakenly used later.
108 // These are the states initialized by Connect().
109 next_state_
= STATE_NONE
;
110 user_callback_
.Reset();
113 bool SOCKSClientSocket::IsConnected() const {
114 return completed_handshake_
&& transport_
->socket()->IsConnected();
117 bool SOCKSClientSocket::IsConnectedAndIdle() const {
118 return completed_handshake_
&& transport_
->socket()->IsConnectedAndIdle();
121 const BoundNetLog
& SOCKSClientSocket::NetLog() const {
125 void SOCKSClientSocket::SetSubresourceSpeculation() {
126 if (transport_
.get() && transport_
->socket()) {
127 transport_
->socket()->SetSubresourceSpeculation();
133 void SOCKSClientSocket::SetOmniboxSpeculation() {
134 if (transport_
.get() && transport_
->socket()) {
135 transport_
->socket()->SetOmniboxSpeculation();
141 bool SOCKSClientSocket::WasEverUsed() const {
142 return was_ever_used_
;
145 bool SOCKSClientSocket::UsingTCPFastOpen() const {
146 if (transport_
.get() && transport_
->socket()) {
147 return transport_
->socket()->UsingTCPFastOpen();
153 bool SOCKSClientSocket::WasNpnNegotiated() const {
154 if (transport_
.get() && transport_
->socket()) {
155 return transport_
->socket()->WasNpnNegotiated();
161 NextProto
SOCKSClientSocket::GetNegotiatedProtocol() const {
162 if (transport_
.get() && transport_
->socket()) {
163 return transport_
->socket()->GetNegotiatedProtocol();
166 return kProtoUnknown
;
169 bool SOCKSClientSocket::GetSSLInfo(SSLInfo
* ssl_info
) {
170 if (transport_
.get() && transport_
->socket()) {
171 return transport_
->socket()->GetSSLInfo(ssl_info
);
177 void SOCKSClientSocket::GetConnectionAttempts(ConnectionAttempts
* out
) const {
181 // Read is called by the transport layer above to read. This can only be done
182 // if the SOCKS handshake is complete.
183 int SOCKSClientSocket::Read(IOBuffer
* buf
, int buf_len
,
184 const CompletionCallback
& callback
) {
185 DCHECK(completed_handshake_
);
186 DCHECK_EQ(STATE_NONE
, next_state_
);
187 DCHECK(user_callback_
.is_null());
188 DCHECK(!callback
.is_null());
190 int rv
= transport_
->socket()->Read(
192 base::Bind(&SOCKSClientSocket::OnReadWriteComplete
,
193 base::Unretained(this), callback
));
195 was_ever_used_
= true;
199 // Write is called by the transport layer. This can only be done if the
200 // SOCKS handshake is complete.
201 int SOCKSClientSocket::Write(IOBuffer
* buf
, int buf_len
,
202 const CompletionCallback
& callback
) {
203 DCHECK(completed_handshake_
);
204 DCHECK_EQ(STATE_NONE
, next_state_
);
205 DCHECK(user_callback_
.is_null());
206 DCHECK(!callback
.is_null());
208 int rv
= transport_
->socket()->Write(
210 base::Bind(&SOCKSClientSocket::OnReadWriteComplete
,
211 base::Unretained(this), callback
));
213 was_ever_used_
= true;
217 int SOCKSClientSocket::SetReceiveBufferSize(int32 size
) {
218 return transport_
->socket()->SetReceiveBufferSize(size
);
221 int SOCKSClientSocket::SetSendBufferSize(int32 size
) {
222 return transport_
->socket()->SetSendBufferSize(size
);
225 void SOCKSClientSocket::DoCallback(int result
) {
226 DCHECK_NE(ERR_IO_PENDING
, result
);
227 DCHECK(!user_callback_
.is_null());
229 // Since Run() may result in Read being called,
230 // clear user_callback_ up front.
231 DVLOG(1) << "Finished setting up SOCKS handshake";
232 base::ResetAndReturn(&user_callback_
).Run(result
);
235 void SOCKSClientSocket::OnIOComplete(int result
) {
236 DCHECK_NE(STATE_NONE
, next_state_
);
237 int rv
= DoLoop(result
);
238 if (rv
!= ERR_IO_PENDING
) {
239 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SOCKS_CONNECT
, rv
);
244 void SOCKSClientSocket::OnReadWriteComplete(const CompletionCallback
& callback
,
246 DCHECK_NE(ERR_IO_PENDING
, result
);
247 DCHECK(!callback
.is_null());
250 was_ever_used_
= true;
251 callback
.Run(result
);
254 int SOCKSClientSocket::DoLoop(int last_io_result
) {
255 DCHECK_NE(next_state_
, STATE_NONE
);
256 int rv
= last_io_result
;
258 State state
= next_state_
;
259 next_state_
= STATE_NONE
;
261 case STATE_RESOLVE_HOST
:
263 rv
= DoResolveHost();
265 case STATE_RESOLVE_HOST_COMPLETE
:
266 rv
= DoResolveHostComplete(rv
);
268 case STATE_HANDSHAKE_WRITE
:
270 rv
= DoHandshakeWrite();
272 case STATE_HANDSHAKE_WRITE_COMPLETE
:
273 rv
= DoHandshakeWriteComplete(rv
);
275 case STATE_HANDSHAKE_READ
:
277 rv
= DoHandshakeRead();
279 case STATE_HANDSHAKE_READ_COMPLETE
:
280 rv
= DoHandshakeReadComplete(rv
);
283 NOTREACHED() << "bad state";
287 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
291 int SOCKSClientSocket::DoResolveHost() {
292 next_state_
= STATE_RESOLVE_HOST_COMPLETE
;
293 // SOCKS4 only supports IPv4 addresses, so only try getting the IPv4
294 // addresses for the target host.
295 host_request_info_
.set_address_family(ADDRESS_FAMILY_IPV4
);
296 return host_resolver_
.Resolve(
300 base::Bind(&SOCKSClientSocket::OnIOComplete
, base::Unretained(this)),
304 int SOCKSClientSocket::DoResolveHostComplete(int result
) {
306 // Resolving the hostname failed; fail the request rather than automatically
307 // falling back to SOCKS4a (since it can be confusing to see invalid IP
308 // addresses being sent to the SOCKS4 server when it doesn't support 4A.)
312 next_state_
= STATE_HANDSHAKE_WRITE
;
316 // Builds the buffer that is to be sent to the server.
317 const std::string
SOCKSClientSocket::BuildHandshakeWriteBuffer() const {
318 SOCKS4ServerRequest request
;
319 request
.version
= kSOCKSVersion4
;
320 request
.command
= kSOCKSStreamRequest
;
321 request
.nw_port
= base::HostToNet16(host_request_info_
.port());
323 DCHECK(!addresses_
.empty());
324 const IPEndPoint
& endpoint
= addresses_
.front();
326 // We disabled IPv6 results when resolving the hostname, so none of the
327 // results in the list will be IPv6.
328 // TODO(eroman): we only ever use the first address in the list. It would be
329 // more robust to try all the IP addresses we have before
330 // failing the connect attempt.
331 CHECK_EQ(ADDRESS_FAMILY_IPV4
, endpoint
.GetFamily());
332 CHECK_LE(endpoint
.address().size(), sizeof(request
.ip
));
333 memcpy(&request
.ip
, &endpoint
.address()[0], endpoint
.address().size());
335 DVLOG(1) << "Resolved Host is : " << endpoint
.ToStringWithoutPort();
337 std::string
handshake_data(reinterpret_cast<char*>(&request
),
339 handshake_data
.append(kEmptyUserId
, arraysize(kEmptyUserId
));
341 return handshake_data
;
344 // Writes the SOCKS handshake data to the underlying socket connection.
345 int SOCKSClientSocket::DoHandshakeWrite() {
346 next_state_
= STATE_HANDSHAKE_WRITE_COMPLETE
;
348 if (buffer_
.empty()) {
349 buffer_
= BuildHandshakeWriteBuffer();
353 int handshake_buf_len
= buffer_
.size() - bytes_sent_
;
354 DCHECK_GT(handshake_buf_len
, 0);
355 handshake_buf_
= new IOBuffer(handshake_buf_len
);
356 memcpy(handshake_buf_
->data(), &buffer_
[bytes_sent_
],
358 return transport_
->socket()->Write(
359 handshake_buf_
.get(),
361 base::Bind(&SOCKSClientSocket::OnIOComplete
, base::Unretained(this)));
364 int SOCKSClientSocket::DoHandshakeWriteComplete(int result
) {
368 // We ignore the case when result is 0, since the underlying Write
369 // may return spurious writes while waiting on the socket.
371 bytes_sent_
+= result
;
372 if (bytes_sent_
== buffer_
.size()) {
373 next_state_
= STATE_HANDSHAKE_READ
;
375 } else if (bytes_sent_
< buffer_
.size()) {
376 next_state_
= STATE_HANDSHAKE_WRITE
;
378 return ERR_UNEXPECTED
;
384 int SOCKSClientSocket::DoHandshakeRead() {
385 next_state_
= STATE_HANDSHAKE_READ_COMPLETE
;
387 if (buffer_
.empty()) {
391 int handshake_buf_len
= kReadHeaderSize
- bytes_received_
;
392 handshake_buf_
= new IOBuffer(handshake_buf_len
);
393 return transport_
->socket()->Read(
394 handshake_buf_
.get(),
396 base::Bind(&SOCKSClientSocket::OnIOComplete
, base::Unretained(this)));
399 int SOCKSClientSocket::DoHandshakeReadComplete(int result
) {
403 // The underlying socket closed unexpectedly.
405 return ERR_CONNECTION_CLOSED
;
407 if (bytes_received_
+ result
> kReadHeaderSize
) {
408 // TODO(eroman): Describe failure in NetLog.
409 return ERR_SOCKS_CONNECTION_FAILED
;
412 buffer_
.append(handshake_buf_
->data(), result
);
413 bytes_received_
+= result
;
414 if (bytes_received_
< kReadHeaderSize
) {
415 next_state_
= STATE_HANDSHAKE_READ
;
419 const SOCKS4ServerResponse
* response
=
420 reinterpret_cast<const SOCKS4ServerResponse
*>(buffer_
.data());
422 if (response
->reserved_null
!= 0x00) {
423 LOG(ERROR
) << "Unknown response from SOCKS server.";
424 return ERR_SOCKS_CONNECTION_FAILED
;
427 switch (response
->code
) {
428 case kServerResponseOk
:
429 completed_handshake_
= true;
431 case kServerResponseRejected
:
432 LOG(ERROR
) << "SOCKS request rejected or failed";
433 return ERR_SOCKS_CONNECTION_FAILED
;
434 case kServerResponseNotReachable
:
435 LOG(ERROR
) << "SOCKS request failed because client is not running "
436 << "identd (or not reachable from the server)";
437 return ERR_SOCKS_CONNECTION_HOST_UNREACHABLE
;
438 case kServerResponseMismatchedUserId
:
439 LOG(ERROR
) << "SOCKS request failed because client's identd could "
440 << "not confirm the user ID string in the request";
441 return ERR_SOCKS_CONNECTION_FAILED
;
443 LOG(ERROR
) << "SOCKS server sent unknown response";
444 return ERR_SOCKS_CONNECTION_FAILED
;
447 // Note: we ignore the last 6 bytes as specified by the SOCKS protocol
450 int SOCKSClientSocket::GetPeerAddress(IPEndPoint
* address
) const {
451 return transport_
->socket()->GetPeerAddress(address
);
454 int SOCKSClientSocket::GetLocalAddress(IPEndPoint
* address
) const {
455 return transport_
->socket()->GetLocalAddress(address
);