socks5_client_socket.cc revision 7b9ca917061470268bf3395c8925d4b9cc52d8e1
1// Copyright (c) 2010 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.
4
5#include "net/socket/socks5_client_socket.h"
6
7#include "base/basictypes.h"
8#include "base/compiler_specific.h"
9#include "base/debug/trace_event.h"
10#include "base/format_macros.h"
11#include "base/string_util.h"
12#include "net/base/io_buffer.h"
13#include "net/base/net_log.h"
14#include "net/base/net_util.h"
15#include "net/base/sys_addrinfo.h"
16#include "net/socket/client_socket_handle.h"
17
18namespace net {
19
20const unsigned int SOCKS5ClientSocket::kGreetReadHeaderSize = 2;
21const unsigned int SOCKS5ClientSocket::kWriteHeaderSize = 10;
22const unsigned int SOCKS5ClientSocket::kReadHeaderSize = 5;
23const uint8 SOCKS5ClientSocket::kSOCKS5Version = 0x05;
24const uint8 SOCKS5ClientSocket::kTunnelCommand = 0x01;
25const uint8 SOCKS5ClientSocket::kNullByte = 0x00;
26
27COMPILE_ASSERT(sizeof(struct in_addr) == 4, incorrect_system_size_of_IPv4);
28COMPILE_ASSERT(sizeof(struct in6_addr) == 16, incorrect_system_size_of_IPv6);
29
30SOCKS5ClientSocket::SOCKS5ClientSocket(
31    ClientSocketHandle* transport_socket,
32    const HostResolver::RequestInfo& req_info)
33    : ALLOW_THIS_IN_INITIALIZER_LIST(
34          io_callback_(this, &SOCKS5ClientSocket::OnIOComplete)),
35      transport_(transport_socket),
36      next_state_(STATE_NONE),
37      user_callback_(NULL),
38      completed_handshake_(false),
39      bytes_sent_(0),
40      bytes_received_(0),
41      read_header_size(kReadHeaderSize),
42      host_request_info_(req_info),
43      net_log_(transport_socket->socket()->NetLog()) {
44}
45
46SOCKS5ClientSocket::SOCKS5ClientSocket(
47    ClientSocket* transport_socket,
48    const HostResolver::RequestInfo& req_info)
49    : ALLOW_THIS_IN_INITIALIZER_LIST(
50          io_callback_(this, &SOCKS5ClientSocket::OnIOComplete)),
51      transport_(new ClientSocketHandle()),
52      next_state_(STATE_NONE),
53      user_callback_(NULL),
54      completed_handshake_(false),
55      bytes_sent_(0),
56      bytes_received_(0),
57      read_header_size(kReadHeaderSize),
58      host_request_info_(req_info),
59      net_log_(transport_socket->NetLog()) {
60  transport_->set_socket(transport_socket);
61}
62
63SOCKS5ClientSocket::~SOCKS5ClientSocket() {
64  Disconnect();
65}
66
67#ifdef ANDROID
68// TODO(kristianm): Find out if Connect should block
69#endif
70int SOCKS5ClientSocket::Connect(CompletionCallback* callback
71#ifdef ANDROID
72                                , bool wait_for_connect
73#endif
74                               ) {
75  DCHECK(transport_.get());
76  DCHECK(transport_->socket());
77  DCHECK_EQ(STATE_NONE, next_state_);
78  DCHECK(!user_callback_);
79
80  // If already connected, then just return OK.
81  if (completed_handshake_)
82    return OK;
83
84  net_log_.BeginEvent(NetLog::TYPE_SOCKS5_CONNECT, NULL);
85
86  next_state_ = STATE_GREET_WRITE;
87  buffer_.clear();
88
89  int rv = DoLoop(OK);
90  if (rv == ERR_IO_PENDING) {
91    user_callback_ = callback;
92  } else {
93    net_log_.EndEvent(NetLog::TYPE_SOCKS5_CONNECT, NULL);
94  }
95  return rv;
96}
97
98void SOCKS5ClientSocket::Disconnect() {
99  completed_handshake_ = false;
100  transport_->socket()->Disconnect();
101
102  // Reset other states to make sure they aren't mistakenly used later.
103  // These are the states initialized by Connect().
104  next_state_ = STATE_NONE;
105  user_callback_ = NULL;
106}
107
108bool SOCKS5ClientSocket::IsConnected() const {
109  return completed_handshake_ && transport_->socket()->IsConnected();
110}
111
112bool SOCKS5ClientSocket::IsConnectedAndIdle() const {
113  return completed_handshake_ && transport_->socket()->IsConnectedAndIdle();
114}
115
116void SOCKS5ClientSocket::SetSubresourceSpeculation() {
117  if (transport_.get() && transport_->socket()) {
118    transport_->socket()->SetSubresourceSpeculation();
119  } else {
120    NOTREACHED();
121  }
122}
123
124void SOCKS5ClientSocket::SetOmniboxSpeculation() {
125  if (transport_.get() && transport_->socket()) {
126    transport_->socket()->SetOmniboxSpeculation();
127  } else {
128    NOTREACHED();
129  }
130}
131
132bool SOCKS5ClientSocket::WasEverUsed() const {
133  if (transport_.get() && transport_->socket()) {
134    return transport_->socket()->WasEverUsed();
135  }
136  NOTREACHED();
137  return false;
138}
139
140bool SOCKS5ClientSocket::UsingTCPFastOpen() const {
141  if (transport_.get() && transport_->socket()) {
142    return transport_->socket()->UsingTCPFastOpen();
143  }
144  NOTREACHED();
145  return false;
146}
147
148// Read is called by the transport layer above to read. This can only be done
149// if the SOCKS handshake is complete.
150int SOCKS5ClientSocket::Read(IOBuffer* buf, int buf_len,
151                             CompletionCallback* callback) {
152  DCHECK(completed_handshake_);
153  DCHECK_EQ(STATE_NONE, next_state_);
154  DCHECK(!user_callback_);
155
156  return transport_->socket()->Read(buf, buf_len, callback);
157}
158
159// Write is called by the transport layer. This can only be done if the
160// SOCKS handshake is complete.
161int SOCKS5ClientSocket::Write(IOBuffer* buf, int buf_len,
162                             CompletionCallback* callback) {
163  DCHECK(completed_handshake_);
164  DCHECK_EQ(STATE_NONE, next_state_);
165  DCHECK(!user_callback_);
166
167  return transport_->socket()->Write(buf, buf_len, callback);
168}
169
170bool SOCKS5ClientSocket::SetReceiveBufferSize(int32 size) {
171  return transport_->socket()->SetReceiveBufferSize(size);
172}
173
174bool SOCKS5ClientSocket::SetSendBufferSize(int32 size) {
175  return transport_->socket()->SetSendBufferSize(size);
176}
177
178void SOCKS5ClientSocket::DoCallback(int result) {
179  DCHECK_NE(ERR_IO_PENDING, result);
180  DCHECK(user_callback_);
181
182  // Since Run() may result in Read being called,
183  // clear user_callback_ up front.
184  CompletionCallback* c = user_callback_;
185  user_callback_ = NULL;
186  c->Run(result);
187}
188
189void SOCKS5ClientSocket::OnIOComplete(int result) {
190  DCHECK_NE(STATE_NONE, next_state_);
191  int rv = DoLoop(result);
192  if (rv != ERR_IO_PENDING) {
193    net_log_.EndEvent(NetLog::TYPE_SOCKS5_CONNECT, NULL);
194    DoCallback(rv);
195  }
196}
197
198int SOCKS5ClientSocket::DoLoop(int last_io_result) {
199  DCHECK_NE(next_state_, STATE_NONE);
200  int rv = last_io_result;
201  do {
202    State state = next_state_;
203    next_state_ = STATE_NONE;
204    switch (state) {
205      case STATE_GREET_WRITE:
206        DCHECK_EQ(OK, rv);
207        net_log_.BeginEvent(NetLog::TYPE_SOCKS5_GREET_WRITE, NULL);
208        rv = DoGreetWrite();
209        break;
210      case STATE_GREET_WRITE_COMPLETE:
211        rv = DoGreetWriteComplete(rv);
212        net_log_.EndEvent(NetLog::TYPE_SOCKS5_GREET_WRITE, NULL);
213        break;
214      case STATE_GREET_READ:
215        DCHECK_EQ(OK, rv);
216        net_log_.BeginEvent(NetLog::TYPE_SOCKS5_GREET_READ, NULL);
217        rv = DoGreetRead();
218        break;
219      case STATE_GREET_READ_COMPLETE:
220        rv = DoGreetReadComplete(rv);
221        net_log_.EndEvent(NetLog::TYPE_SOCKS5_GREET_READ, NULL);
222        break;
223      case STATE_HANDSHAKE_WRITE:
224        DCHECK_EQ(OK, rv);
225        net_log_.BeginEvent(NetLog::TYPE_SOCKS5_HANDSHAKE_WRITE, NULL);
226        rv = DoHandshakeWrite();
227        break;
228      case STATE_HANDSHAKE_WRITE_COMPLETE:
229        rv = DoHandshakeWriteComplete(rv);
230        net_log_.EndEvent(NetLog::TYPE_SOCKS5_HANDSHAKE_WRITE, NULL);
231        break;
232      case STATE_HANDSHAKE_READ:
233        DCHECK_EQ(OK, rv);
234        net_log_.BeginEvent(NetLog::TYPE_SOCKS5_HANDSHAKE_READ, NULL);
235        rv = DoHandshakeRead();
236        break;
237      case STATE_HANDSHAKE_READ_COMPLETE:
238        rv = DoHandshakeReadComplete(rv);
239        net_log_.EndEvent(NetLog::TYPE_SOCKS5_HANDSHAKE_READ, NULL);
240        break;
241      default:
242        NOTREACHED() << "bad state";
243        rv = ERR_UNEXPECTED;
244        break;
245    }
246  } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
247  return rv;
248}
249
250const char kSOCKS5GreetWriteData[] = { 0x05, 0x01, 0x00 };  // no authentication
251const char kSOCKS5GreetReadData[] = { 0x05, 0x00 };
252
253int SOCKS5ClientSocket::DoGreetWrite() {
254  // Since we only have 1 byte to send the hostname length in, if the
255  // URL has a hostname longer than 255 characters we can't send it.
256  if (0xFF < host_request_info_.hostname().size()) {
257    net_log_.AddEvent(NetLog::TYPE_SOCKS_HOSTNAME_TOO_BIG, NULL);
258    return ERR_SOCKS_CONNECTION_FAILED;
259  }
260
261  if (buffer_.empty()) {
262    buffer_ = std::string(kSOCKS5GreetWriteData,
263                          arraysize(kSOCKS5GreetWriteData));
264    bytes_sent_ = 0;
265  }
266
267  next_state_ = STATE_GREET_WRITE_COMPLETE;
268  size_t handshake_buf_len = buffer_.size() - bytes_sent_;
269  handshake_buf_ = new IOBuffer(handshake_buf_len);
270  memcpy(handshake_buf_->data(), &buffer_.data()[bytes_sent_],
271         handshake_buf_len);
272  return transport_->socket()->Write(handshake_buf_, handshake_buf_len,
273                                     &io_callback_);
274}
275
276int SOCKS5ClientSocket::DoGreetWriteComplete(int result) {
277  if (result < 0)
278    return result;
279
280  bytes_sent_ += result;
281  if (bytes_sent_ == buffer_.size()) {
282    buffer_.clear();
283    bytes_received_ = 0;
284    next_state_ = STATE_GREET_READ;
285  } else {
286    next_state_ = STATE_GREET_WRITE;
287  }
288  return OK;
289}
290
291int SOCKS5ClientSocket::DoGreetRead() {
292  next_state_ = STATE_GREET_READ_COMPLETE;
293  size_t handshake_buf_len = kGreetReadHeaderSize - bytes_received_;
294  handshake_buf_ = new IOBuffer(handshake_buf_len);
295  return transport_->socket()->Read(handshake_buf_, handshake_buf_len,
296                                    &io_callback_);
297}
298
299int SOCKS5ClientSocket::DoGreetReadComplete(int result) {
300  if (result < 0)
301    return result;
302
303  if (result == 0) {
304    net_log_.AddEvent(NetLog::TYPE_SOCKS_UNEXPECTEDLY_CLOSED_DURING_GREETING,
305                      NULL);
306    return ERR_SOCKS_CONNECTION_FAILED;
307  }
308
309  bytes_received_ += result;
310  buffer_.append(handshake_buf_->data(), result);
311  if (bytes_received_ < kGreetReadHeaderSize) {
312    next_state_ = STATE_GREET_READ;
313    return OK;
314  }
315
316  // Got the greet data.
317  if (buffer_[0] != kSOCKS5Version) {
318    net_log_.AddEvent(
319        NetLog::TYPE_SOCKS_UNEXPECTED_VERSION,
320        make_scoped_refptr(new NetLogIntegerParameter("version", buffer_[0])));
321    return ERR_SOCKS_CONNECTION_FAILED;
322  }
323  if (buffer_[1] != 0x00) {
324    net_log_.AddEvent(
325        NetLog::TYPE_SOCKS_UNEXPECTED_AUTH,
326        make_scoped_refptr(new NetLogIntegerParameter("method", buffer_[1])));
327    return ERR_SOCKS_CONNECTION_FAILED;
328  }
329
330  buffer_.clear();
331  next_state_ = STATE_HANDSHAKE_WRITE;
332  return OK;
333}
334
335int SOCKS5ClientSocket::BuildHandshakeWriteBuffer(std::string* handshake)
336    const {
337  DCHECK(handshake->empty());
338
339  handshake->push_back(kSOCKS5Version);
340  handshake->push_back(kTunnelCommand);  // Connect command
341  handshake->push_back(kNullByte);  // Reserved null
342
343  handshake->push_back(kEndPointDomain);  // The type of the address.
344
345  DCHECK_GE(static_cast<size_t>(0xFF), host_request_info_.hostname().size());
346
347  // First add the size of the hostname, followed by the hostname.
348  handshake->push_back(static_cast<unsigned char>(
349      host_request_info_.hostname().size()));
350  handshake->append(host_request_info_.hostname());
351
352  uint16 nw_port = htons(host_request_info_.port());
353  handshake->append(reinterpret_cast<char*>(&nw_port), sizeof(nw_port));
354  return OK;
355}
356
357// Writes the SOCKS handshake data to the underlying socket connection.
358int SOCKS5ClientSocket::DoHandshakeWrite() {
359  next_state_ = STATE_HANDSHAKE_WRITE_COMPLETE;
360
361  if (buffer_.empty()) {
362    int rv = BuildHandshakeWriteBuffer(&buffer_);
363    if (rv != OK)
364      return rv;
365    bytes_sent_ = 0;
366  }
367
368  int handshake_buf_len = buffer_.size() - bytes_sent_;
369  DCHECK_LT(0, handshake_buf_len);
370  handshake_buf_ = new IOBuffer(handshake_buf_len);
371  memcpy(handshake_buf_->data(), &buffer_[bytes_sent_],
372         handshake_buf_len);
373  return transport_->socket()->Write(handshake_buf_, handshake_buf_len,
374                                     &io_callback_);
375}
376
377int SOCKS5ClientSocket::DoHandshakeWriteComplete(int result) {
378  if (result < 0)
379    return result;
380
381  // We ignore the case when result is 0, since the underlying Write
382  // may return spurious writes while waiting on the socket.
383
384  bytes_sent_ += result;
385  if (bytes_sent_ == buffer_.size()) {
386    next_state_ = STATE_HANDSHAKE_READ;
387    buffer_.clear();
388  } else if (bytes_sent_ < buffer_.size()) {
389    next_state_ = STATE_HANDSHAKE_WRITE;
390  } else {
391    NOTREACHED();
392  }
393
394  return OK;
395}
396
397int SOCKS5ClientSocket::DoHandshakeRead() {
398  next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
399
400  if (buffer_.empty()) {
401    bytes_received_ = 0;
402    read_header_size = kReadHeaderSize;
403  }
404
405  int handshake_buf_len = read_header_size - bytes_received_;
406  handshake_buf_ = new IOBuffer(handshake_buf_len);
407  return transport_->socket()->Read(handshake_buf_, handshake_buf_len,
408                                    &io_callback_);
409}
410
411int SOCKS5ClientSocket::DoHandshakeReadComplete(int result) {
412  if (result < 0)
413    return result;
414
415  // The underlying socket closed unexpectedly.
416  if (result == 0) {
417    net_log_.AddEvent(NetLog::TYPE_SOCKS_UNEXPECTEDLY_CLOSED_DURING_HANDSHAKE,
418                      NULL);
419    return ERR_SOCKS_CONNECTION_FAILED;
420  }
421
422  buffer_.append(handshake_buf_->data(), result);
423  bytes_received_ += result;
424
425  // When the first few bytes are read, check how many more are required
426  // and accordingly increase them
427  if (bytes_received_ == kReadHeaderSize) {
428    if (buffer_[0] != kSOCKS5Version || buffer_[2] != kNullByte) {
429      net_log_.AddEvent(
430          NetLog::TYPE_SOCKS_UNEXPECTED_VERSION,
431          make_scoped_refptr(
432              new NetLogIntegerParameter("version", buffer_[0])));
433      return ERR_SOCKS_CONNECTION_FAILED;
434    }
435    if (buffer_[1] != 0x00) {
436      net_log_.AddEvent(
437          NetLog::TYPE_SOCKS_SERVER_ERROR,
438          make_scoped_refptr(
439              new NetLogIntegerParameter("error_code", buffer_[1])));
440      return ERR_SOCKS_CONNECTION_FAILED;
441    }
442
443    // We check the type of IP/Domain the server returns and accordingly
444    // increase the size of the response. For domains, we need to read the
445    // size of the domain, so the initial request size is upto the domain
446    // size. Since for IPv4/IPv6 the size is fixed and hence no 'size' is
447    // read, we substract 1 byte from the additional request size.
448    SocksEndPointAddressType address_type =
449        static_cast<SocksEndPointAddressType>(buffer_[3]);
450    if (address_type == kEndPointDomain)
451      read_header_size += static_cast<uint8>(buffer_[4]);
452    else if (address_type == kEndPointResolvedIPv4)
453      read_header_size += sizeof(struct in_addr) - 1;
454    else if (address_type == kEndPointResolvedIPv6)
455      read_header_size += sizeof(struct in6_addr) - 1;
456    else {
457      net_log_.AddEvent(
458          NetLog::TYPE_SOCKS_UNKNOWN_ADDRESS_TYPE,
459          make_scoped_refptr(
460              new NetLogIntegerParameter("address_type", buffer_[3])));
461      return ERR_SOCKS_CONNECTION_FAILED;
462    }
463
464    read_header_size += 2;  // for the port.
465    next_state_ = STATE_HANDSHAKE_READ;
466    return OK;
467  }
468
469  // When the final bytes are read, setup handshake. We ignore the rest
470  // of the response since they represent the SOCKSv5 endpoint and have
471  // no use when doing a tunnel connection.
472  if (bytes_received_ == read_header_size) {
473    completed_handshake_ = true;
474    buffer_.clear();
475    next_state_ = STATE_NONE;
476    return OK;
477  }
478
479  next_state_ = STATE_HANDSHAKE_READ;
480  return OK;
481}
482
483int SOCKS5ClientSocket::GetPeerAddress(AddressList* address) const {
484  return transport_->socket()->GetPeerAddress(address);
485}
486
487}  // namespace net
488