blob: a8da6c4be07dd8533ded024c094d26a254c44cdc [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]e4be2dd2010-12-14 00:44:39143const BoundNetLog& SOCKSClientSocket::NetLog() const {
144 return net_log_;
145}
146
[email protected]9b5614a2010-08-25 20:29:45147void SOCKSClientSocket::SetSubresourceSpeculation() {
148 if (transport_.get() && transport_->socket()) {
149 transport_->socket()->SetSubresourceSpeculation();
150 } else {
151 NOTREACHED();
152 }
153}
154
155void SOCKSClientSocket::SetOmniboxSpeculation() {
156 if (transport_.get() && transport_->socket()) {
157 transport_->socket()->SetOmniboxSpeculation();
158 } else {
159 NOTREACHED();
160 }
161}
162
[email protected]0f873e82010-09-02 16:09:01163bool SOCKSClientSocket::WasEverUsed() const {
164 if (transport_.get() && transport_->socket()) {
165 return transport_->socket()->WasEverUsed();
166 }
167 NOTREACHED();
168 return false;
169}
170
[email protected]7f7e92392010-10-26 18:29:29171bool SOCKSClientSocket::UsingTCPFastOpen() const {
172 if (transport_.get() && transport_->socket()) {
173 return transport_->socket()->UsingTCPFastOpen();
174 }
175 NOTREACHED();
176 return false;
177}
178
179
[email protected]3cd17242009-06-23 02:59:02180// Read is called by the transport layer above to read. This can only be done
181// if the SOCKS handshake is complete.
182int SOCKSClientSocket::Read(IOBuffer* buf, int buf_len,
183 CompletionCallback* callback) {
184 DCHECK(completed_handshake_);
185 DCHECK_EQ(STATE_NONE, next_state_);
186 DCHECK(!user_callback_);
187
[email protected]a796bcec2010-03-22 17:17:26188 return transport_->socket()->Read(buf, buf_len, callback);
[email protected]3cd17242009-06-23 02:59:02189}
190
191// Write is called by the transport layer. This can only be done if the
192// SOCKS handshake is complete.
193int SOCKSClientSocket::Write(IOBuffer* buf, int buf_len,
194 CompletionCallback* callback) {
195 DCHECK(completed_handshake_);
196 DCHECK_EQ(STATE_NONE, next_state_);
197 DCHECK(!user_callback_);
198
[email protected]a796bcec2010-03-22 17:17:26199 return transport_->socket()->Write(buf, buf_len, callback);
[email protected]3cd17242009-06-23 02:59:02200}
201
[email protected]d3f66572009-09-09 22:38:04202bool SOCKSClientSocket::SetReceiveBufferSize(int32 size) {
[email protected]a796bcec2010-03-22 17:17:26203 return transport_->socket()->SetReceiveBufferSize(size);
[email protected]d3f66572009-09-09 22:38:04204}
205
206bool SOCKSClientSocket::SetSendBufferSize(int32 size) {
[email protected]a796bcec2010-03-22 17:17:26207 return transport_->socket()->SetSendBufferSize(size);
[email protected]d3f66572009-09-09 22:38:04208}
209
[email protected]3cd17242009-06-23 02:59:02210void SOCKSClientSocket::DoCallback(int result) {
211 DCHECK_NE(ERR_IO_PENDING, result);
212 DCHECK(user_callback_);
213
214 // Since Run() may result in Read being called,
215 // clear user_callback_ up front.
216 CompletionCallback* c = user_callback_;
217 user_callback_ = NULL;
[email protected]b30a3f52010-10-16 01:05:46218 DVLOG(1) << "Finished setting up SOCKS handshake";
[email protected]3cd17242009-06-23 02:59:02219 c->Run(result);
220}
221
222void SOCKSClientSocket::OnIOComplete(int result) {
223 DCHECK_NE(STATE_NONE, next_state_);
224 int rv = DoLoop(result);
[email protected]5a05c47a2009-11-02 23:25:19225 if (rv != ERR_IO_PENDING) {
[email protected]ec11be62010-04-28 19:28:09226 net_log_.EndEvent(NetLog::TYPE_SOCKS_CONNECT, NULL);
[email protected]3cd17242009-06-23 02:59:02227 DoCallback(rv);
[email protected]5a05c47a2009-11-02 23:25:19228 }
[email protected]3cd17242009-06-23 02:59:02229}
230
231int SOCKSClientSocket::DoLoop(int last_io_result) {
232 DCHECK_NE(next_state_, STATE_NONE);
233 int rv = last_io_result;
234 do {
235 State state = next_state_;
236 next_state_ = STATE_NONE;
237 switch (state) {
238 case STATE_RESOLVE_HOST:
239 DCHECK_EQ(OK, rv);
240 rv = DoResolveHost();
241 break;
242 case STATE_RESOLVE_HOST_COMPLETE:
243 rv = DoResolveHostComplete(rv);
244 break;
245 case STATE_HANDSHAKE_WRITE:
246 DCHECK_EQ(OK, rv);
247 rv = DoHandshakeWrite();
248 break;
249 case STATE_HANDSHAKE_WRITE_COMPLETE:
250 rv = DoHandshakeWriteComplete(rv);
251 break;
252 case STATE_HANDSHAKE_READ:
253 DCHECK_EQ(OK, rv);
254 rv = DoHandshakeRead();
255 break;
256 case STATE_HANDSHAKE_READ_COMPLETE:
257 rv = DoHandshakeReadComplete(rv);
258 break;
259 default:
260 NOTREACHED() << "bad state";
261 rv = ERR_UNEXPECTED;
262 break;
263 }
264 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
265 return rv;
266}
267
268int SOCKSClientSocket::DoResolveHost() {
269 DCHECK_EQ(kSOCKS4Unresolved, socks_version_);
270
271 next_state_ = STATE_RESOLVE_HOST_COMPLETE;
[email protected]ec08bb22009-08-12 00:25:12272 return host_resolver_.Resolve(
[email protected]9e743cd2010-03-16 07:03:53273 host_request_info_, &addresses_, &io_callback_, net_log_);
[email protected]3cd17242009-06-23 02:59:02274}
275
276int SOCKSClientSocket::DoResolveHostComplete(int result) {
277 DCHECK_EQ(kSOCKS4Unresolved, socks_version_);
278
279 bool ok = (result == OK);
280 next_state_ = STATE_HANDSHAKE_WRITE;
281 if (ok) {
282 DCHECK(addresses_.head());
283
284 // If the host is resolved to an IPv6 address, we revert to SOCKS4a
285 // since IPv6 is unsupported by SOCKS4/4a protocol.
286 struct sockaddr *host_info = addresses_.head()->ai_addr;
287 if (host_info->sa_family == AF_INET) {
[email protected]b30a3f52010-10-16 01:05:46288 DVLOG(1) << "Resolved host. Using SOCKS4 to communicate";
[email protected]3cd17242009-06-23 02:59:02289 socks_version_ = kSOCKS4;
290 } else {
[email protected]b30a3f52010-10-16 01:05:46291 DVLOG(1) << "Resolved host but to IPv6. Using SOCKS4a to communicate";
[email protected]3cd17242009-06-23 02:59:02292 socks_version_ = kSOCKS4a;
293 }
294 } else {
[email protected]b30a3f52010-10-16 01:05:46295 DVLOG(1) << "Could not resolve host. Using SOCKS4a to communicate";
[email protected]3cd17242009-06-23 02:59:02296 socks_version_ = kSOCKS4a;
297 }
298
299 // Even if DNS resolution fails, we send OK since the server
300 // resolves the domain.
301 return OK;
302}
303
304// Builds the buffer that is to be sent to the server.
305// We check whether the SOCKS proxy is 4 or 4A.
306// In case it is 4A, the record size increases by size of the hostname.
[email protected]76a51ac82009-06-28 07:58:58307const std::string SOCKSClientSocket::BuildHandshakeWriteBuffer() const {
[email protected]3cd17242009-06-23 02:59:02308 DCHECK_NE(kSOCKS4Unresolved, socks_version_);
309
[email protected]76a51ac82009-06-28 07:58:58310 SOCKS4ServerRequest request;
311 request.version = kSOCKSVersion4;
312 request.command = kSOCKSStreamRequest;
313 request.nw_port = htons(host_request_info_.port());
[email protected]3cd17242009-06-23 02:59:02314
315 if (socks_version_ == kSOCKS4) {
316 const struct addrinfo* ai = addresses_.head();
317 DCHECK(ai);
318 // If the sockaddr is IPv6, we have already marked the version to socks4a
319 // and so this step does not get hit.
[email protected]76a51ac82009-06-28 07:58:58320 struct sockaddr_in* ipv4_host =
[email protected]3cd17242009-06-23 02:59:02321 reinterpret_cast<struct sockaddr_in*>(ai->ai_addr);
[email protected]76a51ac82009-06-28 07:58:58322 memcpy(&request.ip, &(ipv4_host->sin_addr), sizeof(ipv4_host->sin_addr));
[email protected]3cd17242009-06-23 02:59:02323
[email protected]b30a3f52010-10-16 01:05:46324 DVLOG(1) << "Resolved Host is : " << NetAddressToString(ai);
[email protected]3cd17242009-06-23 02:59:02325 } else if (socks_version_ == kSOCKS4a) {
326 // invalid IP of the form 0.0.0.127
[email protected]76a51ac82009-06-28 07:58:58327 memcpy(&request.ip, kInvalidIp, arraysize(kInvalidIp));
[email protected]3cd17242009-06-23 02:59:02328 } else {
329 NOTREACHED();
330 }
331
[email protected]76a51ac82009-06-28 07:58:58332 std::string handshake_data(reinterpret_cast<char*>(&request),
333 sizeof(request));
334 handshake_data.append(kEmptyUserId, arraysize(kEmptyUserId));
[email protected]3cd17242009-06-23 02:59:02335
[email protected]76a51ac82009-06-28 07:58:58336 // In case we are passing the domain also, pass the hostname
337 // terminated with a null character.
[email protected]3cd17242009-06-23 02:59:02338 if (socks_version_ == kSOCKS4a) {
[email protected]76a51ac82009-06-28 07:58:58339 handshake_data.append(host_request_info_.hostname());
340 handshake_data.push_back('\0');
[email protected]3cd17242009-06-23 02:59:02341 }
[email protected]76a51ac82009-06-28 07:58:58342
343 return handshake_data;
[email protected]3cd17242009-06-23 02:59:02344}
345
346// Writes the SOCKS handshake data to the underlying socket connection.
347int SOCKSClientSocket::DoHandshakeWrite() {
348 next_state_ = STATE_HANDSHAKE_WRITE_COMPLETE;
349
[email protected]76a51ac82009-06-28 07:58:58350 if (buffer_.empty()) {
351 buffer_ = BuildHandshakeWriteBuffer();
[email protected]3cd17242009-06-23 02:59:02352 bytes_sent_ = 0;
353 }
354
[email protected]76a51ac82009-06-28 07:58:58355 int handshake_buf_len = buffer_.size() - bytes_sent_;
356 DCHECK_GT(handshake_buf_len, 0);
357 handshake_buf_ = new IOBuffer(handshake_buf_len);
358 memcpy(handshake_buf_->data(), &buffer_[bytes_sent_],
359 handshake_buf_len);
[email protected]a796bcec2010-03-22 17:17:26360 return transport_->socket()->Write(handshake_buf_, handshake_buf_len,
361 &io_callback_);
[email protected]3cd17242009-06-23 02:59:02362}
363
364int SOCKSClientSocket::DoHandshakeWriteComplete(int result) {
365 DCHECK_NE(kSOCKS4Unresolved, socks_version_);
366
367 if (result < 0)
368 return result;
369
[email protected]76a51ac82009-06-28 07:58:58370 // We ignore the case when result is 0, since the underlying Write
371 // may return spurious writes while waiting on the socket.
372
[email protected]3cd17242009-06-23 02:59:02373 bytes_sent_ += result;
[email protected]76a51ac82009-06-28 07:58:58374 if (bytes_sent_ == buffer_.size()) {
[email protected]3cd17242009-06-23 02:59:02375 next_state_ = STATE_HANDSHAKE_READ;
[email protected]76a51ac82009-06-28 07:58:58376 buffer_.clear();
377 } else if (bytes_sent_ < buffer_.size()) {
[email protected]3cd17242009-06-23 02:59:02378 next_state_ = STATE_HANDSHAKE_WRITE;
379 } else {
380 return ERR_UNEXPECTED;
381 }
382
383 return OK;
384}
385
386int SOCKSClientSocket::DoHandshakeRead() {
387 DCHECK_NE(kSOCKS4Unresolved, socks_version_);
388
389 next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
390
[email protected]76a51ac82009-06-28 07:58:58391 if (buffer_.empty()) {
[email protected]3cd17242009-06-23 02:59:02392 bytes_received_ = 0;
393 }
394
[email protected]76a51ac82009-06-28 07:58:58395 int handshake_buf_len = kReadHeaderSize - bytes_received_;
396 handshake_buf_ = new IOBuffer(handshake_buf_len);
[email protected]a796bcec2010-03-22 17:17:26397 return transport_->socket()->Read(handshake_buf_, handshake_buf_len,
398 &io_callback_);
[email protected]3cd17242009-06-23 02:59:02399}
400
401int SOCKSClientSocket::DoHandshakeReadComplete(int result) {
402 DCHECK_NE(kSOCKS4Unresolved, socks_version_);
403
404 if (result < 0)
405 return result;
[email protected]76a51ac82009-06-28 07:58:58406
407 // The underlying socket closed unexpectedly.
408 if (result == 0)
409 return ERR_CONNECTION_CLOSED;
410
[email protected]d5a309592010-02-05 02:22:52411 if (bytes_received_ + result > kReadHeaderSize) {
[email protected]9e743cd2010-03-16 07:03:53412 // TODO(eroman): Describe failure in NetLog.
[email protected]d5a309592010-02-05 02:22:52413 return ERR_SOCKS_CONNECTION_FAILED;
414 }
[email protected]3cd17242009-06-23 02:59:02415
[email protected]76a51ac82009-06-28 07:58:58416 buffer_.append(handshake_buf_->data(), result);
[email protected]3cd17242009-06-23 02:59:02417 bytes_received_ += result;
[email protected]76a51ac82009-06-28 07:58:58418 if (bytes_received_ < kReadHeaderSize) {
[email protected]3cd17242009-06-23 02:59:02419 next_state_ = STATE_HANDSHAKE_READ;
420 return OK;
421 }
422
[email protected]76a51ac82009-06-28 07:58:58423 const SOCKS4ServerResponse* response =
424 reinterpret_cast<const SOCKS4ServerResponse*>(buffer_.data());
[email protected]3cd17242009-06-23 02:59:02425
426 if (response->reserved_null != 0x00) {
427 LOG(ERROR) << "Unknown response from SOCKS server.";
[email protected]d5a309592010-02-05 02:22:52428 return ERR_SOCKS_CONNECTION_FAILED;
[email protected]3cd17242009-06-23 02:59:02429 }
430
[email protected]3cd17242009-06-23 02:59:02431 switch (response->code) {
432 case kServerResponseOk:
433 completed_handshake_ = true;
434 return OK;
435 case kServerResponseRejected:
436 LOG(ERROR) << "SOCKS request rejected or failed";
[email protected]d5a309592010-02-05 02:22:52437 return ERR_SOCKS_CONNECTION_FAILED;
[email protected]3cd17242009-06-23 02:59:02438 case kServerResponseNotReachable:
439 LOG(ERROR) << "SOCKS request failed because client is not running "
440 << "identd (or not reachable from the server)";
[email protected]d5a309592010-02-05 02:22:52441 return ERR_SOCKS_CONNECTION_HOST_UNREACHABLE;
[email protected]3cd17242009-06-23 02:59:02442 case kServerResponseMismatchedUserId:
443 LOG(ERROR) << "SOCKS request failed because client's identd could "
444 << "not confirm the user ID string in the request";
[email protected]d5a309592010-02-05 02:22:52445 return ERR_SOCKS_CONNECTION_FAILED;
[email protected]3cd17242009-06-23 02:59:02446 default:
447 LOG(ERROR) << "SOCKS server sent unknown response";
[email protected]d5a309592010-02-05 02:22:52448 return ERR_SOCKS_CONNECTION_FAILED;
[email protected]3cd17242009-06-23 02:59:02449 }
450
451 // Note: we ignore the last 6 bytes as specified by the SOCKS protocol
452}
453
[email protected]ac9eec62010-02-20 18:50:38454int SOCKSClientSocket::GetPeerAddress(AddressList* address) const {
[email protected]a796bcec2010-03-22 17:17:26455 return transport_->socket()->GetPeerAddress(address);
[email protected]3cd17242009-06-23 02:59:02456}
[email protected]3cd17242009-06-23 02:59:02457
458} // namespace net