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

Side by Side Diff: chrome/browser/extensions/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: An un-DCHECK-ification, a new test, a test clarification, and a lot of nit-double-spaces. Created 6 years, 9 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 (c) 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 "chrome/browser/extensions/api/socket/tls_socket.h"
6
7 #include "base/callback_helpers.h"
8 #include "base/logging.h"
9 #include "chrome/browser/extensions/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 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) << "UpgradeSocketToTLS(): failing before trying. socket is "
157 << tcp_socket;
158 if (tcp_socket) {
159 DVLOG(1) << "UpgradeSocketToTLS(): type: " << tcp_socket->GetSocketType()
160 << ", ClientStream is " << tcp_socket->ClientStream()
161 << ", IsConnected: " << tcp_socket->IsConnected()
162 << ", HasPendingRead: " << tcp_socket->HasPendingRead();
163 }
164 TlsConnectDone(
165 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
166 return;
167 }
168
169 net::IPEndPoint dest_host_port_pair;
170 if (!tcp_socket->GetPeerAddress(&dest_host_port_pair)) {
171 DVLOG(1) << "UpgradeSocketToTLS(): could not get peer address.";
172 TlsConnectDone(
173 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
174 return;
175 }
176
177 // Convert any U-LABELs to A-LABELs.
178 url_canon::CanonHostInfo host_info;
179 std::string canon_host =
180 net::CanonicalizeHost(tcp_socket->hostname(), &host_info);
181
182 // Canonicalization shouldn't fail: the socket already connected with a
183 // host, using this hostname.
184 DCHECK(host_info.family != url_canon::CanonHostInfo::BROKEN)
185 << "UpgradeSocketToTLS(): could not cononicalize hostnaame";
Ryan Sleevi 2014/03/18 01:05:13 Seems to me like you shouldn't be DCHECKing here -
lally 2014/03/26 03:17:51 Ah. I thought that since it successfully connecte
186
187 net::HostPortPair host_and_port(canon_host, dest_host_port_pair.port());
188
189 scoped_ptr<net::ClientSocketHandle> socket_handle(
190 new net::ClientSocketHandle());
191
192 // Set the socket handle to the socket's client stream (that should be the
193 // only one active here). Then have the old socket release ownership on
194 // that client stream.
195 socket_handle->SetSocket(
196 scoped_ptr<net::StreamSocket>(tcp_socket->ClientStream()));
197 tcp_socket->Release();
198
199 net::URLRequestContext* url_context =
200 url_request_getter->GetURLRequestContext();
201 DCHECK(url_context);
202
203 net::SSLClientSocketContext context;
204 context.cert_verifier = url_context->cert_verifier();
205 context.transport_security_state = url_context->transport_security_state();
206 DCHECK(context.transport_security_state);
207
208 // Fill in the SSL socket params.
209 net::SSLConfig ssl_config;
210 ssl_config_service->GetSSLConfig(&ssl_config);
211 if (options && options->tls_version.get()) {
212 uint16 version_min = 0, version_max = 0;
213 api::socket::TLSVersionConstraints* versions = options->tls_version.get();
214 if (versions->min.get()) {
215 version_min = SSLProtocolVersionFromString(*versions->min.get());
216 }
217 if (versions->max.get()) {
218 version_max = SSLProtocolVersionFromString(*versions->max.get());
219 }
220 if (version_min) {
221 ssl_config.version_min = version_min;
222 }
223 if (version_max) {
224 ssl_config.version_max = version_max;
225 }
226 }
227 net::ClientSocketFactory* socket_factory =
228 net::ClientSocketFactory::GetDefaultFactory();
229
230 // Create the socket.
231 scoped_ptr<net::SSLClientSocket> ssl_socket(
232 socket_factory->CreateSSLClientSocket(
233 socket_handle.Pass(), host_and_port, ssl_config, context));
234
235 DVLOG(1) << "UpgradeSocketToTLS: Attempting to secure a connection to "
236 << tcp_socket->hostname() << ":" << dest_host_port_pair.port();
237
238 // We need the contents of |ssl_socket| in order to invoke its Connect()
239 // method. It belongs to |ssl_socket|, and we own that until our internal
240 // callback (|connect_cb|, below) is invoked.
241 net::SSLClientSocket* saved_ssl_socket = ssl_socket.get();
242
243 // Try establish a TLS connection. Pass ownership of |ssl_socket| to
244 // TlsConnectDone, which will pass it on to |callback|. |connect_cb| below
245 // is only for UpgradeSocketToTLS use, and not be confused with the
246 // argument |callback|, which gets invoked by TlsConnectDone() after
247 // Connect() below returns.
248 base::Callback<void(int)> connect_cb(base::Bind(&TLSSocket::TlsConnectDone,
249 base::Passed(&ssl_socket),
250 extension_id,
251 callback));
252 int status = saved_ssl_socket->Connect(connect_cb);
253 saved_ssl_socket = NULL;
254
255 // Connect failed, and won't call the callback. Call it now.
256 if (status != net::ERR_IO_PENDING && status != net::OK) {
257 // Note: this can't recurse -- if |socket| is already a connected
258 // TLSSocket, it will return TYPE_TLS instead of TYPE_TCP, causing
259 // UpgradeSocketToTLS to fail with an error above. If
260 // UpgradeSocketToTLS() is called on |socket| twice, the call to
261 // Release() on |socket| above causes the additional call to
262 // fail with an error above.
263 DVLOG(1) << "UpgradeSocketToTLS: Status is not IO-pending: "
264 << net::ErrorToString(status);
265 connect_cb.Run(status);
266 }
267 }
268
269 // static
270 void TLSSocket::TlsConnectDone(scoped_ptr<net::SSLClientSocket> ssl_socket,
271 const std::string& extension_id,
272 const SecureCallback& callback,
273 int result) {
274 DVLOG(1) << "TLSSocket::TlsConnectDone(): got back result " << result << " ("
275 << net::ErrorToString(result) << ")";
276
277 // No matter how the TLS connection attempt went, the underlying socket's
278 // no longer bound to the original TCPSocket. It belongs to |ssl_socket|,
279 // which is promoted here to a new API-accessible socket (via a TLSSocket
280 // wrapper), or deleted.
281 if (result != net::OK) {
282 callback.Run(scoped_ptr<TLSSocket>(), result);
283 return;
284 };
285
286 // Wrap the StreamSocket in a TLSSocket, which matches the extension socket
287 // API. Set the handle of the socket to the new value, so that it can be
288 // used for read/write/close/etc.
289 scoped_ptr<TLSSocket> wrapper(
290 new TLSSocket(ssl_socket.PassAs<net::StreamSocket>(), extension_id));
291
292 // Caller will end up deleting the prior TCPSocket, once it calls
293 // SetSocket(..,wrapper).
294 callback.Run(wrapper.Pass(), result);
295 }
296
297 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698