Finish refactoring of DomCodeToUsLayoutKeyboardCode().
[chromium-blink-merge.git] / extensions / browser / api / socket / tls_socket.cc
blob1853d31ef96c924885fc8be8d6479e1fa7b4be89
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 net::AddressList& address,
79 const CompletionCallback& callback) {
80 callback.Run(net::ERR_CONNECTION_FAILED);
83 void TLSSocket::Disconnect() {
84 if (tls_socket_) {
85 tls_socket_->Disconnect();
86 tls_socket_.reset();
90 void TLSSocket::Read(int count, const ReadCompletionCallback& callback) {
91 DCHECK(!callback.is_null());
93 if (!read_callback_.is_null()) {
94 callback.Run(net::ERR_IO_PENDING, NULL);
95 return;
98 if (count <= 0) {
99 callback.Run(net::ERR_INVALID_ARGUMENT, NULL);
100 return;
103 if (!tls_socket_.get() || !IsConnected()) {
104 callback.Run(net::ERR_SOCKET_NOT_CONNECTED, NULL);
105 return;
108 read_callback_ = callback;
109 scoped_refptr<net::IOBuffer> io_buffer(new net::IOBuffer(count));
110 // |tls_socket_| is owned by this class and the callback won't be run once
111 // |tls_socket_| is gone (as in an a call to Disconnect()). Therefore, it is
112 // safe to use base::Unretained() here.
113 int result = tls_socket_->Read(
114 io_buffer.get(),
115 count,
116 base::Bind(
117 &TLSSocket::OnReadComplete, base::Unretained(this), io_buffer));
119 if (result != net::ERR_IO_PENDING) {
120 OnReadComplete(io_buffer, result);
124 void TLSSocket::OnReadComplete(const scoped_refptr<net::IOBuffer>& io_buffer,
125 int result) {
126 DCHECK(!read_callback_.is_null());
127 base::ResetAndReturn(&read_callback_).Run(result, io_buffer);
130 int TLSSocket::WriteImpl(net::IOBuffer* io_buffer,
131 int io_buffer_size,
132 const net::CompletionCallback& callback) {
133 if (!IsConnected()) {
134 return net::ERR_SOCKET_NOT_CONNECTED;
136 return tls_socket_->Write(io_buffer, io_buffer_size, callback);
139 bool TLSSocket::SetKeepAlive(bool enable, int delay) {
140 return false;
143 bool TLSSocket::SetNoDelay(bool no_delay) {
144 return false;
147 int TLSSocket::Listen(const std::string& address,
148 uint16 port,
149 int backlog,
150 std::string* error_msg) {
151 *error_msg = kTLSSocketTypeInvalidError;
152 return net::ERR_NOT_IMPLEMENTED;
155 void TLSSocket::Accept(const AcceptCompletionCallback& callback) {
156 callback.Run(net::ERR_FAILED, NULL);
159 bool TLSSocket::IsConnected() {
160 return tls_socket_.get() && tls_socket_->IsConnected();
163 bool TLSSocket::GetPeerAddress(net::IPEndPoint* address) {
164 return IsConnected() && tls_socket_->GetPeerAddress(address);
167 bool TLSSocket::GetLocalAddress(net::IPEndPoint* address) {
168 return IsConnected() && tls_socket_->GetLocalAddress(address);
171 Socket::SocketType TLSSocket::GetSocketType() const {
172 return Socket::TYPE_TLS;
175 // static
176 void TLSSocket::UpgradeSocketToTLS(
177 Socket* socket,
178 scoped_refptr<net::SSLConfigService> ssl_config_service,
179 net::CertVerifier* cert_verifier,
180 net::TransportSecurityState* transport_security_state,
181 const std::string& extension_id,
182 core_api::socket::SecureOptions* options,
183 const TLSSocket::SecureCallback& callback) {
184 DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
185 TCPSocket* tcp_socket = static_cast<TCPSocket*>(socket);
186 scoped_ptr<net::SSLClientSocket> null_sock;
188 if (!tcp_socket || tcp_socket->GetSocketType() != Socket::TYPE_TCP ||
189 !tcp_socket->ClientStream() || !tcp_socket->IsConnected() ||
190 tcp_socket->HasPendingRead()) {
191 DVLOG(1) << "Failing before trying. socket is " << tcp_socket;
192 if (tcp_socket) {
193 DVLOG(1) << "type: " << tcp_socket->GetSocketType()
194 << ", ClientStream is " << tcp_socket->ClientStream()
195 << ", IsConnected: " << tcp_socket->IsConnected()
196 << ", HasPendingRead: " << tcp_socket->HasPendingRead();
198 TlsConnectDone(
199 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
200 return;
203 net::IPEndPoint dest_host_port_pair;
204 if (!tcp_socket->GetPeerAddress(&dest_host_port_pair)) {
205 DVLOG(1) << "Could not get peer address.";
206 TlsConnectDone(
207 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
208 return;
211 // Convert any U-LABELs to A-LABELs.
212 url::CanonHostInfo host_info;
213 std::string canon_host =
214 net::CanonicalizeHost(tcp_socket->hostname(), &host_info);
216 // Canonicalization shouldn't fail: the socket is already connected with a
217 // host, using this hostname.
218 if (host_info.family == url::CanonHostInfo::BROKEN) {
219 DVLOG(1) << "Could not canonicalize hostname";
220 TlsConnectDone(
221 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
222 return;
225 net::HostPortPair host_and_port(canon_host, dest_host_port_pair.port());
227 scoped_ptr<net::ClientSocketHandle> socket_handle(
228 new net::ClientSocketHandle());
230 // Set the socket handle to the socket's client stream (that should be the
231 // only one active here). Then have the old socket release ownership on
232 // that client stream.
233 socket_handle->SetSocket(
234 scoped_ptr<net::StreamSocket>(tcp_socket->ClientStream()));
235 tcp_socket->Release();
237 DCHECK(transport_security_state);
238 net::SSLClientSocketContext context;
239 context.cert_verifier = cert_verifier;
240 context.transport_security_state = transport_security_state;
242 // Fill in the SSL socket params.
243 net::SSLConfig ssl_config;
244 ssl_config_service->GetSSLConfig(&ssl_config);
245 if (options && options->tls_version.get()) {
246 uint16 version_min = 0, version_max = 0;
247 core_api::socket::TLSVersionConstraints* versions =
248 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());
255 if (version_min) {
256 ssl_config.version_min = version_min;
258 if (version_max) {
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