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

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: Made TLSSocket resumable, responses to sleevi's round-1 comments. Created 7 years 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/logging.h"
8 #include "chrome/browser/extensions/api/api_resource.h"
9 #include "net/base/address_list.h"
10 #include "net/base/ip_endpoint.h"
11 #include "net/base/net_errors.h"
12 #include "net/base/rand_callback.h"
13 #include "net/socket/client_socket_factory.h"
14 #include "net/socket/client_socket_handle.h"
15 #include "net/socket/tcp_client_socket.h"
16 #include "net/url_request/url_request_context.h"
17 #include "net/url_request/url_request_context_getter.h"
18
19 namespace {
20 // Returns the SSL protocol version (as a uint16) represented by a string.
21 // Returns 0 if the string is invalid. Pulled from
22 // chrome/browser/net/ssl_config_service_manager_pref.cc.
23 uint16 SSLProtocolVersionFromString(const std::string& version_str) {
24 uint16 version = 0; // Invalid.
25 if (version_str == "ssl3") {
26 version = net::SSL_PROTOCOL_VERSION_SSL3;
27 } else if (version_str == "tls1") {
28 version = net::SSL_PROTOCOL_VERSION_TLS1;
29 } else if (version_str == "tls1.1") {
30 version = net::SSL_PROTOCOL_VERSION_TLS1_1;
31 } else if (version_str == "tls1.2") {
32 version = net::SSL_PROTOCOL_VERSION_TLS1_2;
33 }
34 return version;
35 }
36 } // namespace
37
38 namespace extensions {
39
40 const char kSecureSocketTypeError[] =
41 "Only TCP sockets are supported for TLS.";
42 const char kSocketNotConnectedError[] = "Socket not connected";
43 const char kSocketNotFoundError[] = "Socket not found";
44 const char kTLSSocketTypeInvalidError[] =
45 "Cannot listen on a socket that's already connected.";
46
47 TLSSocket::TLSSocket(net::StreamSocket* tls_socket,
48 const std::string& owner_extension_id)
49 : ResumableTCPSocket(owner_extension_id),
50 tls_socket_(tls_socket) {
51 }
52
53 TLSSocket::~TLSSocket() {
54 Disconnect();
55 }
56
57 void TLSSocket::Connect(const std::string& address,
58 int port,
59 const CompletionCallback& callback) {
60 callback.Run(net::ERR_CONNECTION_FAILED);
61 }
62
63 void TLSSocket::Disconnect() {
64 if (tls_socket_) {
65 tls_socket_->Disconnect();
66 tls_socket_.reset();
67 }
68 }
69
70 void TLSSocket::Read(int count,
71 const ReadCompletionCallback& callback) {
72 DCHECK(!callback.is_null());
73
74 if (!read_callback_.is_null()) {
75 callback.Run(net::ERR_IO_PENDING, NULL);
76 return;
77 }
78
79 if (count <= 0) {
80 callback.Run(net::ERR_INVALID_ARGUMENT, NULL);
81 return;
82 }
83
84 if (!tls_socket_.get() || !IsConnected()) {
85 callback.Run(net::ERR_SOCKET_NOT_CONNECTED, NULL);
86 return;
87 }
88
89 read_callback_ = callback;
90 scoped_refptr<net::IOBuffer> io_buffer = new net::IOBuffer(count);
91 int result = tls_socket_->Read(
92 io_buffer.get(), count, base::Bind(&TLSSocket::OnReadComplete,
93 base::Unretained(this),
94 io_buffer));
95
96 if (result != net::ERR_IO_PENDING)
97 OnReadComplete(io_buffer, result);
98 }
99
100 void TLSSocket::OnReadComplete(scoped_refptr<net::IOBuffer> io_buffer,
101 int result) {
102 DCHECK(!read_callback_.is_null());
103 ReadCompletionCallback read_callback = read_callback_;
104 read_callback_.Reset();
105 // Don't touch 'this' after the read callback.
106 read_callback.Run(result, io_buffer);
107 }
108
109 int TLSSocket::WriteImpl(net::IOBuffer* io_buffer,
110 int io_buffer_size,
111 const net::CompletionCallback& callback) {
112 if (!IsConnected())
113 return net::ERR_SOCKET_NOT_CONNECTED;
114 else
115 return tls_socket_->Write(io_buffer, io_buffer_size, callback);
116 }
117
118 bool TLSSocket::SetKeepAlive(bool enable, int delay) {
119 return false;
120 }
121
122 bool TLSSocket::SetNoDelay(bool no_delay) {
123 return false;
124 }
125
126 int TLSSocket::Listen(const std::string& address, int port, int backlog,
127 std::string* error_msg) {
128 *error_msg = kTLSSocketTypeInvalidError;
129 return net::ERR_NOT_IMPLEMENTED;
130 }
131
132 void TLSSocket::Accept(const AcceptCompletionCallback &callback) {
133 callback.Run(net::ERR_FAILED, NULL);
134 }
135
136 bool TLSSocket::IsConnected() {
137 return tls_socket_.get() && tls_socket_->IsConnected();
138 }
139
140 bool TLSSocket::GetPeerAddress(net::IPEndPoint* address) {
141 return IsConnected() && tls_socket_->GetPeerAddress(address);
142 }
143
144 bool TLSSocket::GetLocalAddress(net::IPEndPoint* address) {
145 return IsConnected() && tls_socket_->GetLocalAddress(address);
146 }
147
148 Socket::SocketType TLSSocket::GetSocketType() const {
149 return Socket::TYPE_TLS;
150 }
151
152 namespace impl {
rpaquay 2013/12/09 23:02:03 Convention: Remove the "impl" namespace and move t
lally 2013/12/12 02:31:39 Done.
153 void TlsConnectDone(net::SSLClientSocket* ssl_socket,
154 const std::string& extension_id, SecureCallback callback,
155 int result ) {
rpaquay 2013/12/09 23:02:03 No space before ")"
lally 2013/12/12 02:31:39 Done.
156 DVLOG(1) << "chrome.socket.secure: TlsConnectDone(): got back result "
157 << result;
158
159 // No matter how the TLS connection attempt went, the underlying socket's
160 // no longer bound to the original TCPSocket. It belongs to ssl_socket_,
161 // which is promoted here to a new API-accessible socket (via a TLSSocket
162 // wrapper) or deleted.
163 if (result == net::OK) {
164 // Wrap the StreamSocket in a TLSSocket (which matches the extension
165 // socket API). Set the handle of the socket to the new value, so that
166 // it can be used for read/write/close/etc.
167 TLSSocket* wrapper = new TLSSocket(ssl_socket, extension_id);
168
169 // Caller will end up deleting the prior TCPSocket, once it calls
170 // SetSocket(..,wrapper).
171 callback.Run(wrapper, result);
172 } else {
173 // Failed TLS connection. This'll delete the underlying TCPClientSocket.
174 delete ssl_socket;
175 callback.Run(NULL, result);
176 }
177 }
178
179 } // namespace impl
180
181 // static
182 const char* TLSSocket::SecureTCPSocket(
183 Socket* socket,
184 Profile* profile,
185 net::URLRequestContextGetter* url_request_getter,
186 const std::string& extension_id,
187 api::socket::SecureOptions* options,
188 SecureCallback callback,
189 base::Value** result_ret) {
190 int result = -1;
rpaquay 2013/12/09 23:02:03 Use "net::ERROR_FAILED" instead of "-1".
lally 2013/12/12 02:31:39 Done.
191
192 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
193 DCHECK(profile);
194
195 if (!socket) {
196 *result_ret = new base::FundamentalValue(result);
197 return kSocketNotFoundError;
198 }
199
200 TCPSocket* tcp_socket = static_cast<TCPSocket*>(socket);
201 if (socket->GetSocketType() != Socket::TYPE_TCP
202 || tcp_socket->ClientStream() == NULL) {
203 *result_ret = new base::FundamentalValue(result);
204 return kSecureSocketTypeError;
205 }
206
207 if (!socket->IsConnected()) {
208 *result_ret = new base::FundamentalValue(result);
209 return kSocketNotConnectedError;
210 }
211
rpaquay 2013/12/09 23:02:03 As mentioned in another comment, the 3 checks abov
lally 2013/12/12 02:31:39 I moved them, but kept simpler versions here that
212 net::IPEndPoint dest_host_port_pair;
213 socket->GetPeerAddress(&dest_host_port_pair);
214 net::HostPortPair host_port(socket->Hostname(), dest_host_port_pair.port());
215
216 // Modeled after P2PSocketHostTcpBase::StartTls()
217 scoped_ptr<net::ClientSocketHandle> socket_handle(
218 new net::ClientSocketHandle());
219
220 // Set the socket handle.
221 socket_handle->SetSocket(scoped_ptr<net::StreamSocket>(
222 tcp_socket->ClientStream()));
223
224 // Have the old socket release its hold on the client stream.
225 tcp_socket->Release();
226
227 net::SSLClientSocketContext context;
228 net::URLRequestContext* url_context =
229 url_request_getter->GetURLRequestContext();
230
231 DCHECK(url_context);
232 context.cert_verifier = url_context->cert_verifier();
233 context.transport_security_state = url_context->transport_security_state();
234 DCHECK(context.transport_security_state);
235
236 // Fill in the SSL socket params.
237 net::SSLConfig ssl_config;
238 profile->GetSSLConfigService()->GetSSLConfig(&ssl_config);
239 if (options && options->tls_version.get()) {
240 uint16 version_min = 0, version_max = 0;
241 api::socket::TLSVersionConstraints* versions = options->tls_version.get();
242 if (versions->min.get()) {
243 version_min = SSLProtocolVersionFromString(*versions->min.get());
244 }
245 if (versions->max.get()) {
246 version_max = SSLProtocolVersionFromString(*versions->max.get());
247 }
248 if (version_min) {
249 ssl_config.version_min = version_min;
250 }
251 if (version_max) {
252 ssl_config.version_max = version_max;
253 }
254 }
255 net::ClientSocketFactory* socket_factory =
256 net::ClientSocketFactory::GetDefaultFactory();
257
258 // Create the socket.
259 net::SSLClientSocket* ssl_socket = socket_factory->CreateSSLClientSocket(
260 socket_handle.Pass(), host_port, ssl_config, context).release();
261
262 // And try to connect.
263 int status = ssl_socket->Connect(
264 base::Bind(&impl::TlsConnectDone, ssl_socket, extension_id, callback));
265
266 *result_ret = new base::FundamentalValue(status);
267 if (status != net::ERR_IO_PENDING) {
268 // Note: this can't recurse -- if 'socket' is already a connected
269 // TLSSocket, it will return TYPE_TLS instead of TYPE_TCP, failing before
270 // we get here. If the connection failed, the socket is closed below
271 // before the callback. If the caller tries to recurse into another
272 // secure() call, they must have either created a prior socket to try, or
273 // will have to go through an asynchronous Connect() call first.
274 impl::TlsConnectDone(ssl_socket, extension_id, callback, status);
275 return NULL;
276 }
277
278 return NULL;
279 }
280
281 } // namespace extensions
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698