1 // Copyright 2014 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 "extensions/browser/api/socket/tls_socket.h"
7 #include "base/callback_helpers.h"
8 #include "base/logging.h"
9 #include "extensions/browser/api/api_resource.h"
10 #include "net/base/address_list.h"
11 #include "net/base/ip_endpoint.h"
12 #include "net/base/net_errors.h"
13 #include "net/base/net_util.h"
14 #include "net/base/rand_callback.h"
15 #include "net/socket/client_socket_factory.h"
16 #include "net/socket/client_socket_handle.h"
17 #include "net/socket/ssl_client_socket.h"
18 #include "net/socket/tcp_client_socket.h"
19 #include "url/url_canon.h"
23 // Returns the SSL protocol version (as a uint16) represented by a string.
24 // Returns 0 if the string is invalid.
25 uint16
SSLProtocolVersionFromString(const std::string
& version_str
) {
26 uint16 version
= 0; // Invalid.
27 if (version_str
== "tls1") {
28 version
= net::SSL_PROTOCOL_VERSION_TLS1
;
29 } else if (version_str
== "tls1.1") {
30 version
= net::SSL_PROTOCOL_VERSION_TLS1_1
;
31 } else if (version_str
== "tls1.2") {
32 version
= net::SSL_PROTOCOL_VERSION_TLS1_2
;
37 void TlsConnectDone(scoped_ptr
<net::SSLClientSocket
> ssl_socket
,
38 const std::string
& extension_id
,
39 const extensions::TLSSocket::SecureCallback
& callback
,
41 DVLOG(1) << "Got back result " << result
<< " " << net::ErrorToString(result
);
43 // No matter how the TLS connection attempt went, the underlying socket's
44 // no longer bound to the original TCPSocket. It belongs to |ssl_socket|,
45 // which is promoted here to a new API-accessible socket (via a TLSSocket
46 // wrapper), or deleted.
47 if (result
!= net::OK
) {
48 callback
.Run(scoped_ptr
<extensions::TLSSocket
>(), result
);
52 // Wrap the StreamSocket in a TLSSocket, which matches the extension socket
53 // API. Set the handle of the socket to the new value, so that it can be
54 // used for read/write/close/etc.
55 scoped_ptr
<extensions::TLSSocket
> wrapper(
56 new extensions::TLSSocket(ssl_socket
.Pass(), extension_id
));
58 // Caller will end up deleting the prior TCPSocket, once it calls
59 // SetSocket(..,wrapper).
60 callback
.Run(wrapper
.Pass(), result
);
65 namespace extensions
{
67 const char kTLSSocketTypeInvalidError
[] =
68 "Cannot listen on a socket that is already connected.";
70 TLSSocket::TLSSocket(scoped_ptr
<net::StreamSocket
> tls_socket
,
71 const std::string
& owner_extension_id
)
72 : ResumableTCPSocket(owner_extension_id
), tls_socket_(tls_socket
.Pass()) {
75 TLSSocket::~TLSSocket() {
79 void TLSSocket::Connect(const net::AddressList
& address
,
80 const CompletionCallback
& callback
) {
81 callback
.Run(net::ERR_CONNECTION_FAILED
);
84 void TLSSocket::Disconnect() {
86 tls_socket_
->Disconnect();
91 void TLSSocket::Read(int count
, const ReadCompletionCallback
& callback
) {
92 DCHECK(!callback
.is_null());
94 if (!read_callback_
.is_null()) {
95 callback
.Run(net::ERR_IO_PENDING
, NULL
);
100 callback
.Run(net::ERR_INVALID_ARGUMENT
, NULL
);
104 if (!tls_socket_
.get() || !IsConnected()) {
105 callback
.Run(net::ERR_SOCKET_NOT_CONNECTED
, NULL
);
109 read_callback_
= callback
;
110 scoped_refptr
<net::IOBuffer
> io_buffer(new net::IOBuffer(count
));
111 // |tls_socket_| is owned by this class and the callback won't be run once
112 // |tls_socket_| is gone (as in an a call to Disconnect()). Therefore, it is
113 // safe to use base::Unretained() here.
114 int result
= tls_socket_
->Read(
118 &TLSSocket::OnReadComplete
, base::Unretained(this), io_buffer
));
120 if (result
!= net::ERR_IO_PENDING
) {
121 OnReadComplete(io_buffer
, result
);
125 void TLSSocket::OnReadComplete(const scoped_refptr
<net::IOBuffer
>& io_buffer
,
127 DCHECK(!read_callback_
.is_null());
128 base::ResetAndReturn(&read_callback_
).Run(result
, io_buffer
);
131 int TLSSocket::WriteImpl(net::IOBuffer
* io_buffer
,
133 const net::CompletionCallback
& callback
) {
134 if (!IsConnected()) {
135 return net::ERR_SOCKET_NOT_CONNECTED
;
137 return tls_socket_
->Write(io_buffer
, io_buffer_size
, callback
);
140 bool TLSSocket::SetKeepAlive(bool enable
, int delay
) {
144 bool TLSSocket::SetNoDelay(bool no_delay
) {
148 int TLSSocket::Listen(const std::string
& address
,
151 std::string
* error_msg
) {
152 *error_msg
= kTLSSocketTypeInvalidError
;
153 return net::ERR_NOT_IMPLEMENTED
;
156 void TLSSocket::Accept(const AcceptCompletionCallback
& callback
) {
157 callback
.Run(net::ERR_FAILED
, NULL
);
160 bool TLSSocket::IsConnected() {
161 return tls_socket_
.get() && tls_socket_
->IsConnected();
164 bool TLSSocket::GetPeerAddress(net::IPEndPoint
* address
) {
165 return IsConnected() && tls_socket_
->GetPeerAddress(address
);
168 bool TLSSocket::GetLocalAddress(net::IPEndPoint
* address
) {
169 return IsConnected() && tls_socket_
->GetLocalAddress(address
);
172 Socket::SocketType
TLSSocket::GetSocketType() const {
173 return Socket::TYPE_TLS
;
177 void TLSSocket::UpgradeSocketToTLS(
179 scoped_refptr
<net::SSLConfigService
> ssl_config_service
,
180 net::CertVerifier
* cert_verifier
,
181 net::TransportSecurityState
* transport_security_state
,
182 const std::string
& extension_id
,
183 api::socket::SecureOptions
* options
,
184 const TLSSocket::SecureCallback
& callback
) {
185 DCHECK_CURRENTLY_ON(content::BrowserThread::IO
);
186 TCPSocket
* tcp_socket
= static_cast<TCPSocket
*>(socket
);
187 scoped_ptr
<net::SSLClientSocket
> null_sock
;
189 if (!tcp_socket
|| tcp_socket
->GetSocketType() != Socket::TYPE_TCP
||
190 !tcp_socket
->ClientStream() || !tcp_socket
->IsConnected() ||
191 tcp_socket
->HasPendingRead()) {
192 DVLOG(1) << "Failing before trying. socket is " << tcp_socket
;
194 DVLOG(1) << "type: " << tcp_socket
->GetSocketType()
195 << ", ClientStream is " << tcp_socket
->ClientStream()
196 << ", IsConnected: " << tcp_socket
->IsConnected()
197 << ", HasPendingRead: " << tcp_socket
->HasPendingRead();
200 null_sock
.Pass(), extension_id
, callback
, net::ERR_INVALID_ARGUMENT
);
204 net::IPEndPoint dest_host_port_pair
;
205 if (!tcp_socket
->GetPeerAddress(&dest_host_port_pair
)) {
206 DVLOG(1) << "Could not get peer address.";
208 null_sock
.Pass(), extension_id
, callback
, net::ERR_INVALID_ARGUMENT
);
212 // Convert any U-LABELs to A-LABELs.
213 url::CanonHostInfo host_info
;
214 std::string canon_host
=
215 net::CanonicalizeHost(tcp_socket
->hostname(), &host_info
);
217 // Canonicalization shouldn't fail: the socket is already connected with a
218 // host, using this hostname.
219 if (host_info
.family
== url::CanonHostInfo::BROKEN
) {
220 DVLOG(1) << "Could not canonicalize hostname";
222 null_sock
.Pass(), extension_id
, callback
, net::ERR_INVALID_ARGUMENT
);
226 net::HostPortPair
host_and_port(canon_host
, dest_host_port_pair
.port());
228 scoped_ptr
<net::ClientSocketHandle
> socket_handle(
229 new net::ClientSocketHandle());
231 // Set the socket handle to the socket's client stream (that should be the
232 // only one active here). Then have the old socket release ownership on
233 // that client stream.
234 socket_handle
->SetSocket(
235 scoped_ptr
<net::StreamSocket
>(tcp_socket
->ClientStream()));
236 tcp_socket
->Release();
238 DCHECK(transport_security_state
);
239 net::SSLClientSocketContext context
;
240 context
.cert_verifier
= cert_verifier
;
241 context
.transport_security_state
= transport_security_state
;
243 // Fill in the SSL socket params.
244 net::SSLConfig ssl_config
;
245 ssl_config_service
->GetSSLConfig(&ssl_config
);
246 if (options
&& options
->tls_version
.get()) {
247 uint16 version_min
= 0, version_max
= 0;
248 api::socket::TLSVersionConstraints
* versions
= options
->tls_version
.get();
249 if (versions
->min
.get()) {
250 version_min
= SSLProtocolVersionFromString(*versions
->min
.get());
252 if (versions
->max
.get()) {
253 version_max
= SSLProtocolVersionFromString(*versions
->max
.get());
256 ssl_config
.version_min
= version_min
;
259 ssl_config
.version_max
= version_max
;
263 net::ClientSocketFactory
* socket_factory
=
264 net::ClientSocketFactory::GetDefaultFactory();
266 // Create the socket.
267 scoped_ptr
<net::SSLClientSocket
> ssl_socket(
268 socket_factory
->CreateSSLClientSocket(
269 socket_handle
.Pass(), host_and_port
, ssl_config
, context
));
271 DVLOG(1) << "Attempting to secure a connection to " << tcp_socket
->hostname()
272 << ":" << dest_host_port_pair
.port();
274 // We need the contents of |ssl_socket| in order to invoke its Connect()
275 // method. It belongs to |ssl_socket|, and we own that until our internal
276 // callback (|connect_cb|, below) is invoked.
277 net::SSLClientSocket
* saved_ssl_socket
= ssl_socket
.get();
279 // Try establish a TLS connection. Pass ownership of |ssl_socket| to
280 // TlsConnectDone, which will pass it on to |callback|. |connect_cb| below
281 // is only for UpgradeSocketToTLS use, and not be confused with the
282 // argument |callback|, which gets invoked by TlsConnectDone() after
283 // Connect() below returns.
284 base::Callback
<void(int)> connect_cb(base::Bind(
285 &TlsConnectDone
, base::Passed(&ssl_socket
), extension_id
, callback
));
286 int status
= saved_ssl_socket
->Connect(connect_cb
);
287 saved_ssl_socket
= NULL
;
289 // Connect completed synchronously, or failed.
290 if (status
!= net::ERR_IO_PENDING
) {
291 // Note: this can't recurse -- if |socket| is already a connected
292 // TLSSocket, it will return TYPE_TLS instead of TYPE_TCP, causing
293 // UpgradeSocketToTLS() to fail with an error above. If
294 // UpgradeSocketToTLS() is called on |socket| twice, the call to
295 // Release() on |socket| above causes the additional call to
296 // fail with an error above.
297 if (status
!= net::OK
) {
298 DVLOG(1) << "Status is not OK or IO-pending: "
299 << net::ErrorToString(status
);
301 connect_cb
.Run(status
);
305 } // namespace extensions