summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorarindam@chromium.org <arindam@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98>2009-07-14 16:49:54 +0000
committerarindam@chromium.org <arindam@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98>2009-07-14 16:49:54 +0000
commit41fe98bb5c0955a12d48527308e359ae577f09bc (patch)
tree59e259d9b7abe8d59a288dbd6eddc8aae034c75a
parent4f26826dc91e9aa41f3adbda05f94c44581eddd8 (diff)
downloadchromium_src-41fe98bb5c0955a12d48527308e359ae577f09bc.zip
chromium_src-41fe98bb5c0955a12d48527308e359ae577f09bc.tar.gz
chromium_src-41fe98bb5c0955a12d48527308e359ae577f09bc.tar.bz2
SOCKS v5 implementation
The implementation is incomplete as it does not support any authentication methods and does not have a UDP layer. BUG=469 TEST=unittests (included) Review URL: http://codereview.chromium.org/150187 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@20626 0039d316-1c4b-4281-b951-d872f2087c98
-rw-r--r--net/http/http_network_transaction.cc14
-rw-r--r--net/http/http_network_transaction_unittest.cc132
-rw-r--r--net/net.gyp3
-rw-r--r--net/socket/socks5_client_socket.cc430
-rw-r--r--net/socket/socks5_client_socket.h151
-rw-r--r--net/socket/socks5_client_socket_unittest.cc307
6 files changed, 1028 insertions, 9 deletions
diff --git a/net/http/http_network_transaction.cc b/net/http/http_network_transaction.cc
index ca3547c..f705541 100644
--- a/net/http/http_network_transaction.cc
+++ b/net/http/http_network_transaction.cc
@@ -26,6 +26,7 @@
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"
#include "net/socket/client_socket_factory.h"
+#include "net/socket/socks5_client_socket.h"
#include "net/socket/socks_client_socket.h"
#include "net/socket/ssl_client_socket.h"
@@ -336,7 +337,7 @@ int HttpNetworkTransaction::Read(IOBuffer* buf, int buf_len,
CompletionCallback* callback) {
DCHECK(response_.headers);
DCHECK(buf);
- DCHECK(buf_len > 0);
+ DCHECK_LT(0, buf_len);
if (!connection_.is_initialized())
return 0; // connection_ has been reset. Treat like EOF.
@@ -349,7 +350,7 @@ int HttpNetworkTransaction::Read(IOBuffer* buf, int buf_len,
// network attacker can already control HTTP sessions.
// We reach this case when the user cancels a 407 proxy auth prompt.
// See http://crbug.com/8473
- DCHECK(response_.headers->response_code() == 407);
+ DCHECK_EQ(407, response_.headers->response_code());
LogBlockedTunnelResponse(response_.headers->response_code());
return ERR_TUNNEL_CONNECTION_FAILED;
}
@@ -545,10 +546,10 @@ int HttpNetworkTransaction::DoResolveProxy() {
int HttpNetworkTransaction::DoResolveProxyComplete(int result) {
next_state_ = STATE_INIT_CONNECTION;
- // Remove unsupported proxies (like SOCKS5) from the list.
+ // Remove unsupported proxies from the list.
proxy_info_.RemoveProxiesWithoutScheme(
ProxyServer::SCHEME_DIRECT | ProxyServer::SCHEME_HTTP |
- ProxyServer::SCHEME_SOCKS4);
+ ProxyServer::SCHEME_SOCKS4 | ProxyServer::SCHEME_SOCKS5);
pac_request_ = NULL;
@@ -662,7 +663,10 @@ int HttpNetworkTransaction::DoSOCKSConnect() {
request_->url.EffectiveIntPort());
req_info.set_referrer(request_->referrer);
- s = new SOCKSClientSocket(s, req_info, session_->host_resolver());
+ if (proxy_info_.proxy_server().scheme() == ProxyServer::SCHEME_SOCKS5)
+ s = new SOCKS5ClientSocket(s, req_info, session_->host_resolver());
+ else
+ s = new SOCKSClientSocket(s, req_info, session_->host_resolver());
connection_.set_socket(s);
return connection_.socket()->Connect(&io_callback_);
}
diff --git a/net/http/http_network_transaction_unittest.cc b/net/http/http_network_transaction_unittest.cc
index bcb22a9..74764a5 100644
--- a/net/http/http_network_transaction_unittest.cc
+++ b/net/http/http_network_transaction_unittest.cc
@@ -3065,14 +3065,14 @@ TEST_F(HttpNetworkTransactionTest, SOCKS4_HTTP_GET) {
char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 };
MockWrite data_writes[] = {
- MockWrite(true, write_buffer, 9),
+ MockWrite(true, write_buffer, arraysize(write_buffer)),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.google.com\r\n"
"Connection: keep-alive\r\n\r\n")
};
MockRead data_reads[] = {
- MockWrite(true, read_buffer, 8),
+ MockWrite(true, read_buffer, arraysize(read_buffer)),
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
MockRead("Payload"),
@@ -3118,14 +3118,138 @@ TEST_F(HttpNetworkTransactionTest, SOCKS4_SSL_GET) {
unsigned char read_buffer[] = { 0x00, 0x5A, 0x00, 0x00, 0, 0, 0, 0 };
MockWrite data_writes[] = {
- MockWrite(true, reinterpret_cast<char*>(write_buffer), 9),
+ MockWrite(true, reinterpret_cast<char*>(write_buffer),
+ arraysize(write_buffer)),
MockWrite("GET / HTTP/1.1\r\n"
"Host: www.google.com\r\n"
"Connection: keep-alive\r\n\r\n")
};
MockRead data_reads[] = {
- MockWrite(true, reinterpret_cast<char*>(read_buffer), 8),
+ MockWrite(true, reinterpret_cast<char*>(read_buffer),
+ arraysize(read_buffer)),
+ MockRead("HTTP/1.0 200 OK\r\n"),
+ MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
+ MockRead("Payload"),
+ MockRead(false, OK)
+ };
+
+ StaticMockSocket data(data_reads, data_writes);
+ session_deps.socket_factory.AddMockSocket(&data);
+
+ MockSSLSocket ssl(true, OK);
+ session_deps.socket_factory.AddMockSSLSocket(&ssl);
+
+ TestCompletionCallback callback;
+
+ int rv = trans->Start(&request, &callback);
+ EXPECT_EQ(ERR_IO_PENDING, rv);
+
+ rv = callback.WaitForResult();
+ EXPECT_EQ(OK, rv);
+
+ const HttpResponseInfo* response = trans->GetResponseInfo();
+ EXPECT_FALSE(response == NULL);
+
+ std::string response_text;
+ rv = ReadTransaction(trans.get(), &response_text);
+ EXPECT_EQ(OK, rv);
+ EXPECT_EQ("Payload", response_text);
+}
+
+TEST_F(HttpNetworkTransactionTest, SOCKS5_HTTP_GET) {
+ SessionDependencies session_deps;
+ session_deps.proxy_service.reset(CreateFixedProxyService(
+ "socks5://myproxy:1080"));
+
+ scoped_ptr<HttpTransaction> trans(
+ new HttpNetworkTransaction(
+ CreateSession(&session_deps),
+ &session_deps.socket_factory));
+
+ HttpRequestInfo request;
+ request.method = "GET";
+ request.url = GURL("http://www.google.com/");
+ request.load_flags = 0;
+
+ const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
+ const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
+ const char kSOCKS5OkRequest[] =
+ { 0x05, 0x01, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
+ const char kSOCKS5OkResponse[] =
+ { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
+
+ MockWrite data_writes[] = {
+ MockWrite(true, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)),
+ MockWrite(true, kSOCKS5OkRequest, arraysize(kSOCKS5OkRequest)),
+ MockWrite("GET / HTTP/1.1\r\n"
+ "Host: www.google.com\r\n"
+ "Connection: keep-alive\r\n\r\n")
+ };
+
+ MockRead data_reads[] = {
+ MockWrite(true, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)),
+ MockWrite(true, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)),
+ MockRead("HTTP/1.0 200 OK\r\n"),
+ MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
+ MockRead("Payload"),
+ MockRead(false, OK)
+ };
+
+ StaticMockSocket data(data_reads, data_writes);
+ session_deps.socket_factory.AddMockSocket(&data);
+
+ TestCompletionCallback callback;
+
+ int rv = trans->Start(&request, &callback);
+ EXPECT_EQ(ERR_IO_PENDING, rv);
+
+ rv = callback.WaitForResult();
+ EXPECT_EQ(OK, rv);
+
+ const HttpResponseInfo* response = trans->GetResponseInfo();
+ EXPECT_FALSE(response == NULL);
+
+ std::string response_text;
+ rv = ReadTransaction(trans.get(), &response_text);
+ EXPECT_EQ(OK, rv);
+ EXPECT_EQ("Payload", response_text);
+}
+
+TEST_F(HttpNetworkTransactionTest, SOCKS5_SSL_GET) {
+ SessionDependencies session_deps;
+ session_deps.proxy_service.reset(CreateFixedProxyService(
+ "socks5://myproxy:1080"));
+
+ scoped_ptr<HttpTransaction> trans(
+ new HttpNetworkTransaction(
+ CreateSession(&session_deps),
+ &session_deps.socket_factory));
+
+ HttpRequestInfo request;
+ request.method = "GET";
+ request.url = GURL("https://www.google.com/");
+ request.load_flags = 0;
+
+ const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
+ const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
+ const unsigned char kSOCKS5OkRequest[] =
+ { 0x05, 0x01, 0x00, 0x01, 127, 0, 0, 1, 0x01, 0xBB };
+ const char kSOCKS5OkResponse[] =
+ { 0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0x00, 0x00 };
+
+ MockWrite data_writes[] = {
+ MockWrite(true, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)),
+ MockWrite(true, reinterpret_cast<const char*>(kSOCKS5OkRequest),
+ arraysize(kSOCKS5OkRequest)),
+ MockWrite("GET / HTTP/1.1\r\n"
+ "Host: www.google.com\r\n"
+ "Connection: keep-alive\r\n\r\n")
+ };
+
+ MockRead data_reads[] = {
+ MockWrite(true, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)),
+ MockWrite(true, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)),
MockRead("HTTP/1.0 200 OK\r\n"),
MockRead("Content-Type: text/html; charset=iso-8859-1\r\n\r\n"),
MockRead("Payload"),
diff --git a/net/net.gyp b/net/net.gyp
index a5b3b12d..5bd2257 100644
--- a/net/net.gyp
+++ b/net/net.gyp
@@ -276,6 +276,8 @@
'socket/client_socket_pool_base.cc',
'socket/client_socket_pool_base.h',
'socket/socket.h',
+ 'socket/socks5_client_socket.cc',
+ 'socket/socks5_client_socket.h',
'socket/socks_client_socket.cc',
'socket/socks_client_socket.h',
'socket/ssl_client_socket.h',
@@ -483,6 +485,7 @@
'proxy/proxy_server_unittest.cc',
'proxy/proxy_service_unittest.cc',
'socket/client_socket_pool_base_unittest.cc',
+ 'socket/socks5_client_socket_unittest.cc',
'socket/socks_client_socket_unittest.cc',
'socket/ssl_client_socket_unittest.cc',
'socket/tcp_client_socket_pool_unittest.cc',
diff --git a/net/socket/socks5_client_socket.cc b/net/socket/socks5_client_socket.cc
new file mode 100644
index 0000000..8876bb9
--- /dev/null
+++ b/net/socket/socks5_client_socket.cc
@@ -0,0 +1,430 @@
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "net/socket/socks5_client_socket.h"
+
+#include "base/basictypes.h"
+#include "build/build_config.h"
+#if defined(OS_WIN)
+#include <ws2tcpip.h>
+#elif defined(OS_POSIX)
+#include <netdb.h>
+#endif
+#include "base/compiler_specific.h"
+#include "base/trace_event.h"
+#include "net/base/io_buffer.h"
+#include "net/base/net_util.h"
+
+namespace net {
+
+const unsigned int SOCKS5ClientSocket::kGreetReadHeaderSize = 2;
+const unsigned int SOCKS5ClientSocket::kWriteHeaderSize = 10;
+const unsigned int SOCKS5ClientSocket::kReadHeaderSize = 5;
+const uint8 SOCKS5ClientSocket::kSOCKS5Version = 0x05;
+const uint8 SOCKS5ClientSocket::kTunnelCommand = 0x01;
+const uint8 SOCKS5ClientSocket::kNullByte = 0x00;
+
+COMPILE_ASSERT(sizeof(struct in_addr) == 4, incorrect_system_size_of_IPv4);
+COMPILE_ASSERT(sizeof(struct in6_addr) == 16, incorrect_system_size_of_IPv6);
+
+SOCKS5ClientSocket::SOCKS5ClientSocket(ClientSocket* transport_socket,
+ const HostResolver::RequestInfo& req_info,
+ HostResolver* host_resolver)
+ : ALLOW_THIS_IN_INITIALIZER_LIST(
+ io_callback_(this, &SOCKS5ClientSocket::OnIOComplete)),
+ transport_(transport_socket),
+ next_state_(STATE_NONE),
+ address_type_(kEndPointUnresolved),
+ user_callback_(NULL),
+ completed_handshake_(false),
+ bytes_sent_(0),
+ bytes_received_(0),
+ read_header_size(kReadHeaderSize),
+ host_resolver_(host_resolver),
+ host_request_info_(req_info) {
+}
+
+SOCKS5ClientSocket::~SOCKS5ClientSocket() {
+ Disconnect();
+}
+
+int SOCKS5ClientSocket::Connect(CompletionCallback* callback) {
+ DCHECK(transport_.get());
+ DCHECK(transport_->IsConnected());
+ DCHECK_EQ(STATE_NONE, next_state_);
+ DCHECK(!user_callback_);
+
+ // If already connected, then just return OK.
+ if (completed_handshake_)
+ return OK;
+
+ next_state_ = STATE_RESOLVE_HOST;
+
+ int rv = DoLoop(OK);
+ if (rv == ERR_IO_PENDING)
+ user_callback_ = callback;
+ return rv;
+}
+
+void SOCKS5ClientSocket::Disconnect() {
+ completed_handshake_ = false;
+ transport_->Disconnect();
+}
+
+bool SOCKS5ClientSocket::IsConnected() const {
+ return completed_handshake_ && transport_->IsConnected();
+}
+
+bool SOCKS5ClientSocket::IsConnectedAndIdle() const {
+ return completed_handshake_ && transport_->IsConnectedAndIdle();
+}
+
+// Read is called by the transport layer above to read. This can only be done
+// if the SOCKS handshake is complete.
+int SOCKS5ClientSocket::Read(IOBuffer* buf, int buf_len,
+ CompletionCallback* callback) {
+ DCHECK(completed_handshake_);
+ DCHECK_EQ(STATE_NONE, next_state_);
+ DCHECK(!user_callback_);
+
+ return transport_->Read(buf, buf_len, callback);
+}
+
+// Write is called by the transport layer. This can only be done if the
+// SOCKS handshake is complete.
+int SOCKS5ClientSocket::Write(IOBuffer* buf, int buf_len,
+ CompletionCallback* callback) {
+ DCHECK(completed_handshake_);
+ DCHECK_EQ(STATE_NONE, next_state_);
+ DCHECK(!user_callback_);
+
+ return transport_->Write(buf, buf_len, callback);
+}
+
+void SOCKS5ClientSocket::DoCallback(int result) {
+ DCHECK_NE(ERR_IO_PENDING, result);
+ DCHECK(user_callback_);
+
+ // Since Run() may result in Read being called,
+ // clear user_callback_ up front.
+ CompletionCallback* c = user_callback_;
+ user_callback_ = NULL;
+ DLOG(INFO) << "Finished setting up SOCKSv5 handshake";
+ c->Run(result);
+}
+
+void SOCKS5ClientSocket::OnIOComplete(int result) {
+ DCHECK_NE(STATE_NONE, next_state_);
+ int rv = DoLoop(result);
+ if (rv != ERR_IO_PENDING)
+ DoCallback(rv);
+}
+
+int SOCKS5ClientSocket::DoLoop(int last_io_result) {
+ DCHECK_NE(next_state_, STATE_NONE);
+ int rv = last_io_result;
+ do {
+ State state = next_state_;
+ next_state_ = STATE_NONE;
+ switch (state) {
+ case STATE_RESOLVE_HOST:
+ DCHECK_EQ(OK, rv);
+ rv = DoResolveHost();
+ break;
+ case STATE_RESOLVE_HOST_COMPLETE:
+ rv = DoResolveHostComplete(rv);
+ break;
+ case STATE_GREET_WRITE:
+ DCHECK_EQ(OK, rv);
+ rv = DoGreetWrite();
+ break;
+ case STATE_GREET_WRITE_COMPLETE:
+ rv = DoGreetWriteComplete(rv);
+ break;
+ case STATE_GREET_READ:
+ DCHECK_EQ(OK, rv);
+ rv = DoGreetRead();
+ break;
+ case STATE_GREET_READ_COMPLETE:
+ rv = DoGreetReadComplete(rv);
+ break;
+ case STATE_HANDSHAKE_WRITE:
+ DCHECK_EQ(OK, rv);
+ rv = DoHandshakeWrite();
+ break;
+ case STATE_HANDSHAKE_WRITE_COMPLETE:
+ rv = DoHandshakeWriteComplete(rv);
+ break;
+ case STATE_HANDSHAKE_READ:
+ DCHECK_EQ(OK, rv);
+ rv = DoHandshakeRead();
+ break;
+ case STATE_HANDSHAKE_READ_COMPLETE:
+ rv = DoHandshakeReadComplete(rv);
+ break;
+ default:
+ NOTREACHED() << "bad state";
+ rv = ERR_UNEXPECTED;
+ break;
+ }
+ } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
+ return rv;
+}
+
+int SOCKS5ClientSocket::DoResolveHost() {
+ DCHECK_EQ(kEndPointUnresolved, address_type_);
+
+ next_state_ = STATE_RESOLVE_HOST_COMPLETE;
+ return host_resolver_.Resolve(host_request_info_, &addresses_, &io_callback_);
+}
+
+int SOCKS5ClientSocket::DoResolveHostComplete(int result) {
+ DCHECK_EQ(kEndPointUnresolved, address_type_);
+
+ bool ok = (result == OK);
+ next_state_ = STATE_GREET_WRITE;
+ if (ok) {
+ DCHECK(addresses_.head());
+ struct sockaddr* host_info = addresses_.head()->ai_addr;
+ if (host_info->sa_family == AF_INET) {
+ address_type_ = kEndPointResolvedIPv4;
+ } else if (host_info->sa_family == AF_INET6) {
+ address_type_ = kEndPointResolvedIPv6;
+ }
+ } else {
+ address_type_ = kEndPointFailedDomain;
+ }
+
+ buffer_.clear();
+
+ // Even if DNS resolution fails, we send OK since the server
+ // resolves the domain.
+ return OK;
+}
+
+const char kSOCKS5GreetWriteData[] = { 0x05, 0x01, 0x00 }; // no authentication
+const char kSOCKS5GreetReadData[] = { 0x05, 0x00 };
+
+int SOCKS5ClientSocket::DoGreetWrite() {
+ if (buffer_.empty()) {
+ buffer_ = std::string(kSOCKS5GreetWriteData,
+ arraysize(kSOCKS5GreetWriteData));
+ bytes_sent_ = 0;
+ }
+
+ next_state_ = STATE_GREET_WRITE_COMPLETE;
+ size_t handshake_buf_len = buffer_.size() - bytes_sent_;
+ handshake_buf_ = new IOBuffer(handshake_buf_len);
+ memcpy(handshake_buf_->data(), &buffer_.data()[bytes_sent_],
+ handshake_buf_len);
+ return transport_->Write(handshake_buf_, handshake_buf_len, &io_callback_);
+}
+
+int SOCKS5ClientSocket::DoGreetWriteComplete(int result) {
+ if (result < 0)
+ return result;
+
+ bytes_sent_ += result;
+ if (bytes_sent_ == buffer_.size()) {
+ buffer_.clear();
+ bytes_received_ = 0;
+ next_state_ = STATE_GREET_READ;
+ } else {
+ next_state_ = STATE_GREET_WRITE;
+ }
+ return OK;
+}
+
+int SOCKS5ClientSocket::DoGreetRead() {
+ next_state_ = STATE_GREET_READ_COMPLETE;
+ size_t handshake_buf_len = kGreetReadHeaderSize - bytes_received_;
+ handshake_buf_ = new IOBuffer(handshake_buf_len);
+ return transport_->Read(handshake_buf_, handshake_buf_len, &io_callback_);
+}
+
+int SOCKS5ClientSocket::DoGreetReadComplete(int result) {
+ if (result < 0)
+ return result;
+
+ if (result == 0)
+ return ERR_CONNECTION_CLOSED; // Unexpected socket close
+
+ bytes_received_ += result;
+ buffer_.append(handshake_buf_->data(), result);
+ if (bytes_received_ < kGreetReadHeaderSize) {
+ next_state_ = STATE_GREET_READ;
+ return OK;
+ }
+
+ // Got the greet data.
+ if (buffer_[0] != kSOCKS5Version || buffer_[1] != 0x00)
+ return ERR_INVALID_RESPONSE; // Unknown error
+
+ buffer_.clear();
+ next_state_ = STATE_HANDSHAKE_WRITE;
+ return OK;
+}
+
+int SOCKS5ClientSocket::BuildHandshakeWriteBuffer(std::string* handshake)
+ const {
+ DCHECK_NE(kEndPointUnresolved, address_type_);
+ DCHECK(handshake->empty());
+
+ handshake->push_back(kSOCKS5Version);
+ handshake->push_back(kTunnelCommand); // Connect command
+ handshake->push_back(kNullByte); // Reserved null
+
+ handshake->push_back(address_type_); // The type of connection
+ if (address_type_ == kEndPointFailedDomain) {
+ if(256 <= host_request_info_.hostname().size())
+ return ERR_ADDRESS_INVALID;
+
+ // First add the size of the hostname, followed by the hostname.
+ handshake->push_back(static_cast<unsigned char>(
+ host_request_info_.hostname().size()));
+ handshake->append(host_request_info_.hostname());
+
+ } else if (address_type_ == kEndPointResolvedIPv4) {
+ struct sockaddr_in* ipv4_host =
+ reinterpret_cast<struct sockaddr_in*>(addresses_.head()->ai_addr);
+ handshake->append(reinterpret_cast<char*>(&ipv4_host->sin_addr),
+ sizeof(ipv4_host->sin_addr));
+
+ } else if (address_type_ == kEndPointResolvedIPv6) {
+ struct sockaddr_in6* ipv6_host =
+ reinterpret_cast<struct sockaddr_in6*>(addresses_.head()->ai_addr);
+ handshake->append(reinterpret_cast<char*>(&ipv6_host->sin6_addr),
+ sizeof(ipv6_host->sin6_addr));
+
+ } else {
+ NOTREACHED();
+ }
+
+ uint16 nw_port = htons(host_request_info_.port());
+ handshake->append(reinterpret_cast<char*>(&nw_port), sizeof(nw_port));
+ return OK;
+}
+
+// Writes the SOCKS handshake data to the underlying socket connection.
+int SOCKS5ClientSocket::DoHandshakeWrite() {
+ next_state_ = STATE_HANDSHAKE_WRITE_COMPLETE;
+
+ if (buffer_.empty()) {
+ int rv = BuildHandshakeWriteBuffer(&buffer_);
+ if (rv != OK)
+ return rv;
+ bytes_sent_ = 0;
+ }
+
+ int handshake_buf_len = buffer_.size() - bytes_sent_;
+ DCHECK_LT(0, handshake_buf_len);
+ handshake_buf_ = new IOBuffer(handshake_buf_len);
+ memcpy(handshake_buf_->data(), &buffer_[bytes_sent_],
+ handshake_buf_len);
+ return transport_->Write(handshake_buf_, handshake_buf_len, &io_callback_);
+}
+
+int SOCKS5ClientSocket::DoHandshakeWriteComplete(int result) {
+ DCHECK_NE(kEndPointUnresolved, address_type_);
+
+ if (result < 0)
+ return result;
+
+ // We ignore the case when result is 0, since the underlying Write
+ // may return spurious writes while waiting on the socket.
+
+ bytes_sent_ += result;
+ if (bytes_sent_ == buffer_.size()) {
+ next_state_ = STATE_HANDSHAKE_READ;
+ buffer_.clear();
+ } else if (bytes_sent_ < buffer_.size()) {
+ next_state_ = STATE_HANDSHAKE_WRITE;
+ } else {
+ NOTREACHED();
+ }
+
+ return OK;
+}
+
+int SOCKS5ClientSocket::DoHandshakeRead() {
+ DCHECK_NE(kEndPointUnresolved, address_type_);
+
+ next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
+
+ if (buffer_.empty()) {
+ bytes_received_ = 0;
+ read_header_size = kReadHeaderSize;
+ }
+
+ int handshake_buf_len = read_header_size - bytes_received_;
+ handshake_buf_ = new IOBuffer(handshake_buf_len);
+ return transport_->Read(handshake_buf_, handshake_buf_len, &io_callback_);
+}
+
+int SOCKS5ClientSocket::DoHandshakeReadComplete(int result) {
+ DCHECK_NE(kEndPointUnresolved, address_type_);
+
+ if (result < 0)
+ return result;
+
+ // The underlying socket closed unexpectedly.
+ if (result == 0)
+ return ERR_CONNECTION_CLOSED;
+
+ buffer_.append(handshake_buf_->data(), result);
+ bytes_received_ += result;
+
+ // When the first few bytes are read, check how many more are required
+ // and accordingly increase them
+ if (bytes_received_ == kReadHeaderSize) {
+ // TODO(arindam): add error codes to net/error_list.h
+ if (buffer_[0] != kSOCKS5Version || buffer_[2] != kNullByte)
+ return ERR_INVALID_RESPONSE;
+ if (buffer_[1] != 0x00)
+ return ERR_FAILED;
+
+ // We check the type of IP/Domain the server returns and accordingly
+ // increase the size of the response. For domains, we need to read the
+ // size of the domain, so the initial request size is upto the domain
+ // size. Since for IPv4/IPv6 the size is fixed and hence no 'size' is
+ // read, we substract 1 byte from the additional request size.
+ SocksEndPointAddressType address_type =
+ static_cast<SocksEndPointAddressType>(buffer_[3]);
+ if (address_type == kEndPointFailedDomain)
+ read_header_size += static_cast<uint8>(buffer_[4]);
+ else if (address_type == kEndPointResolvedIPv4)
+ read_header_size += sizeof(struct in_addr) - 1;
+ else if (address_type == kEndPointResolvedIPv6)
+ read_header_size += sizeof(struct in6_addr) - 1;
+ else
+ return ERR_INVALID_RESPONSE;
+
+ read_header_size += 2; // for the port.
+ next_state_ = STATE_HANDSHAKE_READ;
+ return OK;
+ }
+
+ // When the final bytes are read, setup handshake. We ignore the rest
+ // of the response since they represent the SOCKSv5 endpoint and have
+ // no use when doing a tunnel connection.
+ if (bytes_received_ == read_header_size) {
+ completed_handshake_ = true;
+ buffer_.clear();
+ next_state_ = STATE_NONE;
+ return OK;
+ }
+
+ next_state_ = STATE_HANDSHAKE_READ;
+ return OK;
+}
+
+#if defined(OS_LINUX)
+int SOCKS5ClientSocket::GetPeerName(struct sockaddr* name,
+ socklen_t* namelen) {
+ return transport_->GetPeerName(name, namelen);
+}
+#endif
+
+} // namespace net
+
diff --git a/net/socket/socks5_client_socket.h b/net/socket/socks5_client_socket.h
new file mode 100644
index 0000000..1a5672d
--- /dev/null
+++ b/net/socket/socks5_client_socket.h
@@ -0,0 +1,151 @@
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef NET_SOCKET_SOCKS5_CLIENT_SOCKET_H_
+#define NET_SOCKET_SOCKS5_CLIENT_SOCKET_H_
+
+#include <string>
+
+#include "base/logging.h"
+#include "base/ref_counted.h"
+#include "base/scoped_ptr.h"
+#include "googleurl/src/gurl.h"
+#include "net/base/address_list.h"
+#include "net/base/completion_callback.h"
+#include "net/base/host_resolver.h"
+#include "net/base/net_errors.h"
+#include "net/socket/client_socket.h"
+#include "testing/gtest/include/gtest/gtest_prod.h"
+
+namespace net {
+
+// This ClientSocket is used to setup a SOCKSv5 handshake with a socks proxy.
+// Currently no SOCKSv5 authentication is supported.
+class SOCKS5ClientSocket : public ClientSocket {
+ public:
+ // Takes ownership of the |transport_socket|, which should already be
+ // connected by the time Connect() is called.
+ //
+ // |req_info| contains the hostname and port to which the socket above will
+ // communicate to via the SOCKS layer.
+ SOCKS5ClientSocket(ClientSocket* transport_socket,
+ const HostResolver::RequestInfo& req_info,
+ HostResolver* host_resolver);
+
+ // On destruction Disconnect() is called.
+ virtual ~SOCKS5ClientSocket();
+
+ // ClientSocket methods:
+
+ // Does the SOCKS handshake and completes the protocol.
+ virtual int Connect(CompletionCallback* callback);
+ virtual void Disconnect();
+ virtual bool IsConnected() const;
+ virtual bool IsConnectedAndIdle() const;
+
+ // Socket methods:
+ virtual int Read(IOBuffer* buf, int buf_len, CompletionCallback* callback);
+ virtual int Write(IOBuffer* buf, int buf_len, CompletionCallback* callback);
+
+#if defined(OS_LINUX)
+ virtual int GetPeerName(struct sockaddr* name, socklen_t* namelen);
+#endif
+
+ private:
+ FRIEND_TEST(SOCKS5ClientSocketTest, IPv6Domain);
+ FRIEND_TEST(SOCKS5ClientSocketTest, FailedDNS);
+ FRIEND_TEST(SOCKS5ClientSocketTest, CompleteHandshake);
+
+ enum State {
+ STATE_RESOLVE_HOST,
+ STATE_RESOLVE_HOST_COMPLETE,
+ STATE_GREET_WRITE,
+ STATE_GREET_WRITE_COMPLETE,
+ STATE_GREET_READ,
+ STATE_GREET_READ_COMPLETE,
+ STATE_HANDSHAKE_WRITE,
+ STATE_HANDSHAKE_WRITE_COMPLETE,
+ STATE_HANDSHAKE_READ,
+ STATE_HANDSHAKE_READ_COMPLETE,
+ STATE_NONE,
+ };
+
+ // State of the SOCKSv5 handshake. Before host resolution all connections
+ // are kEndPointFailedDomain. If DNS lookup fails, we move to
+ // kEndPointFailedDomain, otherwise the IPv4/IPv6 address as resolved.
+ enum SocksEndPointAddressType {
+ kEndPointUnresolved,
+ kEndPointFailedDomain = 0x03,
+ kEndPointResolvedIPv4 = 0x01,
+ kEndPointResolvedIPv6 = 0x04,
+ };
+
+ static const unsigned int kGreetReadHeaderSize;
+ static const unsigned int kWriteHeaderSize;
+ static const unsigned int kReadHeaderSize;
+ static const uint8 kSOCKS5Version;
+ static const uint8 kTunnelCommand;
+ static const uint8 kNullByte;
+
+ void DoCallback(int result);
+ void OnIOComplete(int result);
+
+ int DoLoop(int last_io_result);
+ int DoResolveHost();
+ int DoResolveHostComplete(int result);
+ int DoHandshakeRead();
+ int DoHandshakeReadComplete(int result);
+ int DoHandshakeWrite();
+ int DoHandshakeWriteComplete(int result);
+ int DoGreetRead();
+ int DoGreetReadComplete(int result);
+ int DoGreetWrite();
+ int DoGreetWriteComplete(int result);
+
+ // Writes the SOCKS handshake buffer into |handshake|
+ // and return OK on success.
+ int BuildHandshakeWriteBuffer(std::string* handshake) const;
+
+ CompletionCallbackImpl<SOCKS5ClientSocket> io_callback_;
+
+ // Stores the underlying socket.
+ scoped_ptr<ClientSocket> transport_;
+
+ State next_state_;
+ SocksEndPointAddressType address_type_;
+
+ // Stores the callback to the layer above, called on completing Connect().
+ CompletionCallback* user_callback_;
+
+ // This IOBuffer is used by the class to read and write
+ // SOCKS handshake data. The length contains the expected size to
+ // read or write.
+ scoped_refptr<IOBuffer> handshake_buf_;
+
+ // While writing, this buffer stores the complete write handshake data.
+ // While reading, it stores the handshake information received so far.
+ std::string buffer_;
+
+ // This becomes true when the SOCKS handshake has completed and the
+ // overlying connection is free to communicate.
+ bool completed_handshake_;
+
+ // These contain the bytes sent / received by the SOCKS handshake.
+ size_t bytes_sent_;
+ size_t bytes_received_;
+
+ size_t read_header_size;
+
+ // Used to resolve the hostname to which the SOCKS proxy will connect.
+ SingleRequestHostResolver host_resolver_;
+ AddressList addresses_;
+ HostResolver::RequestInfo host_request_info_;
+
+ DISALLOW_COPY_AND_ASSIGN(SOCKS5ClientSocket);
+};
+
+} // namespace net
+
+#endif // NET_SOCKET_SOCKS5_CLIENT_SOCKET_H_
+
diff --git a/net/socket/socks5_client_socket_unittest.cc b/net/socket/socks5_client_socket_unittest.cc
new file mode 100644
index 0000000..e62f191
--- /dev/null
+++ b/net/socket/socks5_client_socket_unittest.cc
@@ -0,0 +1,307 @@
+// Copyright (c) 2009 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "net/socket/socks5_client_socket.h"
+
+#include <map>
+#include "build/build_config.h"
+#if defined(OS_WIN)
+#include <ws2tcpip.h>
+#elif defined(OS_POSIX)
+#include <netdb.h>
+#endif
+#include "net/base/address_list.h"
+#include "net/base/host_resolver_unittest.h"
+#include "net/base/test_completion_callback.h"
+#include "net/base/winsock_init.h"
+#include "net/socket/client_socket_factory.h"
+#include "net/socket/socket_test_util.h"
+#include "net/socket/tcp_client_socket.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "testing/platform_test.h"
+
+//-----------------------------------------------------------------------------
+
+namespace net {
+
+// Base class to test SOCKS5ClientSocket
+class SOCKS5ClientSocketTest : public PlatformTest {
+ public:
+ SOCKS5ClientSocketTest();
+ // Create a SOCKSClientSocket on top of a MockSocket.
+ SOCKS5ClientSocket* BuildMockSocket(MockRead reads[],
+ MockWrite writes[],
+ const std::string& hostname,
+ int port);
+ virtual void SetUp();
+
+ protected:
+ scoped_ptr<SOCKS5ClientSocket> user_sock_;
+ AddressList address_list_;
+ ClientSocket* tcp_sock_;
+ ScopedHostMapper host_mapper_;
+ TestCompletionCallback callback_;
+ scoped_refptr<RuleBasedHostMapper> mapper_;
+ scoped_refptr<HostResolver> host_resolver_;
+ scoped_ptr<MockSocket> mock_socket_;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SOCKS5ClientSocketTest);
+};
+
+SOCKS5ClientSocketTest::SOCKS5ClientSocketTest()
+ : host_resolver_(new HostResolver(0, 0)) {
+}
+
+// Set up platform before every test case
+void SOCKS5ClientSocketTest::SetUp() {
+ PlatformTest::SetUp();
+
+ // Resolve the "localhost" AddressList used by the TCP connection to connect.
+ scoped_refptr<HostResolver> resolver = new HostResolver();
+ HostResolver::RequestInfo info("www.socks-proxy.com", 1080);
+ int rv = resolver->Resolve(info, &address_list_, NULL, NULL);
+ ASSERT_EQ(OK, rv);
+
+ // Create a new host mapping for the duration of this test case only.
+ mapper_ = new RuleBasedHostMapper();
+ host_mapper_.Init(mapper_);
+}
+
+SOCKS5ClientSocket* SOCKS5ClientSocketTest::BuildMockSocket(
+ MockRead reads[],
+ MockWrite writes[],
+ const std::string& hostname,
+ int port) {
+
+ TestCompletionCallback callback;
+ mock_socket_.reset(new StaticMockSocket(reads, writes));
+ tcp_sock_ = new MockTCPClientSocket(address_list_, mock_socket_.get());
+
+ int rv = tcp_sock_->Connect(&callback);
+ EXPECT_EQ(ERR_IO_PENDING, rv);
+ rv = callback.WaitForResult();
+ EXPECT_EQ(OK, rv);
+ EXPECT_TRUE(tcp_sock_->IsConnected());
+
+ return new SOCKS5ClientSocket(tcp_sock_,
+ HostResolver::RequestInfo(hostname, port),
+ host_resolver_);
+}
+
+const char kSOCKS5GreetRequest[] = { 0x05, 0x01, 0x00 };
+const char kSOCKS5GreetResponse[] = { 0x05, 0x00 };
+
+const char kSOCKS5OkRequest[] =
+ { 0x05, 0x01, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
+const char kSOCKS5OkResponse[] =
+ { 0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x50 };
+
+const uint16 kNwPort = htons(80);
+
+// Tests a complete SOCKS5 handshake and the disconnection.
+TEST_F(SOCKS5ClientSocketTest, CompleteHandshake) {
+ const std::string payload_write = "random data";
+ const std::string payload_read = "moar random data";
+
+ MockWrite data_writes[] = {
+ MockWrite(true, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)),
+ MockWrite(true, kSOCKS5OkRequest, arraysize(kSOCKS5OkRequest)),
+ MockWrite(true, payload_write.data(), payload_write.size()) };
+ MockRead data_reads[] = {
+ MockRead(true, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)),
+ MockRead(true, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)),
+ MockRead(true, payload_read.data(), payload_read.size()) };
+
+ user_sock_.reset(BuildMockSocket(data_reads, data_writes, "localhost", 80));
+
+ // At this state the TCP connection is completed but not the SOCKS handshake.
+ EXPECT_TRUE(tcp_sock_->IsConnected());
+ EXPECT_FALSE(user_sock_->IsConnected());
+
+ int rv = user_sock_->Connect(&callback_);
+ EXPECT_EQ(ERR_IO_PENDING, rv);
+ EXPECT_FALSE(user_sock_->IsConnected());
+ rv = callback_.WaitForResult();
+
+ EXPECT_EQ(OK, rv);
+ EXPECT_TRUE(user_sock_->IsConnected());
+ EXPECT_EQ(SOCKS5ClientSocket::kEndPointResolvedIPv4,
+ user_sock_->address_type_);
+
+ scoped_refptr<IOBuffer> buffer = new IOBuffer(payload_write.size());
+ memcpy(buffer->data(), payload_write.data(), payload_write.size());
+ rv = user_sock_->Write(buffer, payload_write.size(), &callback_);
+ EXPECT_EQ(ERR_IO_PENDING, rv);
+ rv = callback_.WaitForResult();
+ EXPECT_EQ(static_cast<int>(payload_write.size()), rv);
+
+ buffer = new IOBuffer(payload_read.size());
+ rv = user_sock_->Read(buffer, payload_read.size(), &callback_);
+ EXPECT_EQ(ERR_IO_PENDING, rv);
+ rv = callback_.WaitForResult();
+ EXPECT_EQ(static_cast<int>(payload_read.size()), rv);
+ EXPECT_EQ(payload_read, std::string(buffer->data(), payload_read.size()));
+
+ user_sock_->Disconnect();
+ EXPECT_FALSE(tcp_sock_->IsConnected());
+ EXPECT_FALSE(user_sock_->IsConnected());
+}
+
+// Tries to connect to a DNS which fails domain lookup.
+TEST_F(SOCKS5ClientSocketTest, FailedDNS) {
+ const std::string hostname = "unresolved.ipv4.address";
+ const char kSOCKS5DomainRequest[] = { 0x05, 0x01, 0x00, 0x03 };
+
+ mapper_->AddSimulatedFailure(hostname.c_str());
+
+ std::string request(kSOCKS5DomainRequest,
+ arraysize(kSOCKS5DomainRequest));
+ request.push_back(hostname.size());
+ request.append(hostname);
+ request.append(reinterpret_cast<const char*>(&kNwPort), sizeof(kNwPort));
+
+ MockWrite data_writes[] = {
+ MockWrite(false, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)),
+ MockWrite(false, request.data(), request.size()) };
+ MockRead data_reads[] = {
+ MockRead(false, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)),
+ MockRead(false, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)) };
+
+ user_sock_.reset(BuildMockSocket(data_reads, data_writes, hostname, 80));
+
+ int rv = user_sock_->Connect(&callback_);
+ EXPECT_EQ(ERR_IO_PENDING, rv);
+ rv = callback_.WaitForResult();
+ EXPECT_EQ(OK, rv);
+ EXPECT_TRUE(user_sock_->IsConnected());
+ EXPECT_EQ(SOCKS5ClientSocket::kEndPointFailedDomain,
+ user_sock_->address_type_);
+}
+
+// Tries to connect to a domain that resolves to IPv6.
+TEST_F(SOCKS5ClientSocketTest, IPv6Domain) {
+ const std::string hostname = "an.ipv6.address";
+ const char kSOCKS5IPv6Request[] = { 0x05, 0x01, 0x00, 0x04 };
+ const uint8 ipv6_addr[] = { 0x20, 0x01, 0x0d, 0xb8, 0x87, 0x14, 0x3a, 0x90,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x000, 0x00, 0x12 };
+
+ mapper_->AddRule(hostname.c_str(), "2001:db8:8714:3a90::12");
+
+ AddressList address_list;
+ scoped_refptr<HostResolver> resolver = new HostResolver();
+ HostResolver::RequestInfo info(hostname, 80);
+ int rv = resolver->Resolve(info, &address_list, NULL, NULL);
+ if (rv != OK || !address_list.head()) {
+ // This machine does not support IPv6. We skip this test altogether.
+ // TODO(arindam): create a MockIPv6HostResolver to manually
+ // populate the |address_list| in case of a machine with no IPv6 suppport.
+ return;
+ }
+
+ std::string request(kSOCKS5IPv6Request,
+ arraysize(kSOCKS5IPv6Request));
+ request.append(reinterpret_cast<const char*>(&ipv6_addr), sizeof(ipv6_addr));
+ request.append(reinterpret_cast<const char*>(&kNwPort), sizeof(kNwPort));
+
+ MockWrite data_writes[] = {
+ MockWrite(false, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)),
+ MockWrite(false, request.data(), request.size()) };
+ MockRead data_reads[] = {
+ MockRead(false, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)),
+ MockRead(false, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)) };
+
+ user_sock_.reset(BuildMockSocket(data_reads, data_writes, hostname, 80));
+
+ rv = user_sock_->Connect(&callback_);
+ EXPECT_EQ(ERR_IO_PENDING, rv);
+ rv = callback_.WaitForResult();
+ EXPECT_EQ(OK, rv);
+ EXPECT_TRUE(user_sock_->IsConnected());
+ EXPECT_EQ(SOCKS5ClientSocket::kEndPointResolvedIPv6,
+ user_sock_->address_type_);
+}
+
+TEST_F(SOCKS5ClientSocketTest, PartialReadWrites) {
+ const std::string hostname = "www.google.com";
+
+ // Test for partial greet request write
+ {
+ const char partial1[] = { 0x05, 0x01 };
+ const char partial2[] = { 0x00 };
+ MockWrite data_writes[] = {
+ MockWrite(true, arraysize(partial1)),
+ MockWrite(true, partial2, arraysize(partial2)),
+ MockWrite(true, kSOCKS5OkRequest, arraysize(kSOCKS5OkRequest)) };
+ MockRead data_reads[] = {
+ MockRead(true, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)),
+ MockRead(true, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)) };
+ user_sock_.reset(BuildMockSocket(data_reads, data_writes, hostname, 80));
+ int rv = user_sock_->Connect(&callback_);
+ EXPECT_EQ(ERR_IO_PENDING, rv);
+ rv = callback_.WaitForResult();
+ EXPECT_EQ(OK, rv);
+ EXPECT_TRUE(user_sock_->IsConnected());
+ }
+
+ // Test for partial greet response read
+ {
+ const char partial1[] = { 0x05 };
+ const char partial2[] = { 0x00 };
+ MockWrite data_writes[] = {
+ MockWrite(true, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)),
+ MockWrite(true, kSOCKS5OkRequest, arraysize(kSOCKS5OkRequest)) };
+ MockRead data_reads[] = {
+ MockRead(true, partial1, arraysize(partial1)),
+ MockRead(true, partial2, arraysize(partial2)),
+ MockRead(true, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)) };
+ user_sock_.reset(BuildMockSocket(data_reads, data_writes, hostname, 80));
+ int rv = user_sock_->Connect(&callback_);
+ EXPECT_EQ(ERR_IO_PENDING, rv);
+ rv = callback_.WaitForResult();
+ EXPECT_EQ(OK, rv);
+ EXPECT_TRUE(user_sock_->IsConnected());
+ }
+
+ // Test for partial handshake request write
+ {
+ const char partial1[] = { 0x05, 0x01, 0x00 };
+ const char partial2[] = { 0x01, 127, 0, 0, 1, 0x00, 0x50 };
+ MockWrite data_writes[] = {
+ MockWrite(true, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)),
+ MockWrite(true, arraysize(partial1)),
+ MockWrite(true, partial2, arraysize(partial2)) };
+ MockRead data_reads[] = {
+ MockRead(true, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)),
+ MockRead(true, kSOCKS5OkResponse, arraysize(kSOCKS5OkResponse)) };
+ user_sock_.reset(BuildMockSocket(data_reads, data_writes, hostname, 80));
+ int rv = user_sock_->Connect(&callback_);
+ EXPECT_EQ(ERR_IO_PENDING, rv);
+ rv = callback_.WaitForResult();
+ EXPECT_EQ(OK, rv);
+ EXPECT_TRUE(user_sock_->IsConnected());
+ }
+
+ // Test for partial handshake response read
+ {
+ const char partial1[] = { 0x05, 0x00, 0x00, 0x01, 127, 0 };
+ const char partial2[] = { 0, 1, 0x00, 0x50 };
+ MockWrite data_writes[] = {
+ MockWrite(true, kSOCKS5GreetRequest, arraysize(kSOCKS5GreetRequest)),
+ MockWrite(true, kSOCKS5OkRequest, arraysize(kSOCKS5OkRequest)) };
+ MockRead data_reads[] = {
+ MockRead(true, kSOCKS5GreetResponse, arraysize(kSOCKS5GreetResponse)),
+ MockRead(true, partial1, arraysize(partial1)),
+ MockRead(true, partial2, arraysize(partial2)) };
+ user_sock_.reset(BuildMockSocket(data_reads, data_writes, hostname, 80));
+ int rv = user_sock_->Connect(&callback_);
+ EXPECT_EQ(ERR_IO_PENDING, rv);
+ rv = callback_.WaitForResult();
+ EXPECT_EQ(OK, rv);
+ EXPECT_TRUE(user_sock_->IsConnected());
+ }
+}
+
+} // namespace net
+