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

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

Powered by Google App Engine
This is Rietveld 408576698