Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / extensions / browser / api / socket / tls_socket.cc
blob4b34c4bbfa504a873f8b5f597d9762387759c6b0
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/rand_callback.h"
14 #include "net/socket/client_socket_factory.h"
15 #include "net/socket/client_socket_handle.h"
16 #include "net/socket/ssl_client_socket.h"
17 #include "net/socket/tcp_client_socket.h"
18 #include "url/url_canon.h"
20 namespace {
22 // Returns the SSL protocol version (as a uint16) represented by a string.
23 // Returns 0 if the string is invalid.
24 uint16 SSLProtocolVersionFromString(const std::string& version_str) {
25 uint16 version = 0; // Invalid.
26 if (version_str == "tls1") {
27 version = net::SSL_PROTOCOL_VERSION_TLS1;
28 } else if (version_str == "tls1.1") {
29 version = net::SSL_PROTOCOL_VERSION_TLS1_1;
30 } else if (version_str == "tls1.2") {
31 version = net::SSL_PROTOCOL_VERSION_TLS1_2;
33 return version;
36 void TlsConnectDone(scoped_ptr<net::SSLClientSocket> ssl_socket,
37 const std::string& extension_id,
38 const extensions::TLSSocket::SecureCallback& callback,
39 int result) {
40 DVLOG(1) << "Got back result " << result << " " << net::ErrorToString(result);
42 // No matter how the TLS connection attempt went, the underlying socket's
43 // no longer bound to the original TCPSocket. It belongs to |ssl_socket|,
44 // which is promoted here to a new API-accessible socket (via a TLSSocket
45 // wrapper), or deleted.
46 if (result != net::OK) {
47 callback.Run(scoped_ptr<extensions::TLSSocket>(), result);
48 return;
51 // Wrap the StreamSocket in a TLSSocket, which matches the extension socket
52 // API. Set the handle of the socket to the new value, so that it can be
53 // used for read/write/close/etc.
54 scoped_ptr<extensions::TLSSocket> wrapper(
55 new extensions::TLSSocket(ssl_socket.Pass(), extension_id));
57 // Caller will end up deleting the prior TCPSocket, once it calls
58 // SetSocket(..,wrapper).
59 callback.Run(wrapper.Pass(), result);
62 } // namespace
64 namespace extensions {
66 const char kTLSSocketTypeInvalidError[] =
67 "Cannot listen on a socket that is already connected.";
69 TLSSocket::TLSSocket(scoped_ptr<net::StreamSocket> tls_socket,
70 const std::string& owner_extension_id)
71 : ResumableTCPSocket(owner_extension_id), tls_socket_(tls_socket.Pass()) {
74 TLSSocket::~TLSSocket() {
75 Disconnect();
78 void TLSSocket::Connect(const std::string& address,
79 uint16 port,
80 const CompletionCallback& callback) {
81 callback.Run(net::ERR_CONNECTION_FAILED);
84 void TLSSocket::Disconnect() {
85 if (tls_socket_) {
86 tls_socket_->Disconnect();
87 tls_socket_.reset();
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);
96 return;
99 if (count <= 0) {
100 callback.Run(net::ERR_INVALID_ARGUMENT, NULL);
101 return;
104 if (!tls_socket_.get() || !IsConnected()) {
105 callback.Run(net::ERR_SOCKET_NOT_CONNECTED, NULL);
106 return;
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(
115 io_buffer.get(),
116 count,
117 base::Bind(
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,
126 int result) {
127 DCHECK(!read_callback_.is_null());
128 base::ResetAndReturn(&read_callback_).Run(result, io_buffer);
131 int TLSSocket::WriteImpl(net::IOBuffer* io_buffer,
132 int io_buffer_size,
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) {
141 return false;
144 bool TLSSocket::SetNoDelay(bool no_delay) {
145 return false;
148 int TLSSocket::Listen(const std::string& address,
149 uint16 port,
150 int backlog,
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;
176 // static
177 void TLSSocket::UpgradeSocketToTLS(
178 Socket* socket,
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 core_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;
193 if (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();
199 TlsConnectDone(
200 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
201 return;
204 net::IPEndPoint dest_host_port_pair;
205 if (!tcp_socket->GetPeerAddress(&dest_host_port_pair)) {
206 DVLOG(1) << "Could not get peer address.";
207 TlsConnectDone(
208 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
209 return;
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";
221 TlsConnectDone(
222 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
223 return;
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 core_api::socket::TLSVersionConstraints* versions =
249 options->tls_version.get();
250 if (versions->min.get()) {
251 version_min = SSLProtocolVersionFromString(*versions->min.get());
253 if (versions->max.get()) {
254 version_max = SSLProtocolVersionFromString(*versions->max.get());
256 if (version_min) {
257 ssl_config.version_min = version_min;
259 if (version_max) {
260 ssl_config.version_max = version_max;
264 net::ClientSocketFactory* socket_factory =
265 net::ClientSocketFactory::GetDefaultFactory();
267 // Create the socket.
268 scoped_ptr<net::SSLClientSocket> ssl_socket(
269 socket_factory->CreateSSLClientSocket(
270 socket_handle.Pass(), host_and_port, ssl_config, context));
272 DVLOG(1) << "Attempting to secure a connection to " << tcp_socket->hostname()
273 << ":" << dest_host_port_pair.port();
275 // We need the contents of |ssl_socket| in order to invoke its Connect()
276 // method. It belongs to |ssl_socket|, and we own that until our internal
277 // callback (|connect_cb|, below) is invoked.
278 net::SSLClientSocket* saved_ssl_socket = ssl_socket.get();
280 // Try establish a TLS connection. Pass ownership of |ssl_socket| to
281 // TlsConnectDone, which will pass it on to |callback|. |connect_cb| below
282 // is only for UpgradeSocketToTLS use, and not be confused with the
283 // argument |callback|, which gets invoked by TlsConnectDone() after
284 // Connect() below returns.
285 base::Callback<void(int)> connect_cb(base::Bind(
286 &TlsConnectDone, base::Passed(&ssl_socket), extension_id, callback));
287 int status = saved_ssl_socket->Connect(connect_cb);
288 saved_ssl_socket = NULL;
290 // Connect completed synchronously, or failed.
291 if (status != net::ERR_IO_PENDING) {
292 // Note: this can't recurse -- if |socket| is already a connected
293 // TLSSocket, it will return TYPE_TLS instead of TYPE_TCP, causing
294 // UpgradeSocketToTLS() to fail with an error above. If
295 // UpgradeSocketToTLS() is called on |socket| twice, the call to
296 // Release() on |socket| above causes the additional call to
297 // fail with an error above.
298 if (status != net::OK) {
299 DVLOG(1) << "Status is not OK or IO-pending: "
300 << net::ErrorToString(status);
302 connect_cb.Run(status);
306 } // namespace extensions