Update V8 to version 4.7.47.
[chromium-blink-merge.git] / net / socket / socks5_client_socket.cc
blob4ac9ca59656a47a9209c5e15af16bea3745b6557
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"
19 namespace net {
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),
39 bytes_sent_(0),
40 bytes_received_(0),
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() {
48 Disconnect();
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_)
59 return OK;
61 net_log_.BeginEvent(NetLog::TYPE_SOCKS5_CONNECT);
63 next_state_ = STATE_GREET_WRITE;
64 buffer_.clear();
66 int rv = DoLoop(OK);
67 if (rv == ERR_IO_PENDING) {
68 user_callback_ = callback;
69 } else {
70 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SOCKS5_CONNECT, rv);
72 return 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 {
94 return net_log_;
97 void SOCKS5ClientSocket::SetSubresourceSpeculation() {
98 if (transport_.get() && transport_->socket()) {
99 transport_->socket()->SetSubresourceSpeculation();
100 } else {
101 NOTREACHED();
105 void SOCKS5ClientSocket::SetOmniboxSpeculation() {
106 if (transport_.get() && transport_->socket()) {
107 transport_->socket()->SetOmniboxSpeculation();
108 } else {
109 NOTREACHED();
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();
121 NOTREACHED();
122 return false;
125 bool SOCKS5ClientSocket::WasNpnNegotiated() const {
126 if (transport_.get() && transport_->socket()) {
127 return transport_->socket()->WasNpnNegotiated();
129 NOTREACHED();
130 return false;
133 NextProto SOCKS5ClientSocket::GetNegotiatedProtocol() const {
134 if (transport_.get() && transport_->socket()) {
135 return transport_->socket()->GetNegotiatedProtocol();
137 NOTREACHED();
138 return kProtoUnknown;
141 bool SOCKS5ClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
142 if (transport_.get() && transport_->socket()) {
143 return transport_->socket()->GetSSLInfo(ssl_info);
145 NOTREACHED();
146 return false;
149 void SOCKS5ClientSocket::GetConnectionAttempts(ConnectionAttempts* out) const {
150 out->clear();
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(
163 buf, buf_len,
164 base::Bind(&SOCKS5ClientSocket::OnReadWriteComplete,
165 base::Unretained(this), callback));
166 if (rv > 0)
167 was_ever_used_ = true;
168 return rv;
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(
181 buf, buf_len,
182 base::Bind(&SOCKS5ClientSocket::OnReadWriteComplete,
183 base::Unretained(this), callback));
184 if (rv > 0)
185 was_ever_used_ = true;
186 return rv;
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);
211 DoCallback(rv);
215 void SOCKS5ClientSocket::OnReadWriteComplete(const CompletionCallback& callback,
216 int result) {
217 DCHECK_NE(ERR_IO_PENDING, result);
218 DCHECK(!callback.is_null());
220 if (result > 0)
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;
228 do {
229 State state = next_state_;
230 next_state_ = STATE_NONE;
231 switch (state) {
232 case STATE_GREET_WRITE:
233 DCHECK_EQ(OK, rv);
234 net_log_.BeginEvent(NetLog::TYPE_SOCKS5_GREET_WRITE);
235 rv = DoGreetWrite();
236 break;
237 case STATE_GREET_WRITE_COMPLETE:
238 rv = DoGreetWriteComplete(rv);
239 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SOCKS5_GREET_WRITE, rv);
240 break;
241 case STATE_GREET_READ:
242 DCHECK_EQ(OK, rv);
243 net_log_.BeginEvent(NetLog::TYPE_SOCKS5_GREET_READ);
244 rv = DoGreetRead();
245 break;
246 case STATE_GREET_READ_COMPLETE:
247 rv = DoGreetReadComplete(rv);
248 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SOCKS5_GREET_READ, rv);
249 break;
250 case STATE_HANDSHAKE_WRITE:
251 DCHECK_EQ(OK, rv);
252 net_log_.BeginEvent(NetLog::TYPE_SOCKS5_HANDSHAKE_WRITE);
253 rv = DoHandshakeWrite();
254 break;
255 case STATE_HANDSHAKE_WRITE_COMPLETE:
256 rv = DoHandshakeWriteComplete(rv);
257 net_log_.EndEventWithNetErrorCode(
258 NetLog::TYPE_SOCKS5_HANDSHAKE_WRITE, rv);
259 break;
260 case STATE_HANDSHAKE_READ:
261 DCHECK_EQ(OK, rv);
262 net_log_.BeginEvent(NetLog::TYPE_SOCKS5_HANDSHAKE_READ);
263 rv = DoHandshakeRead();
264 break;
265 case STATE_HANDSHAKE_READ_COMPLETE:
266 rv = DoHandshakeReadComplete(rv);
267 net_log_.EndEventWithNetErrorCode(
268 NetLog::TYPE_SOCKS5_HANDSHAKE_READ, rv);
269 break;
270 default:
271 NOTREACHED() << "bad state";
272 rv = ERR_UNEXPECTED;
273 break;
275 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
276 return rv;
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));
292 bytes_sent_ = 0;
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_],
299 handshake_buf_len);
300 return transport_->socket()
301 ->Write(handshake_buf_.get(), handshake_buf_len, io_callback_);
304 int SOCKS5ClientSocket::DoGreetWriteComplete(int result) {
305 if (result < 0)
306 return result;
308 bytes_sent_ += result;
309 if (bytes_sent_ == buffer_.size()) {
310 buffer_.clear();
311 bytes_received_ = 0;
312 next_state_ = STATE_GREET_READ;
313 } else {
314 next_state_ = STATE_GREET_WRITE;
316 return OK;
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) {
328 if (result < 0)
329 return result;
331 if (result == 0) {
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;
340 return OK;
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;
355 buffer_.clear();
356 next_state_ = STATE_HANDSHAKE_WRITE;
357 return OK;
360 int SOCKS5ClientSocket::BuildHandshakeWriteBuffer(std::string* handshake)
361 const {
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));
379 return OK;
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_);
388 if (rv != OK)
389 return rv;
390 bytes_sent_ = 0;
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_],
397 handshake_buf_len);
398 return transport_->socket()
399 ->Write(handshake_buf_.get(), handshake_buf_len, io_callback_);
402 int SOCKS5ClientSocket::DoHandshakeWriteComplete(int result) {
403 if (result < 0)
404 return 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;
412 buffer_.clear();
413 } else if (bytes_sent_ < buffer_.size()) {
414 next_state_ = STATE_HANDSHAKE_WRITE;
415 } else {
416 NOTREACHED();
419 return OK;
422 int SOCKS5ClientSocket::DoHandshakeRead() {
423 next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
425 if (buffer_.empty()) {
426 bytes_received_ = 0;
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) {
437 if (result < 0)
438 return result;
440 // The underlying socket closed unexpectedly.
441 if (result == 0) {
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;
476 else {
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;
484 return OK;
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;
492 buffer_.clear();
493 next_state_ = STATE_NONE;
494 return OK;
497 next_state_ = STATE_HANDSHAKE_READ;
498 return OK;
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);
509 } // namespace net