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/socks_client_socket.h"
7 #include "base/basictypes.h"
9 #include "base/compiler_specific.h"
10 #include "base/sys_byteorder.h"
11 #include "net/base/io_buffer.h"
12 #include "net/base/net_log.h"
13 #include "net/base/net_util.h"
14 #include "net/socket/client_socket_handle.h"
18 // Every SOCKS server requests a user-id from the client. It is optional
19 // and we send an empty string.
20 static const char kEmptyUserId[] = "";
22 // For SOCKS4, the client sends 8 bytes plus the size of the user-id.
23 static const unsigned int kWriteHeaderSize = 8;
25 // For SOCKS4 the server sends 8 bytes for acknowledgement.
26 static const unsigned int kReadHeaderSize = 8;
28 // Server Response codes for SOCKS.
29 static const uint8 kServerResponseOk = 0x5A;
30 static const uint8 kServerResponseRejected = 0x5B;
31 static const uint8 kServerResponseNotReachable = 0x5C;
32 static const uint8 kServerResponseMismatchedUserId = 0x5D;
34 static const uint8 kSOCKSVersion4 = 0x04;
35 static const uint8 kSOCKSStreamRequest = 0x01;
37 // A struct holding the essential details of the SOCKS4 Server Request.
38 // The port in the header is stored in network byte order.
39 struct SOCKS4ServerRequest {
45 COMPILE_ASSERT(sizeof(SOCKS4ServerRequest) == kWriteHeaderSize,
46 socks4_server_request_struct_wrong_size);
48 // A struct holding details of the SOCKS4 Server Response.
49 struct SOCKS4ServerResponse {
55 COMPILE_ASSERT(sizeof(SOCKS4ServerResponse) == kReadHeaderSize,
56 socks4_server_response_struct_wrong_size);
58 SOCKSClientSocket::SOCKSClientSocket(
59 scoped_ptr<ClientSocketHandle> transport_socket,
60 const HostResolver::RequestInfo& req_info,
61 RequestPriority priority,
62 HostResolver* host_resolver)
63 : transport_(transport_socket.Pass()),
64 next_state_(STATE_NONE),
65 completed_handshake_(false),
68 host_resolver_(host_resolver),
69 host_request_info_(req_info),
71 net_log_(transport_->socket()->NetLog()) {}
73 SOCKSClientSocket::~SOCKSClientSocket() {
77 int SOCKSClientSocket::Connect(const CompletionCallback& callback) {
78 DCHECK(transport_.get());
79 DCHECK(transport_->socket());
80 DCHECK_EQ(STATE_NONE, next_state_);
81 DCHECK(user_callback_.is_null());
83 // If already connected, then just return OK.
84 if (completed_handshake_)
87 next_state_ = STATE_RESOLVE_HOST;
89 net_log_.BeginEvent(NetLog::TYPE_SOCKS_CONNECT);
92 if (rv == ERR_IO_PENDING) {
93 user_callback_ = callback;
95 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SOCKS_CONNECT, rv);
100 void SOCKSClientSocket::Disconnect() {
101 completed_handshake_ = false;
102 host_resolver_.Cancel();
103 transport_->socket()->Disconnect();
105 // Reset other states to make sure they aren't mistakenly used later.
106 // These are the states initialized by Connect().
107 next_state_ = STATE_NONE;
108 user_callback_.Reset();
111 bool SOCKSClientSocket::IsConnected() const {
112 return completed_handshake_ && transport_->socket()->IsConnected();
115 bool SOCKSClientSocket::IsConnectedAndIdle() const {
116 return completed_handshake_ && transport_->socket()->IsConnectedAndIdle();
119 const BoundNetLog& SOCKSClientSocket::NetLog() const {
123 void SOCKSClientSocket::SetSubresourceSpeculation() {
124 if (transport_.get() && transport_->socket()) {
125 transport_->socket()->SetSubresourceSpeculation();
131 void SOCKSClientSocket::SetOmniboxSpeculation() {
132 if (transport_.get() && transport_->socket()) {
133 transport_->socket()->SetOmniboxSpeculation();
139 bool SOCKSClientSocket::WasEverUsed() const {
140 if (transport_.get() && transport_->socket()) {
141 return transport_->socket()->WasEverUsed();
147 bool SOCKSClientSocket::UsingTCPFastOpen() const {
148 if (transport_.get() && transport_->socket()) {
149 return transport_->socket()->UsingTCPFastOpen();
155 bool SOCKSClientSocket::WasNpnNegotiated() const {
156 if (transport_.get() && transport_->socket()) {
157 return transport_->socket()->WasNpnNegotiated();
163 NextProto SOCKSClientSocket::GetNegotiatedProtocol() const {
164 if (transport_.get() && transport_->socket()) {
165 return transport_->socket()->GetNegotiatedProtocol();
168 return kProtoUnknown;
171 bool SOCKSClientSocket::GetSSLInfo(SSLInfo* ssl_info) {
172 if (transport_.get() && transport_->socket()) {
173 return transport_->socket()->GetSSLInfo(ssl_info);
180 // Read is called by the transport layer above to read. This can only be done
181 // if the SOCKS handshake is complete.
182 int SOCKSClientSocket::Read(IOBuffer* buf, int buf_len,
183 const CompletionCallback& callback) {
184 DCHECK(completed_handshake_);
185 DCHECK_EQ(STATE_NONE, next_state_);
186 DCHECK(user_callback_.is_null());
188 return transport_->socket()->Read(buf, buf_len, callback);
191 // Write is called by the transport layer. This can only be done if the
192 // SOCKS handshake is complete.
193 int SOCKSClientSocket::Write(IOBuffer* buf, int buf_len,
194 const CompletionCallback& callback) {
195 DCHECK(completed_handshake_);
196 DCHECK_EQ(STATE_NONE, next_state_);
197 DCHECK(user_callback_.is_null());
199 return transport_->socket()->Write(buf, buf_len, callback);
202 bool SOCKSClientSocket::SetReceiveBufferSize(int32 size) {
203 return transport_->socket()->SetReceiveBufferSize(size);
206 bool SOCKSClientSocket::SetSendBufferSize(int32 size) {
207 return transport_->socket()->SetSendBufferSize(size);
210 void SOCKSClientSocket::DoCallback(int result) {
211 DCHECK_NE(ERR_IO_PENDING, result);
212 DCHECK(!user_callback_.is_null());
214 // Since Run() may result in Read being called,
215 // clear user_callback_ up front.
216 CompletionCallback c = user_callback_;
217 user_callback_.Reset();
218 DVLOG(1) << "Finished setting up SOCKS handshake";
222 void SOCKSClientSocket::OnIOComplete(int result) {
223 DCHECK_NE(STATE_NONE, next_state_);
224 int rv = DoLoop(result);
225 if (rv != ERR_IO_PENDING) {
226 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SOCKS_CONNECT, rv);
231 int SOCKSClientSocket::DoLoop(int last_io_result) {
232 DCHECK_NE(next_state_, STATE_NONE);
233 int rv = last_io_result;
235 State state = next_state_;
236 next_state_ = STATE_NONE;
238 case STATE_RESOLVE_HOST:
240 rv = DoResolveHost();
242 case STATE_RESOLVE_HOST_COMPLETE:
243 rv = DoResolveHostComplete(rv);
245 case STATE_HANDSHAKE_WRITE:
247 rv = DoHandshakeWrite();
249 case STATE_HANDSHAKE_WRITE_COMPLETE:
250 rv = DoHandshakeWriteComplete(rv);
252 case STATE_HANDSHAKE_READ:
254 rv = DoHandshakeRead();
256 case STATE_HANDSHAKE_READ_COMPLETE:
257 rv = DoHandshakeReadComplete(rv);
260 NOTREACHED() << "bad state";
264 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
268 int SOCKSClientSocket::DoResolveHost() {
269 next_state_ = STATE_RESOLVE_HOST_COMPLETE;
270 // SOCKS4 only supports IPv4 addresses, so only try getting the IPv4
271 // addresses for the target host.
272 host_request_info_.set_address_family(ADDRESS_FAMILY_IPV4);
273 return host_resolver_.Resolve(
277 base::Bind(&SOCKSClientSocket::OnIOComplete, base::Unretained(this)),
281 int SOCKSClientSocket::DoResolveHostComplete(int result) {
283 // Resolving the hostname failed; fail the request rather than automatically
284 // falling back to SOCKS4a (since it can be confusing to see invalid IP
285 // addresses being sent to the SOCKS4 server when it doesn't support 4A.)
289 next_state_ = STATE_HANDSHAKE_WRITE;
293 // Builds the buffer that is to be sent to the server.
294 const std::string SOCKSClientSocket::BuildHandshakeWriteBuffer() const {
295 SOCKS4ServerRequest request;
296 request.version = kSOCKSVersion4;
297 request.command = kSOCKSStreamRequest;
298 request.nw_port = base::HostToNet16(host_request_info_.port());
300 DCHECK(!addresses_.empty());
301 const IPEndPoint& endpoint = addresses_.front();
303 // We disabled IPv6 results when resolving the hostname, so none of the
304 // results in the list will be IPv6.
305 // TODO(eroman): we only ever use the first address in the list. It would be
306 // more robust to try all the IP addresses we have before
307 // failing the connect attempt.
308 CHECK_EQ(ADDRESS_FAMILY_IPV4, endpoint.GetFamily());
309 CHECK_LE(endpoint.address().size(), sizeof(request.ip));
310 memcpy(&request.ip, &endpoint.address()[0], endpoint.address().size());
312 DVLOG(1) << "Resolved Host is : " << endpoint.ToStringWithoutPort();
314 std::string handshake_data(reinterpret_cast<char*>(&request),
316 handshake_data.append(kEmptyUserId, arraysize(kEmptyUserId));
318 return handshake_data;
321 // Writes the SOCKS handshake data to the underlying socket connection.
322 int SOCKSClientSocket::DoHandshakeWrite() {
323 next_state_ = STATE_HANDSHAKE_WRITE_COMPLETE;
325 if (buffer_.empty()) {
326 buffer_ = BuildHandshakeWriteBuffer();
330 int handshake_buf_len = buffer_.size() - bytes_sent_;
331 DCHECK_GT(handshake_buf_len, 0);
332 handshake_buf_ = new IOBuffer(handshake_buf_len);
333 memcpy(handshake_buf_->data(), &buffer_[bytes_sent_],
335 return transport_->socket()->Write(
336 handshake_buf_.get(),
338 base::Bind(&SOCKSClientSocket::OnIOComplete, base::Unretained(this)));
341 int SOCKSClientSocket::DoHandshakeWriteComplete(int result) {
345 // We ignore the case when result is 0, since the underlying Write
346 // may return spurious writes while waiting on the socket.
348 bytes_sent_ += result;
349 if (bytes_sent_ == buffer_.size()) {
350 next_state_ = STATE_HANDSHAKE_READ;
352 } else if (bytes_sent_ < buffer_.size()) {
353 next_state_ = STATE_HANDSHAKE_WRITE;
355 return ERR_UNEXPECTED;
361 int SOCKSClientSocket::DoHandshakeRead() {
362 next_state_ = STATE_HANDSHAKE_READ_COMPLETE;
364 if (buffer_.empty()) {
368 int handshake_buf_len = kReadHeaderSize - bytes_received_;
369 handshake_buf_ = new IOBuffer(handshake_buf_len);
370 return transport_->socket()->Read(
371 handshake_buf_.get(),
373 base::Bind(&SOCKSClientSocket::OnIOComplete, base::Unretained(this)));
376 int SOCKSClientSocket::DoHandshakeReadComplete(int result) {
380 // The underlying socket closed unexpectedly.
382 return ERR_CONNECTION_CLOSED;
384 if (bytes_received_ + result > kReadHeaderSize) {
385 // TODO(eroman): Describe failure in NetLog.
386 return ERR_SOCKS_CONNECTION_FAILED;
389 buffer_.append(handshake_buf_->data(), result);
390 bytes_received_ += result;
391 if (bytes_received_ < kReadHeaderSize) {
392 next_state_ = STATE_HANDSHAKE_READ;
396 const SOCKS4ServerResponse* response =
397 reinterpret_cast<const SOCKS4ServerResponse*>(buffer_.data());
399 if (response->reserved_null != 0x00) {
400 LOG(ERROR) << "Unknown response from SOCKS server.";
401 return ERR_SOCKS_CONNECTION_FAILED;
404 switch (response->code) {
405 case kServerResponseOk:
406 completed_handshake_ = true;
408 case kServerResponseRejected:
409 LOG(ERROR) << "SOCKS request rejected or failed";
410 return ERR_SOCKS_CONNECTION_FAILED;
411 case kServerResponseNotReachable:
412 LOG(ERROR) << "SOCKS request failed because client is not running "
413 << "identd (or not reachable from the server)";
414 return ERR_SOCKS_CONNECTION_HOST_UNREACHABLE;
415 case kServerResponseMismatchedUserId:
416 LOG(ERROR) << "SOCKS request failed because client's identd could "
417 << "not confirm the user ID string in the request";
418 return ERR_SOCKS_CONNECTION_FAILED;
420 LOG(ERROR) << "SOCKS server sent unknown response";
421 return ERR_SOCKS_CONNECTION_FAILED;
424 // Note: we ignore the last 6 bytes as specified by the SOCKS protocol
427 int SOCKSClientSocket::GetPeerAddress(IPEndPoint* address) const {
428 return transport_->socket()->GetPeerAddress(address);
431 int SOCKSClientSocket::GetLocalAddress(IPEndPoint* address) const {
432 return transport_->socket()->GetLocalAddress(address);