blob: a4a73910737f2401b36ae8ccd32c5e4edfcc9cb5 [file] [log] [blame]
[email protected]a2006ece2010-04-23 16:44:021// Copyright (c) 2010 The Chromium Authors. All rights reserved.
[email protected]3cd17242009-06-23 02:59:022// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/socket/socks_client_socket.h"
6
7#include "base/basictypes.h"
[email protected]3cd17242009-06-23 02:59:028#include "base/compiler_specific.h"
[email protected]3cd17242009-06-23 02:59:029#include "net/base/io_buffer.h"
[email protected]9e743cd2010-03-16 07:03:5310#include "net/base/net_log.h"
[email protected]3cd17242009-06-23 02:59:0211#include "net/base/net_util.h"
[email protected]a540c2d2009-12-12 00:47:3712#include "net/base/sys_addrinfo.h"
[email protected]a796bcec2010-03-22 17:17:2613#include "net/socket/client_socket_handle.h"
[email protected]3cd17242009-06-23 02:59:0214
15namespace net {
16
17// Every SOCKS server requests a user-id from the client. It is optional
18// and we send an empty string.
19static const char kEmptyUserId[] = "";
20
21// The SOCKS4a implementation suggests to use an invalid IP in case the DNS
22// resolution at client fails.
23static const uint8 kInvalidIp[] = { 0, 0, 0, 127 };
24
25// For SOCKS4, the client sends 8 bytes plus the size of the user-id.
26// For SOCKS4A, this increases to accomodate the unresolved hostname.
[email protected]76a51ac82009-06-28 07:58:5827static const unsigned int kWriteHeaderSize = 8;
[email protected]3cd17242009-06-23 02:59:0228
29// For SOCKS4 and SOCKS4a, the server sends 8 bytes for acknowledgement.
[email protected]76a51ac82009-06-28 07:58:5830static const unsigned int kReadHeaderSize = 8;
[email protected]3cd17242009-06-23 02:59:0231
32// Server Response codes for SOCKS.
33static const uint8 kServerResponseOk = 0x5A;
34static const uint8 kServerResponseRejected = 0x5B;
35static const uint8 kServerResponseNotReachable = 0x5C;
36static const uint8 kServerResponseMismatchedUserId = 0x5D;
37
38static const uint8 kSOCKSVersion4 = 0x04;
39static const uint8 kSOCKSStreamRequest = 0x01;
40
41// A struct holding the essential details of the SOCKS4/4a Server Request.
42// The port in the header is stored in network byte order.
43struct SOCKS4ServerRequest {
44 uint8 version;
45 uint8 command;
46 uint16 nw_port;
47 uint8 ip[4];
48};
49COMPILE_ASSERT(sizeof(SOCKS4ServerRequest) == kWriteHeaderSize,
50 socks4_server_request_struct_wrong_size);
51
52// A struct holding details of the SOCKS4/4a Server Response.
53struct SOCKS4ServerResponse {
54 uint8 reserved_null;
55 uint8 code;
56 uint16 port;
57 uint8 ip[4];
58};
59COMPILE_ASSERT(sizeof(SOCKS4ServerResponse) == kReadHeaderSize,
60 socks4_server_response_struct_wrong_size);
61
[email protected]a796bcec2010-03-22 17:17:2662SOCKSClientSocket::SOCKSClientSocket(ClientSocketHandle* transport_socket,
[email protected]3cd17242009-06-23 02:59:0263 const HostResolver::RequestInfo& req_info,
64 HostResolver* host_resolver)
65 : ALLOW_THIS_IN_INITIALIZER_LIST(
66 io_callback_(this, &SOCKSClientSocket::OnIOComplete)),
67 transport_(transport_socket),
68 next_state_(STATE_NONE),
69 socks_version_(kSOCKS4Unresolved),
70 user_callback_(NULL),
[email protected]3cd17242009-06-23 02:59:0271 completed_handshake_(false),
72 bytes_sent_(0),
73 bytes_received_(0),
[email protected]76a51ac82009-06-28 07:58:5874 host_resolver_(host_resolver),
[email protected]a2006ece2010-04-23 16:44:0275 host_request_info_(req_info),
76 net_log_(transport_socket->socket()->NetLog()) {
[email protected]3cd17242009-06-23 02:59:0277}
78
[email protected]a796bcec2010-03-22 17:17:2679SOCKSClientSocket::SOCKSClientSocket(ClientSocket* transport_socket,
80 const HostResolver::RequestInfo& req_info,
81 HostResolver* host_resolver)
82 : ALLOW_THIS_IN_INITIALIZER_LIST(
83 io_callback_(this, &SOCKSClientSocket::OnIOComplete)),
84 transport_(new ClientSocketHandle()),
85 next_state_(STATE_NONE),
86 socks_version_(kSOCKS4Unresolved),
87 user_callback_(NULL),
88 completed_handshake_(false),
89 bytes_sent_(0),
90 bytes_received_(0),
91 host_resolver_(host_resolver),
[email protected]a2006ece2010-04-23 16:44:0292 host_request_info_(req_info),
93 net_log_(transport_socket->NetLog()) {
[email protected]a796bcec2010-03-22 17:17:2694 transport_->set_socket(transport_socket);
95}
96
[email protected]3cd17242009-06-23 02:59:0297SOCKSClientSocket::~SOCKSClientSocket() {
98 Disconnect();
99}
100
[email protected]a2006ece2010-04-23 16:44:02101int SOCKSClientSocket::Connect(CompletionCallback* callback) {
[email protected]3cd17242009-06-23 02:59:02102 DCHECK(transport_.get());
[email protected]a796bcec2010-03-22 17:17:26103 DCHECK(transport_->socket());
[email protected]3cd17242009-06-23 02:59:02104 DCHECK_EQ(STATE_NONE, next_state_);
105 DCHECK(!user_callback_);
106
107 // If already connected, then just return OK.
108 if (completed_handshake_)
109 return OK;
110
111 next_state_ = STATE_RESOLVE_HOST;
[email protected]5a05c47a2009-11-02 23:25:19112
[email protected]ec11be62010-04-28 19:28:09113 net_log_.BeginEvent(NetLog::TYPE_SOCKS_CONNECT, NULL);
[email protected]3cd17242009-06-23 02:59:02114
115 int rv = DoLoop(OK);
[email protected]5a05c47a2009-11-02 23:25:19116 if (rv == ERR_IO_PENDING) {
[email protected]3cd17242009-06-23 02:59:02117 user_callback_ = callback;
[email protected]5a05c47a2009-11-02 23:25:19118 } else {
[email protected]ec11be62010-04-28 19:28:09119 net_log_.EndEvent(NetLog::TYPE_SOCKS_CONNECT, NULL);
[email protected]5a05c47a2009-11-02 23:25:19120 }
[email protected]3cd17242009-06-23 02:59:02121 return rv;
122}
123
124void SOCKSClientSocket::Disconnect() {
125 completed_handshake_ = false;
[email protected]16a02742010-01-07 22:50:10126 host_resolver_.Cancel();
[email protected]a796bcec2010-03-22 17:17:26127 transport_->socket()->Disconnect();
[email protected]16a02742010-01-07 22:50:10128
129 // Reset other states to make sure they aren't mistakenly used later.
130 // These are the states initialized by Connect().
131 next_state_ = STATE_NONE;
132 user_callback_ = NULL;
[email protected]3cd17242009-06-23 02:59:02133}
134
135bool SOCKSClientSocket::IsConnected() const {
[email protected]a796bcec2010-03-22 17:17:26136 return completed_handshake_ && transport_->socket()->IsConnected();
[email protected]3cd17242009-06-23 02:59:02137}
138
139bool SOCKSClientSocket::IsConnectedAndIdle() const {
[email protected]a796bcec2010-03-22 17:17:26140 return completed_handshake_ && transport_->socket()->IsConnectedAndIdle();
[email protected]3cd17242009-06-23 02:59:02141}
142
[email protected]9b5614a2010-08-25 20:29:45143void SOCKSClientSocket::SetSubresourceSpeculation() {
144 if (transport_.get() && transport_->socket()) {
145 transport_->socket()->SetSubresourceSpeculation();
146 } else {
147 NOTREACHED();
148 }
149}
150
151void SOCKSClientSocket::SetOmniboxSpeculation() {
152 if (transport_.get() && transport_->socket()) {
153 transport_->socket()->SetOmniboxSpeculation();
154 } else {
155 NOTREACHED();
156 }
157}
158
[email protected]0f873e82010-09-02 16:09:01159bool SOCKSClientSocket::WasEverUsed() const {
160 if (transport_.get() && transport_->socket()) {
161 return transport_->socket()->WasEverUsed();
162 }
163 NOTREACHED();
164 return false;
165}
166
[email protected]7f7e92392010-10-26 18:29:29167bool SOCKSClientSocket::UsingTCPFastOpen() const {
168 if (transport_.get() && transport_->socket()) {
169 return transport_->socket()->UsingTCPFastOpen();
170 }
171 NOTREACHED();
172 return false;
173}
174
175
[email protected]3cd17242009-06-23 02:59:02176// Read is called by the transport layer above to read. This can only be done
177// if the SOCKS handshake is complete.
178int SOCKSClientSocket::Read(IOBuffer* buf, int buf_len,
179 CompletionCallback* callback) {
180 DCHECK(completed_handshake_);
181 DCHECK_EQ(STATE_NONE, next_state_);
182 DCHECK(!user_callback_);
183
[email protected]a796bcec2010-03-22 17:17:26184 return transport_->socket()->Read(buf, buf_len, callback);
[email protected]3cd17242009-06-23 02:59:02185}
186
187// Write is called by the transport layer. This can only be done if the
188// SOCKS handshake is complete.
189int SOCKSClientSocket::Write(IOBuffer* buf, int buf_len,
190 CompletionCallback* callback) {
191 DCHECK(completed_handshake_);
192 DCHECK_EQ(STATE_NONE, next_state_);
193 DCHECK(!user_callback_);
194
[email protected]a796bcec2010-03-22 17:17:26195 return transport_->socket()->Write(buf, buf_len, callback);
[email protected]3cd17242009-06-23 02:59:02196}
197
[email protected]d3f66572009-09-09 22:38:04198bool SOCKSClientSocket::SetReceiveBufferSize(int32 size) {
[email protected]a796bcec2010-03-22 17:17:26199 return transport_->socket()->SetReceiveBufferSize(size);
[email protected]d3f66572009-09-09 22:38:04200}
201
202bool SOCKSClientSocket::SetSendBufferSize(int32 size) {
[email protected]a796bcec2010-03-22 17:17:26203 return transport_->socket()->SetSendBufferSize(size);
[email protected]d3f66572009-09-09 22:38:04204}
205
[email protected]3cd17242009-06-23 02:59:02206void SOCKSClientSocket::DoCallback(int result) {
207 DCHECK_NE(ERR_IO_PENDING, result);
208 DCHECK(user_callback_);
209
210 // Since Run() may result in Read being called,
211 // clear user_callback_ up front.
212 CompletionCallback* c = user_callback_;
213 user_callback_ = NULL;
[email protected]b30a3f52010-10-16 01:05:46214 DVLOG(1) << "Finished setting up SOCKS handshake";
[email protected]3cd17242009-06-23 02:59:02215 c->Run(result);
216}
217
218void SOCKSClientSocket::OnIOComplete(int result) {
219 DCHECK_NE(STATE_NONE, next_state_);
220 int rv = DoLoop(result);
[email protected]5a05c47a2009-11-02 23:25:19221 if (rv != ERR_IO_PENDING) {
[email protected]ec11be62010-04-28 19:28:09222 net_log_.EndEvent(NetLog::TYPE_SOCKS_CONNECT, NULL);
[email protected]3cd17242009-06-23 02:59:02223 DoCallback(rv);
[email protected]5a05c47a2009-11-02 23:25:19224 }
[email protected]3cd17242009-06-23 02:59:02225}
226
227int SOCKSClientSocket::DoLoop(int last_io_result) {
228 DCHECK_NE(next_state_, STATE_NONE);
229 int rv = last_io_result;
230 do {
231 State state = next_state_;
232 next_state_ = STATE_NONE;
233 switch (state) {
234 case STATE_RESOLVE_HOST:
235 DCHECK_EQ(OK, rv);
236 rv = DoResolveHost();
237 break;
238 case STATE_RESOLVE_HOST_COMPLETE:
239 rv = DoResolveHostComplete(rv);
240 break;
241 case STATE_HANDSHAKE_WRITE:
242 DCHECK_EQ(OK, rv);
243 rv = DoHandshakeWrite();
244 break;
245 case STATE_HANDSHAKE_WRITE_COMPLETE:
246 rv = DoHandshakeWriteComplete(rv);
247 break;
248 case STATE_HANDSHAKE_READ:
249 DCHECK_EQ(OK, rv);
250 rv = DoHandshakeRead();
251 break;
252 case STATE_HANDSHAKE_READ_COMPLETE:
253 rv = DoHandshakeReadComplete(rv);
254 break;
255 default:
256 NOTREACHED() << "bad state";
257 rv = ERR_UNEXPECTED;
258 break;
259 }
260 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
261 return rv;
262}
263
264int SOCKSClientSocket::DoResolveHost() {
265 DCHECK_EQ(kSOCKS4Unresolved, socks_version_);
266
267 next_state_ = STATE_RESOLVE_HOST_COMPLETE;
[email protected]ec08bb22009-08-12 00:25:12268 return host_resolver_.Resolve(
[email protected]9e743cd2010-03-16 07:03:53269 host_request_info_, &addresses_, &io_callback_, net_log_);
[email protected]3cd17242009-06-23 02:59:02270}
271
272int SOCKSClientSocket::DoResolveHostComplete(int result) {
273 DCHECK_EQ(kSOCKS4Unresolved, socks_version_);
274
275 bool ok = (result == OK);
276 next_state_ = STATE_HANDSHAKE_WRITE;
277 if (ok) {
278 DCHECK(addresses_.head());
279
280 // If the host is resolved to an IPv6 address, we revert to SOCKS4a
281 // since IPv6 is unsupported by SOCKS4/4a protocol.
282 struct sockaddr *host_info = addresses_.head()->ai_addr;
283 if (host_info->sa_family == AF_INET) {
[email protected]b30a3f52010-10-16 01:05:46284 DVLOG(1) << "Resolved host. Using SOCKS4 to communicate";
[email protected]3cd17242009-06-23 02:59:02285 socks_version_ = kSOCKS4;
286 } else {
[email protected]b30a3f52010-10-16 01:05:46287 DVLOG(1) << "Resolved host but to IPv6. Using SOCKS4a to communicate";
[email protected]3cd17242009-06-23 02:59:02288 socks_version_ = kSOCKS4a;
289 }
290 } else {
[email protected]b30a3f52010-10-16 01:05:46291 DVLOG(1) << "Could not resolve host. Using SOCKS4a to communicate";
[email protected]3cd17242009-06-23 02:59:02292 socks_version_ = kSOCKS4a;
293 }
294
295 // Even if DNS resolution fails, we send OK since the server
296 // resolves the domain.
297 return OK;
298}
299
300// Builds the buffer that is to be sent to the server.
301// We check whether the SOCKS proxy is 4 or 4A.
302// In case it is 4A, the record size increases by size of the hostname.
[email protected]76a51ac82009-06-28 07:58:58303const std::string SOCKSClientSocket::BuildHandshakeWriteBuffer() const {
[email protected]3cd17242009-06-23 02:59:02304 DCHECK_NE(kSOCKS4Unresolved, socks_version_);
305
[email protected]76a51ac82009-06-28 07:58:58306 SOCKS4ServerRequest request;
307 request.version = kSOCKSVersion4;
308 request.command = kSOCKSStreamRequest;
309 request.nw_port = htons(host_request_info_.port());
[email protected]3cd17242009-06-23 02:59:02310
311 if (socks_version_ == kSOCKS4) {
312 const struct addrinfo* ai = addresses_.head();
313 DCHECK(ai);
314 // If the sockaddr is IPv6, we have already marked the version to socks4a
315 // and so this step does not get hit.
[email protected]76a51ac82009-06-28 07:58:58316 struct sockaddr_in* ipv4_host =
[email protected]3cd17242009-06-23 02:59:02317 reinterpret_cast<struct sockaddr_in*>(ai->ai_addr);
[email protected]76a51ac82009-06-28 07:58:58318 memcpy(&request.ip, &(ipv4_host->sin_addr), sizeof(ipv4_host->sin_addr));
[email protected]3cd17242009-06-23 02:59:02319
[email protected]b30a3f52010-10-16 01:05:46320 DVLOG(1) << "Resolved Host is : " << NetAddressToString(ai);
[email protected]3cd17242009-06-23 02:59:02321 } else if (socks_version_ == kSOCKS4a) {
322 // invalid IP of the form 0.0.0.127
[email protected]76a51ac82009-06-28 07:58:58323 memcpy(&request.ip, kInvalidIp, arraysize(kInvalidIp));
[email protected]3cd17242009-06-23 02:59:02324 } else {
325 NOTREACHED();
326 }
327
[email protected]76a51ac82009-06-28 07:58:58328 std::string handshake_data(reinterpret_cast<char*>(&request),
329 sizeof(request));
330 handshake_data.append(kEmptyUserId, arraysize(kEmptyUserId));
[email protected]3cd17242009-06-23 02:59:02331
[email protected]76a51ac82009-06-28 07:58:58332 // In case we are passing the domain also, pass the hostname
333 // terminated with a null character.
[email protected]3cd17242009-06-23 02:59:02334 if (socks_version_ == kSOCKS4a) {
[email protected]76a51ac82009-06-28 07:58:58335 handshake_data.append(host_request_info_.hostname());
336 handshake_data.push_back('\0');
[email protected]3cd17242009-06-23 02:59:02337 }
[email protected]76a51ac82009-06-28 07:58:58338
339 return handshake_data;
[email protected]3cd17242009-06-23 02:59:02340}
341
342// Writes the SOCKS handshake data to the underlying socket connection.
343int SOCKSClientSocket::DoHandshakeWrite() {
344 next_state_ = STATE_HANDSHAKE_WRITE_COMPLETE;
345
[email protected]76a51ac82009-06-28 07:58:58346 if (buffer_.empty()) {
347 buffer_ = BuildHandshakeWriteBuffer();
[email protected]3cd17242009-06-23 02:59:02348 bytes_sent_ = 0;
349 }
350
[email protected]76a51ac82009-06-28 07:58:58351 int handshake_buf_len = buffer_.size() - bytes_sent_;
352 DCHECK_GT(handshake_buf_len, 0);
353 handshake_buf_ = new IOBuffer(handshake_buf_len);
354 memcpy(handshake_buf_->data(), &buffer_[bytes_sent_],
355 handshake_buf_len);
[email protected]a796bcec2010-03-22 17:17:26356 return transport_->socket()->Write(handshake_buf_, handshake_buf_len,
357 &io_callback_);
[email protected]3cd17242009-06-23 02:59:02358}
359
360int SOCKSClientSocket::DoHandshakeWriteComplete(int result) {
361 DCHECK_NE(kSOCKS4Unresolved, socks_version_);
362
363 if (result < 0)
364 return result;
365
[email protected]76a51ac82009-06-28 07:58:58366 // We ignore the case when result is 0, since the underlying Write
367 // may return spurious writes while waiting on the socket.
368
[email protected]3cd17242009-06-23 02:59:02369 bytes_sent_ += result;
[email protected]76a51ac82009-06-28 07:58:58370 if (bytes_sent_ == buffer_.size()) {
[email protected]3cd17242009-06-23 02:59:02371 next_state_ = STATE_HANDSHAKE_READ;
[email protected]76a51ac82009-06-28 07:58:58372 buffer_.clear();
373 } else if (bytes_sent_ < buffer_.size()) {
[email protected]3cd17242009-06-23 02:59:02374 next_state_ = STATE_HANDSHAKE_WRITE;
375 } else {
376 return ERR_UNEXPECTED;
377 }
378
379 return OK;
380}
381
382int SOCKSClientSocket::DoHandshakeRead() {
383 DCHECK_NE(kSOCKS4Unresolved, socks_version_);
384
385 next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
386
[email protected]76a51ac82009-06-28 07:58:58387 if (buffer_.empty()) {
[email protected]3cd17242009-06-23 02:59:02388 bytes_received_ = 0;
389 }
390
[email protected]76a51ac82009-06-28 07:58:58391 int handshake_buf_len = kReadHeaderSize - bytes_received_;
392 handshake_buf_ = new IOBuffer(handshake_buf_len);
[email protected]a796bcec2010-03-22 17:17:26393 return transport_->socket()->Read(handshake_buf_, handshake_buf_len,
394 &io_callback_);
[email protected]3cd17242009-06-23 02:59:02395}
396
397int SOCKSClientSocket::DoHandshakeReadComplete(int result) {
398 DCHECK_NE(kSOCKS4Unresolved, socks_version_);
399
400 if (result < 0)
401 return result;
[email protected]76a51ac82009-06-28 07:58:58402
403 // The underlying socket closed unexpectedly.
404 if (result == 0)
405 return ERR_CONNECTION_CLOSED;
406
[email protected]d5a309592010-02-05 02:22:52407 if (bytes_received_ + result > kReadHeaderSize) {
[email protected]9e743cd2010-03-16 07:03:53408 // TODO(eroman): Describe failure in NetLog.
[email protected]d5a309592010-02-05 02:22:52409 return ERR_SOCKS_CONNECTION_FAILED;
410 }
[email protected]3cd17242009-06-23 02:59:02411
[email protected]76a51ac82009-06-28 07:58:58412 buffer_.append(handshake_buf_->data(), result);
[email protected]3cd17242009-06-23 02:59:02413 bytes_received_ += result;
[email protected]76a51ac82009-06-28 07:58:58414 if (bytes_received_ < kReadHeaderSize) {
[email protected]3cd17242009-06-23 02:59:02415 next_state_ = STATE_HANDSHAKE_READ;
416 return OK;
417 }
418
[email protected]76a51ac82009-06-28 07:58:58419 const SOCKS4ServerResponse* response =
420 reinterpret_cast<const SOCKS4ServerResponse*>(buffer_.data());
[email protected]3cd17242009-06-23 02:59:02421
422 if (response->reserved_null != 0x00) {
423 LOG(ERROR) << "Unknown response from SOCKS server.";
[email protected]d5a309592010-02-05 02:22:52424 return ERR_SOCKS_CONNECTION_FAILED;
[email protected]3cd17242009-06-23 02:59:02425 }
426
[email protected]3cd17242009-06-23 02:59:02427 switch (response->code) {
428 case kServerResponseOk:
429 completed_handshake_ = true;
430 return OK;
431 case kServerResponseRejected:
432 LOG(ERROR) << "SOCKS request rejected or failed";
[email protected]d5a309592010-02-05 02:22:52433 return ERR_SOCKS_CONNECTION_FAILED;
[email protected]3cd17242009-06-23 02:59:02434 case kServerResponseNotReachable:
435 LOG(ERROR) << "SOCKS request failed because client is not running "
436 << "identd (or not reachable from the server)";
[email protected]d5a309592010-02-05 02:22:52437 return ERR_SOCKS_CONNECTION_HOST_UNREACHABLE;
[email protected]3cd17242009-06-23 02:59:02438 case kServerResponseMismatchedUserId:
439 LOG(ERROR) << "SOCKS request failed because client's identd could "
440 << "not confirm the user ID string in the request";
[email protected]d5a309592010-02-05 02:22:52441 return ERR_SOCKS_CONNECTION_FAILED;
[email protected]3cd17242009-06-23 02:59:02442 default:
443 LOG(ERROR) << "SOCKS server sent unknown response";
[email protected]d5a309592010-02-05 02:22:52444 return ERR_SOCKS_CONNECTION_FAILED;
[email protected]3cd17242009-06-23 02:59:02445 }
446
447 // Note: we ignore the last 6 bytes as specified by the SOCKS protocol
448}
449
[email protected]ac9eec62010-02-20 18:50:38450int SOCKSClientSocket::GetPeerAddress(AddressList* address) const {
[email protected]a796bcec2010-03-22 17:17:26451 return transport_->socket()->GetPeerAddress(address);
[email protected]3cd17242009-06-23 02:59:02452}
[email protected]3cd17242009-06-23 02:59:02453
454} // namespace net