Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(282)

Side by Side Diff: extensions/browser/api/socket/tls_socket.cc

Issue 76403004: An implementation of chrome.socket.secure(). (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Tiny, tiny, tiny changes to clean up the diffs post-rebase. Created 6 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright 2013 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.
4
5 #include "extensions/browser/api/socket/tls_socket.h"
6
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/tcp_client_socket.h"
17 #include "net/url_request/url_request_context.h"
18 #include "net/url_request/url_request_context_getter.h"
19 #include "url/url_canon.h"
20
21 namespace {
22
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 == "ssl3") {
28 version = net::SSL_PROTOCOL_VERSION_SSL3;
29 } else if (version_str == "tls1") {
30 version = net::SSL_PROTOCOL_VERSION_TLS1;
31 } else if (version_str == "tls1.1") {
32 version = net::SSL_PROTOCOL_VERSION_TLS1_1;
33 } else if (version_str == "tls1.2") {
34 version = net::SSL_PROTOCOL_VERSION_TLS1_2;
35 }
36 return version;
37 }
38
39 } // namespace
40
41 namespace extensions {
42
43 const char kTLSSocketTypeInvalidError[] =
44 "Cannot listen on a socket that is already connected.";
45
46 TLSSocket::TLSSocket(scoped_ptr<net::StreamSocket> tls_socket,
47 const std::string& owner_extension_id)
48 : ResumableTCPSocket(owner_extension_id), tls_socket_(tls_socket.Pass()) {}
49
50 TLSSocket::~TLSSocket() { Disconnect(); }
51
52 void TLSSocket::Connect(const std::string& address,
53 int port,
54 const CompletionCallback& callback) {
55 callback.Run(net::ERR_CONNECTION_FAILED);
56 }
57
58 void TLSSocket::Disconnect() {
59 if (tls_socket_) {
60 tls_socket_->Disconnect();
61 tls_socket_.reset();
62 }
63 }
64
65 void TLSSocket::Read(int count, const ReadCompletionCallback& callback) {
66 DCHECK(!callback.is_null());
67
68 if (!read_callback_.is_null()) {
69 callback.Run(net::ERR_IO_PENDING, NULL);
70 return;
71 }
72
73 if (count <= 0) {
74 callback.Run(net::ERR_INVALID_ARGUMENT, NULL);
75 return;
76 }
77
78 if (!tls_socket_.get() || !IsConnected()) {
79 callback.Run(net::ERR_SOCKET_NOT_CONNECTED, NULL);
80 return;
81 }
82
83 read_callback_ = callback;
84 scoped_refptr<net::IOBuffer> io_buffer(new net::IOBuffer(count));
85 int result = tls_socket_->Read(
86 io_buffer.get(),
87 count,
88 base::Bind(
89 &TLSSocket::OnReadComplete, base::Unretained(this), io_buffer));
90
91 if (result != net::ERR_IO_PENDING) {
92 OnReadComplete(io_buffer, result);
93 }
94 }
95
96 void TLSSocket::OnReadComplete(const scoped_refptr<net::IOBuffer>& io_buffer,
97 int result) {
98 DCHECK(!read_callback_.is_null());
99 base::ResetAndReturn(&read_callback_).Run(result, io_buffer);
100 }
101
102 int TLSSocket::WriteImpl(net::IOBuffer* io_buffer,
103 int io_buffer_size,
104 const net::CompletionCallback& callback) {
105 if (!IsConnected()) {
106 return net::ERR_SOCKET_NOT_CONNECTED;
107 }
108 return tls_socket_->Write(io_buffer, io_buffer_size, callback);
109 }
110
111 bool TLSSocket::SetKeepAlive(bool enable, int delay) { return false; }
112
113 bool TLSSocket::SetNoDelay(bool no_delay) { return false; }
114
115 int TLSSocket::Listen(const std::string& address,
116 int port,
117 int backlog,
118 std::string* error_msg) {
119 *error_msg = kTLSSocketTypeInvalidError;
120 return net::ERR_NOT_IMPLEMENTED;
121 }
122
123 void TLSSocket::Accept(const AcceptCompletionCallback& callback) {
124 callback.Run(net::ERR_FAILED, NULL);
125 }
126
127 bool TLSSocket::IsConnected() {
128 return tls_socket_.get() && tls_socket_->IsConnected();
129 }
130
131 bool TLSSocket::GetPeerAddress(net::IPEndPoint* address) {
132 return IsConnected() && tls_socket_->GetPeerAddress(address);
133 }
134
135 bool TLSSocket::GetLocalAddress(net::IPEndPoint* address) {
136 return IsConnected() && tls_socket_->GetLocalAddress(address);
137 }
138
139 Socket::SocketType TLSSocket::GetSocketType() const { return Socket::TYPE_TLS; }
140
141 // static
142 void TLSSocket::UpgradeSocketToTLS(
143 Socket* socket,
144 scoped_refptr<net::SSLConfigService> ssl_config_service,
145 scoped_refptr<net::URLRequestContextGetter> url_request_getter,
146 const std::string& extension_id,
147 core_api::socket::SecureOptions* options,
148 const SecureCallback& callback) {
149 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
150 TCPSocket* tcp_socket = static_cast<TCPSocket*>(socket);
151 scoped_ptr<net::SSLClientSocket> null_sock;
152
153 if (!tcp_socket || tcp_socket->GetSocketType() != Socket::TYPE_TCP ||
154 !tcp_socket->ClientStream() || !tcp_socket->IsConnected() ||
155 tcp_socket->HasPendingRead()) {
156 DVLOG(1) << "Failing before trying. socket is " << tcp_socket;
157 if (tcp_socket) {
158 DVLOG(1) << "type: " << tcp_socket->GetSocketType()
159 << ", ClientStream is " << tcp_socket->ClientStream()
160 << ", IsConnected: " << tcp_socket->IsConnected()
161 << ", HasPendingRead: " << tcp_socket->HasPendingRead();
162 }
163 TlsConnectDone(
164 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
165 return;
166 }
167
168 net::IPEndPoint dest_host_port_pair;
169 if (!tcp_socket->GetPeerAddress(&dest_host_port_pair)) {
170 DVLOG(1) << "Could not get peer address.";
171 TlsConnectDone(
172 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
173 return;
174 }
175
176 // Convert any U-LABELs to A-LABELs.
177 url_canon::CanonHostInfo host_info;
178 std::string canon_host =
179 net::CanonicalizeHost(tcp_socket->hostname(), &host_info);
180
181 // Canonicalization shouldn't fail: the socket is already connected with a
182 // host, using this hostname.
183 if (host_info.family == url_canon::CanonHostInfo::BROKEN) {
184 DVLOG(1) << "Could not canonicalize hostname";
185 TlsConnectDone(
186 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
187 }
188
189 net::HostPortPair host_and_port(canon_host, dest_host_port_pair.port());
190
191 scoped_ptr<net::ClientSocketHandle> socket_handle(
192 new net::ClientSocketHandle());
193
194 // Set the socket handle to the socket's client stream (that should be the
195 // only one active here). Then have the old socket release ownership on
196 // that client stream.
197 socket_handle->SetSocket(
198 scoped_ptr<net::StreamSocket>(tcp_socket->ClientStream()));
199 tcp_socket->Release();
200
201 net::URLRequestContext* url_context =
202 url_request_getter->GetURLRequestContext();
203 DCHECK(url_context);
204
205 net::SSLClientSocketContext context;
206 context.cert_verifier = url_context->cert_verifier();
207 context.transport_security_state = url_context->transport_security_state();
208 DCHECK(context.transport_security_state);
209
210 // Fill in the SSL socket params.
211 net::SSLConfig ssl_config;
212 ssl_config_service->GetSSLConfig(&ssl_config);
213 if (options && options->tls_version.get()) {
214 uint16 version_min = 0, version_max = 0;
215 core_api::socket::TLSVersionConstraints* versions =
216 options->tls_version.get();
217 if (versions->min.get()) {
218 version_min = SSLProtocolVersionFromString(*versions->min.get());
219 }
220 if (versions->max.get()) {
221 version_max = SSLProtocolVersionFromString(*versions->max.get());
222 }
223 if (version_min) {
224 ssl_config.version_min = version_min;
225 }
226 if (version_max) {
227 ssl_config.version_max = version_max;
228 }
229 }
230 net::ClientSocketFactory* socket_factory =
231 net::ClientSocketFactory::GetDefaultFactory();
232
233 // Create the socket.
234 scoped_ptr<net::SSLClientSocket> ssl_socket(
235 socket_factory->CreateSSLClientSocket(
236 socket_handle.Pass(), host_and_port, ssl_config, context));
237
238 DVLOG(1) << "Attempting to secure a connection to " << tcp_socket->hostname()
239 << ":" << dest_host_port_pair.port();
240
241 // We need the contents of |ssl_socket| in order to invoke its Connect()
242 // method. It belongs to |ssl_socket|, and we own that until our internal
243 // callback (|connect_cb|, below) is invoked.
244 net::SSLClientSocket* saved_ssl_socket = ssl_socket.get();
245
246 // Try establish a TLS connection. Pass ownership of |ssl_socket| to
247 // TlsConnectDone, which will pass it on to |callback|. |connect_cb| below
248 // is only for UpgradeSocketToTLS use, and not be confused with the
249 // argument |callback|, which gets invoked by TlsConnectDone() after
250 // Connect() below returns.
251 base::Callback<void(int)> connect_cb(base::Bind(&TLSSocket::TlsConnectDone,
252 base::Passed(&ssl_socket),
253 extension_id,
254 callback));
255 int status = saved_ssl_socket->Connect(connect_cb);
256 saved_ssl_socket = NULL;
257
258 // Connect failed, and won't call the callback. Call it now.
259 if (status != net::ERR_IO_PENDING && status != net::OK) {
260 // Note: this can't recurse -- if |socket| is already a connected
261 // TLSSocket, it will return TYPE_TLS instead of TYPE_TCP, causing
262 // UpgradeSocketToTLS() to fail with an error above. If
263 // UpgradeSocketToTLS() is called on |socket| twice, the call to
264 // Release() on |socket| above causes the additional call to
265 // fail with an error above.
266 DVLOG(1) << "Status is not IO-pending: " << net::ErrorToString(status);
267 connect_cb.Run(status);
268 }
269 }
270
271 // static
272 void TLSSocket::TlsConnectDone(scoped_ptr<net::SSLClientSocket> ssl_socket,
273 const std::string& extension_id,
274 const SecureCallback& callback,
275 int result) {
276 DVLOG(1) << "Got back result " << result << " " << net::ErrorToString(result);
277
278 // No matter how the TLS connection attempt went, the underlying socket's
279 // no longer bound to the original TCPSocket. It belongs to |ssl_socket|,
280 // which is promoted here to a new API-accessible socket (via a TLSSocket
281 // wrapper), or deleted.
282 if (result != net::OK) {
283 callback.Run(scoped_ptr<TLSSocket>(), result);
284 return;
285 };
286
287 // Wrap the StreamSocket in a TLSSocket, which matches the extension socket
288 // API. Set the handle of the socket to the new value, so that it can be
289 // used for read/write/close/etc.
290 scoped_ptr<TLSSocket> wrapper(
291 new TLSSocket(ssl_socket.PassAs<net::StreamSocket>(), extension_id));
292
293 // Caller will end up deleting the prior TCPSocket, once it calls
294 // SetSocket(..,wrapper).
295 callback.Run(wrapper.Pass(), result);
296 }
297
298 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698