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

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: Double. Spaces removed. Created 6 years, 10 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 DVLOG(1) << "UpgradeSocketToTLS(): failing before trying. socket is "
153 << tcp_socket << ", type is " << tcp_socket->GetSocketType()
154 << ", client_stream is " << tcp_socket->ClientStream()
155 << ", and socket IsConnected: " << tcp_socket->IsConnected();
156 TlsConnectDone(
157 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
158 return;
159 }
160
161 net::IPEndPoint dest_host_port_pair;
162 if (!tcp_socket->GetPeerAddress(&dest_host_port_pair)) {
163 DVLOG(1) << "UpgradeSocketToTLS(): could not get peer address.";
164 TlsConnectDone(
165 null_sock.Pass(), extension_id, callback, net::ERR_INVALID_ARGUMENT);
166 return;
167 }
168
169 net::HostPortPair host_and_port(tcp_socket->hostname(),
170 dest_host_port_pair.port());
171
172 scoped_ptr<net::ClientSocketHandle> socket_handle(
173 new net::ClientSocketHandle());
174
175 // Set the socket handle to the socket's client stream (that should be the
176 // only one active here). Then have the old socket release ownership on of
177 // that client stream.
178 socket_handle->SetSocket(
179 scoped_ptr<net::StreamSocket>(tcp_socket->ClientStream()));
180 tcp_socket->Release();
181
182 net::URLRequestContext* url_context =
183 url_request_getter->GetURLRequestContext();
184 DCHECK(url_context);
185
186 net::SSLClientSocketContext context;
187 context.cert_verifier = url_context->cert_verifier();
188 context.transport_security_state = url_context->transport_security_state();
189 DCHECK(context.transport_security_state);
190
191 // Fill in the SSL socket params.
192 net::SSLConfig ssl_config;
193 ssl_config_service->GetSSLConfig(&ssl_config);
194 if (options && options->tls_version.get()) {
195 uint16 version_min = 0, version_max = 0;
196 api::socket::TLSVersionConstraints* versions = options->tls_version.get();
197 if (versions->min.get()) {
198 version_min = SSLProtocolVersionFromString(*versions->min.get());
199 }
200 if (versions->max.get()) {
201 version_max = SSLProtocolVersionFromString(*versions->max.get());
202 }
203 if (version_min) {
204 ssl_config.version_min = version_min;
205 }
206 if (version_max) {
207 ssl_config.version_max = version_max;
208 }
209 }
210 net::ClientSocketFactory* socket_factory =
211 net::ClientSocketFactory::GetDefaultFactory();
212
213 // Create the socket.
214 scoped_ptr<net::SSLClientSocket> ssl_socket(
215 socket_factory->CreateSSLClientSocket(
216 socket_handle.Pass(), host_and_port, ssl_config, context));
217
218 DVLOG(1) << "UpgradeSocketToTLS: Attempting to connect to "
219 << tcp_socket->hostname() << ":" << dest_host_port_pair.port();
220
221 // We need the contents of |ssl_socket| in order to invoke its Connect()
222 // method. It belongs to |ssl_socket|, and we own that until our internal
223 // callback (|connect_cb|, below) is invoked.
224 net::SSLClientSocket* saved_ssl_socket = ssl_socket.get();
225
226 // Try establish a TLS connection. Pass ownership of ssl_socket to
227 // TlsConnectDone, which will pass it on to |callback|. |connect_cb| below
228 // is only for UpgradeSocketToTLS use, and not be confused with the
229 // argument |callback|, which gets invoked by TlsConnectDone after
230 // Connect() below returns.
231 base::Callback<void(int)> connect_cb(base::Bind(&TLSSocket::TlsConnectDone,
232 base::Passed(&ssl_socket),
233 extension_id,
234 callback));
235 int status = saved_ssl_socket->Connect(connect_cb);
236 saved_ssl_socket = NULL;
237
238 // Connect failed, and won't call the callback. Call it now.
239 if (status != net::ERR_IO_PENDING && status != net::OK) {
240 // Note: this can't recurse -- if 'socket' is already a connected
241 // TLSSocket, it will return TYPE_TLS instead of TYPE_TCP, failing before
242 // we get here. If the connection failed, the socket is closed below
243 // before the callback. If the caller tries to recurse into another
244 // secure() call, they must have either created a prior socket to try, or
245 // will have to go through an asynchronous Connect() call first.
246 DVLOG(1) << "UpgradeSocketToTLS: Status is not IO-pending: "
247 << net::ErrorToString(status);
248 connect_cb.Run(status);
249 }
250 }
251
252 // static
253 void TLSSocket::TlsConnectDone(scoped_ptr<net::SSLClientSocket> ssl_socket,
254 const std::string& extension_id,
255 const SecureCallback& callback,
256 int result) {
257 DVLOG(1) << "TLSSocket::TlsConnectDone(): got back result " << result << " ("
258 << net::ErrorToString(result) << ")";
259
260 // No matter how the TLS connection attempt went, the underlying socket's
261 // no longer bound to the original TCPSocket. It belongs to |ssl_socket|,
262 // which is promoted here to a new API-accessible socket (via a TLSSocket
263 // wrapper) or deleted.
264 if (result != net::OK) {
265 callback.Run(scoped_ptr<TLSSocket>(), result);
266 return;
267 };
268
269 // Wrap the StreamSocket in a TLSSocket (which matches the extension socket
270 // API). Set the handle of the socket to the new value, so that it can be
271 // used for read/write/close/etc.
272 scoped_ptr<TLSSocket> wrapper(
273 new TLSSocket(ssl_socket.PassAs<net::StreamSocket>(), extension_id));
274
275 // Caller will end up deleting the prior TCPSocket, once it calls
276 // SetSocket(..,wrapper).
277 callback.Run(wrapper.Pass(), result);
278 }
279
280 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698