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

Side by Side Diff: blimp/client/session/assignment_source.cc

Issue 1696563002: Blimp: add support for SSL connections. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: std::move'd another scoped_refptr. Created 4 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
OLDNEW
1 // Copyright 2016 The Chromium Authors. All rights reserved. 1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "blimp/client/session/assignment_source.h" 5 #include "blimp/client/session/assignment_source.h"
6 6
7 #include "base/bind.h" 7 #include "base/bind.h"
8 #include "base/callback_helpers.h" 8 #include "base/callback_helpers.h"
9 #include "base/command_line.h" 9 #include "base/command_line.h"
10 #include "base/files/file_util.h"
10 #include "base/json/json_reader.h" 11 #include "base/json/json_reader.h"
11 #include "base/json/json_writer.h" 12 #include "base/json/json_writer.h"
12 #include "base/location.h" 13 #include "base/location.h"
14 #include "base/memory/ref_counted.h"
13 #include "base/numerics/safe_conversions.h" 15 #include "base/numerics/safe_conversions.h"
14 #include "base/strings/string_number_conversions.h" 16 #include "base/strings/string_number_conversions.h"
17 #include "base/task_runner_util.h"
15 #include "base/values.h" 18 #include "base/values.h"
16 #include "blimp/client/app/blimp_client_switches.h" 19 #include "blimp/client/app/blimp_client_switches.h"
17 #include "blimp/common/protocol_version.h" 20 #include "blimp/common/protocol_version.h"
18 #include "net/base/ip_address.h" 21 #include "net/base/ip_address.h"
19 #include "net/base/ip_endpoint.h" 22 #include "net/base/ip_endpoint.h"
20 #include "net/base/load_flags.h" 23 #include "net/base/load_flags.h"
21 #include "net/base/net_errors.h" 24 #include "net/base/net_errors.h"
22 #include "net/base/url_util.h" 25 #include "net/base/url_util.h"
23 #include "net/http/http_status_code.h" 26 #include "net/http/http_status_code.h"
24 #include "net/proxy/proxy_config_service.h" 27 #include "net/proxy/proxy_config_service.h"
25 #include "net/proxy/proxy_service.h" 28 #include "net/proxy/proxy_service.h"
26 #include "net/url_request/url_fetcher.h" 29 #include "net/url_request/url_fetcher.h"
27 #include "net/url_request/url_request_context.h" 30 #include "net/url_request/url_request_context.h"
28 #include "net/url_request/url_request_context_builder.h" 31 #include "net/url_request/url_request_context_builder.h"
29 #include "net/url_request/url_request_context_getter.h" 32 #include "net/url_request/url_request_context_getter.h"
30 33
31 namespace blimp { 34 namespace blimp {
32 namespace client { 35 namespace client {
33 36
34 namespace { 37 namespace {
35 38
36 // Assignment request JSON keys. 39 // Assignment request JSON keys.
37 const char kProtocolVersionKey[] = "protocol_version"; 40 const char kProtocolVersionKey[] = "protocol_version";
38 41
39 // Assignment response JSON keys. 42 // Assignment response JSON keys.
40 const char kClientTokenKey[] = "clientToken"; 43 const char kClientTokenKey[] = "clientToken";
41 const char kHostKey[] = "host"; 44 const char kHostKey[] = "host";
42 const char kPortKey[] = "port"; 45 const char kPortKey[] = "port";
43 const char kCertificateFingerprintKey[] = "certificateFingerprint";
44 const char kCertificateKey[] = "certificate"; 46 const char kCertificateKey[] = "certificate";
45 47
46 // URL scheme constants for custom assignments. See the '--blimplet-endpoint' 48 // URL scheme constants for custom assignments. See the '--blimplet-endpoint'
47 // documentation in blimp_client_switches.cc for details. 49 // documentation in blimp_client_switches.cc for details.
48 const char kCustomSSLScheme[] = "ssl"; 50 const char kCustomSSLScheme[] = "ssl";
49 const char kCustomTCPScheme[] = "tcp"; 51 const char kCustomTCPScheme[] = "tcp";
50 const char kCustomQUICScheme[] = "quic"; 52 const char kCustomQUICScheme[] = "quic";
51 53
52 Assignment GetCustomBlimpletAssignment() {
53 GURL url(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
54 switches::kBlimpletEndpoint));
55
56 std::string host;
57 int port;
58 if (url.is_empty() || !url.is_valid() || !url.has_scheme() ||
59 !net::ParseHostAndPort(url.path(), &host, &port)) {
60 return Assignment();
61 }
62
63 net::IPAddress ip_address;
64 if (!ip_address.AssignFromIPLiteral(host)) {
65 CHECK(false) << "Invalid BlimpletAssignment host " << host;
66 }
67
68 if (!base::IsValueInRangeForNumericType<uint16_t>(port)) {
69 CHECK(false) << "Invalid BlimpletAssignment port " << port;
70 }
71
72 Assignment::TransportProtocol protocol =
73 Assignment::TransportProtocol::UNKNOWN;
74 if (url.has_scheme()) {
75 if (url.SchemeIs(kCustomSSLScheme)) {
76 protocol = Assignment::TransportProtocol::SSL;
77 } else if (url.SchemeIs(kCustomTCPScheme)) {
78 protocol = Assignment::TransportProtocol::TCP;
79 } else if (url.SchemeIs(kCustomQUICScheme)) {
80 protocol = Assignment::TransportProtocol::QUIC;
81 } else {
82 CHECK(false) << "Invalid BlimpletAssignment scheme " << url.scheme();
83 }
84 }
85
86 Assignment assignment;
87 assignment.transport_protocol = protocol;
88 assignment.ip_endpoint = net::IPEndPoint(ip_address, port);
89 assignment.client_token = kDummyClientToken;
90 return assignment;
91 }
92
93 GURL GetBlimpAssignerURL() { 54 GURL GetBlimpAssignerURL() {
94 // TODO(dtrainor): Add a way to specify another assigner. 55 // TODO(dtrainor): Add a way to specify another assigner.
95 return GURL(kDefaultAssignerURL); 56 return GURL(kDefaultAssignerURL);
96 } 57 }
97 58
98 class SimpleURLRequestContextGetter : public net::URLRequestContextGetter { 59 class SimpleURLRequestContextGetter : public net::URLRequestContextGetter {
99 public: 60 public:
100 SimpleURLRequestContextGetter( 61 SimpleURLRequestContextGetter(
101 const scoped_refptr<base::SingleThreadTaskRunner>& io_loop_task_runner) 62 scoped_refptr<base::SingleThreadTaskRunner> io_loop_task_runner)
102 : io_loop_task_runner_(io_loop_task_runner), 63 : io_loop_task_runner_(std::move(io_loop_task_runner)),
103 proxy_config_service_(net::ProxyService::CreateSystemProxyConfigService( 64 proxy_config_service_(net::ProxyService::CreateSystemProxyConfigService(
104 io_loop_task_runner_, 65 io_loop_task_runner_,
105 io_loop_task_runner_)) {} 66 io_loop_task_runner_)) {}
106 67
107 // net::URLRequestContextGetter implementation. 68 // net::URLRequestContextGetter implementation.
108 net::URLRequestContext* GetURLRequestContext() override { 69 net::URLRequestContext* GetURLRequestContext() override {
109 if (!url_request_context_) { 70 if (!url_request_context_) {
110 net::URLRequestContextBuilder builder; 71 net::URLRequestContextBuilder builder;
111 builder.set_proxy_config_service(std::move(proxy_config_service_)); 72 builder.set_proxy_config_service(std::move(proxy_config_service_));
112 builder.DisableHttpCache(); 73 builder.DisableHttpCache();
(...skipping 16 matching lines...) Expand all
129 90
130 // Temporary storage for the ProxyConfigService, which needs to be created on 91 // Temporary storage for the ProxyConfigService, which needs to be created on
131 // the main thread but cleared on the IO thread. This will be built in the 92 // the main thread but cleared on the IO thread. This will be built in the
132 // constructor and cleared on the IO thread. Due to the usage of this class 93 // constructor and cleared on the IO thread. Due to the usage of this class
133 // this is safe. 94 // this is safe.
134 scoped_ptr<net::ProxyConfigService> proxy_config_service_; 95 scoped_ptr<net::ProxyConfigService> proxy_config_service_;
135 96
136 DISALLOW_COPY_AND_ASSIGN(SimpleURLRequestContextGetter); 97 DISALLOW_COPY_AND_ASSIGN(SimpleURLRequestContextGetter);
137 }; 98 };
138 99
100 // Populates an Assignment using command-line parameters, if provided.
101 // Returns a null Assignment if no parameters were set.
102 // Must be called on the IO thread.
103
104 Assignment GetCustomAssignment() {
105 GURL url(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
106 switches::kEngineEndpoint));
107
108 std::string host;
109 int port;
110 if (url.is_empty() || !url.is_valid() || !url.has_scheme() ||
111 !net::ParseHostAndPort(url.path(), &host, &port)) {
112 return Assignment();
113 }
114
115 net::IPAddress ip_address;
116 CHECK(ip_address.AssignFromIPLiteral(host)) << "Invalid Assignment host "
117 << host;
118
119 Assignment::TransportProtocol protocol =
120 Assignment::TransportProtocol::UNKNOWN;
121 if (url.SchemeIs(kCustomSSLScheme)) {
122 protocol = Assignment::TransportProtocol::SSL;
123 } else if (url.SchemeIs(kCustomTCPScheme)) {
124 protocol = Assignment::TransportProtocol::TCP;
125 } else if (url.SchemeIs(kCustomQUICScheme)) {
126 protocol = Assignment::TransportProtocol::QUIC;
127 } else {
128 CHECK(false) << "Invalid engine protocol scheme " << url.scheme();
129 }
130
131 scoped_refptr<net::X509Certificate> cert;
132 if (protocol == Assignment::TransportProtocol::SSL ||
133 protocol == Assignment::TransportProtocol::QUIC) {
134 base::FilePath cert_path =
135 base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
136 switches::kEngineCertPath);
137 CHECK(!cert_path.empty()) << "Missing required parameter --"
138 << switches::kEngineCertPath << ".";
139 std::string cert_str;
140 CHECK(base::ReadFileToString(cert_path, &cert_str))
141 << "Couldn't read from file: " << cert_path.LossyDisplayName();
142 net::CertificateList cert_list =
143 net::X509Certificate::CreateCertificateListFromBytes(
144 cert_str.data(), cert_str.size(),
145 net::X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
146 CHECK_EQ(1u, cert_list.size())
147 << "Only one cert is allowed in PEM cert list.";
148 cert = std::move(cert_list[0]);
149 }
Ryan Sleevi 2016/02/23 21:01:31 Is it a bug to supply kEngineCertPath without supp
Kevin M 2016/02/24 00:31:42 That's a harmless flag combination, so not really.
150
151 Assignment assignment;
152 assignment.transport_protocol = protocol;
153 assignment.ip_endpoint =
154 net::IPEndPoint(ip_address, base::checked_cast<uint16_t>(port));
155 assignment.client_token = kDummyClientToken;
156 assignment.cert = std::move(cert);
157 return assignment;
158 }
159
139 } // namespace 160 } // namespace
140 161
141 Assignment::Assignment() : transport_protocol(TransportProtocol::UNKNOWN) {} 162 Assignment::Assignment() : transport_protocol(TransportProtocol::UNKNOWN) {}
142 163
143 Assignment::~Assignment() {} 164 Assignment::~Assignment() {}
144 165
145 bool Assignment::is_null() const { 166 bool Assignment::is_null() const {
146 return ip_endpoint.address().empty() || ip_endpoint.port() == 0 || 167 return ip_endpoint.address().empty() || ip_endpoint.port() == 0 ||
147 transport_protocol == TransportProtocol::UNKNOWN; 168 transport_protocol == TransportProtocol::UNKNOWN;
148 } 169 }
149 170
150 AssignmentSource::AssignmentSource( 171 AssignmentSource::AssignmentSource(
151 const scoped_refptr<base::SingleThreadTaskRunner>& main_task_runner, 172 scoped_refptr<base::SingleThreadTaskRunner> io_task_runner)
152 const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner) 173 : url_request_context_(new SimpleURLRequestContextGetter(io_task_runner)),
153 : main_task_runner_(main_task_runner), 174 io_task_runner_(std::move(io_task_runner)),
Ryan Sleevi 2016/02/23 21:01:31 CODE DESIGN: OK, so this is one of those times whe
Kevin M 2016/02/24 00:31:42 Reordered fields & initialization list based on re
154 url_request_context_(new SimpleURLRequestContextGetter(io_task_runner)) {} 175 weak_factory_(this) {}
155 176
156 AssignmentSource::~AssignmentSource() {} 177 AssignmentSource::~AssignmentSource() {}
157 178
158 void AssignmentSource::GetAssignment(const std::string& client_auth_token, 179 void AssignmentSource::GetAssignment(const std::string& client_auth_token,
159 const AssignmentCallback& callback) { 180 const AssignmentCallback& callback) {
160 DCHECK(main_task_runner_->BelongsToCurrentThread());
161
162 // Cancel any outstanding callback. 181 // Cancel any outstanding callback.
163 if (!callback_.is_null()) { 182 if (!callback_.is_null()) {
164 base::ResetAndReturn(&callback_) 183 base::ResetAndReturn(&callback_)
165 .Run(AssignmentSource::Result::RESULT_SERVER_INTERRUPTED, Assignment()); 184 .Run(AssignmentSource::Result::RESULT_SERVER_INTERRUPTED, Assignment());
166 } 185 }
167 callback_ = AssignmentCallback(callback); 186 callback_ = AssignmentCallback(callback);
168 187
169 Assignment assignment = GetCustomBlimpletAssignment(); 188 // Try to get a custom assignment on the IO thread first.
170 if (!assignment.is_null()) { 189 PostTaskAndReplyWithResult(
171 // Post the result so that the behavior of this function is consistent. 190 io_task_runner_.get(), FROM_HERE, base::Bind(&GetCustomAssignment),
172 main_task_runner_->PostTask( 191 base::Bind(&AssignmentSource::OnGetCustomAssignmentDone,
173 FROM_HERE, base::Bind(base::ResetAndReturn(&callback_), 192 weak_factory_.GetWeakPtr(), client_auth_token));
174 AssignmentSource::Result::RESULT_OK, assignment)); 193 }
194
195 void AssignmentSource::OnGetCustomAssignmentDone(
196 const std::string& client_auth_token,
197 Assignment custom_assignment) {
198 // If GetCustomAssignment succeeded, then return the custom assignment
199 // directly.
200 if (!custom_assignment.is_null()) {
201 base::ResetAndReturn(&callback_)
202 .Run(AssignmentSource::RESULT_OK, custom_assignment);
175 return; 203 return;
176 } 204 }
177 205
178 // Call out to the network for a real assignment. Build the network request 206 // Call out to the network for a real assignment. Build the network request
179 // to hit the assigner. 207 // to hit the assigner.
180 url_fetcher_ = net::URLFetcher::Create(GetBlimpAssignerURL(), 208 url_fetcher_ = net::URLFetcher::Create(GetBlimpAssignerURL(),
181 net::URLFetcher::POST, this); 209 net::URLFetcher::POST, this);
182 url_fetcher_->SetRequestContext(url_request_context_.get()); 210 url_fetcher_->SetRequestContext(url_request_context_.get());
183 url_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES | 211 url_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES |
184 net::LOAD_DO_NOT_SEND_COOKIES); 212 net::LOAD_DO_NOT_SEND_COOKIES);
185 url_fetcher_->AddExtraRequestHeader("Authorization: Bearer " + 213 url_fetcher_->AddExtraRequestHeader("Authorization: Bearer " +
186 client_auth_token); 214 client_auth_token);
187 215
188 // Write the JSON for the request data. 216 // Write the JSON for the request data.
189 base::DictionaryValue dictionary; 217 base::DictionaryValue dictionary;
190 dictionary.SetString(kProtocolVersionKey, blimp::kEngineVersion); 218 dictionary.SetString(kProtocolVersionKey, blimp::kEngineVersion);
191 std::string json; 219 std::string json;
192 base::JSONWriter::Write(dictionary, &json); 220 base::JSONWriter::Write(dictionary, &json);
193 url_fetcher_->SetUploadData("application/json", json); 221 url_fetcher_->SetUploadData("application/json", json);
194
195 url_fetcher_->Start(); 222 url_fetcher_->Start();
196 } 223 }
197 224
198 void AssignmentSource::OnURLFetchComplete(const net::URLFetcher* source) { 225 void AssignmentSource::OnURLFetchComplete(const net::URLFetcher* source) {
199 DCHECK(main_task_runner_->BelongsToCurrentThread());
200 DCHECK(!callback_.is_null()); 226 DCHECK(!callback_.is_null());
201 DCHECK_EQ(url_fetcher_.get(), source); 227 DCHECK_EQ(url_fetcher_.get(), source);
202 228
203 if (!source->GetStatus().is_success()) { 229 if (!source->GetStatus().is_success()) {
204 DVLOG(1) << "Assignment request failed due to network error: " 230 DVLOG(1) << "Assignment request failed due to network error: "
205 << net::ErrorToString(source->GetStatus().error()); 231 << net::ErrorToString(source->GetStatus().error());
206 base::ResetAndReturn(&callback_) 232 base::ResetAndReturn(&callback_)
207 .Run(AssignmentSource::Result::RESULT_NETWORK_FAILURE, Assignment()); 233 .Run(AssignmentSource::Result::RESULT_NETWORK_FAILURE, Assignment());
208 return; 234 return;
209 } 235 }
(...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after
265 if (!json->GetAsDictionary(&dict)) { 291 if (!json->GetAsDictionary(&dict)) {
266 base::ResetAndReturn(&callback_) 292 base::ResetAndReturn(&callback_)
267 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment()); 293 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
268 return; 294 return;
269 } 295 }
270 296
271 // Validate that all the expected fields are present. 297 // Validate that all the expected fields are present.
272 std::string client_token; 298 std::string client_token;
273 std::string host; 299 std::string host;
274 int port; 300 int port;
275 std::string cert_fingerprint; 301 std::string cert_str;
276 std::string cert;
277 if (!(dict->GetString(kClientTokenKey, &client_token) && 302 if (!(dict->GetString(kClientTokenKey, &client_token) &&
278 dict->GetString(kHostKey, &host) && dict->GetInteger(kPortKey, &port) && 303 dict->GetString(kHostKey, &host) && dict->GetInteger(kPortKey, &port) &&
279 dict->GetString(kCertificateFingerprintKey, &cert_fingerprint) && 304 dict->GetString(kCertificateKey, &cert_str))) {
280 dict->GetString(kCertificateKey, &cert))) {
281 base::ResetAndReturn(&callback_) 305 base::ResetAndReturn(&callback_)
282 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment()); 306 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
283 return; 307 return;
284 } 308 }
285 309
286 net::IPAddress ip_address; 310 net::IPAddress ip_address;
287 if (!ip_address.AssignFromIPLiteral(host)) { 311 if (!ip_address.AssignFromIPLiteral(host)) {
288 base::ResetAndReturn(&callback_) 312 base::ResetAndReturn(&callback_)
289 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment()); 313 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
290 return; 314 return;
291 } 315 }
292 316
293 if (!base::IsValueInRangeForNumericType<uint16_t>(port)) { 317 if (!base::IsValueInRangeForNumericType<uint16_t>(port)) {
294 base::ResetAndReturn(&callback_) 318 base::ResetAndReturn(&callback_)
295 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment()); 319 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
296 return; 320 return;
297 } 321 }
298 322
299 Assignment assignment; 323 net::CertificateList cert_list =
324 net::X509Certificate::CreateCertificateListFromBytes(
325 cert_str.data(), cert_str.size(),
326 net::X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
327 if (cert_list.size() != 1) {
328 base::ResetAndReturn(&callback_)
329 .Run(AssignmentSource::Result::RESULT_INVALID_CERT, Assignment());
330 return;
331 }
332
300 // The assigner assumes SSL-only and all engines it assigns only communicate 333 // The assigner assumes SSL-only and all engines it assigns only communicate
301 // over SSL. 334 // over SSL.
335 Assignment assignment;
302 assignment.transport_protocol = Assignment::TransportProtocol::SSL; 336 assignment.transport_protocol = Assignment::TransportProtocol::SSL;
303 assignment.ip_endpoint = net::IPEndPoint(ip_address, port); 337 assignment.ip_endpoint = net::IPEndPoint(ip_address, port);
304 assignment.client_token = client_token; 338 assignment.client_token = client_token;
305 assignment.certificate = cert; 339 assignment.cert = std::move(cert_list[0]);
306 assignment.certificate_fingerprint = cert_fingerprint;
307 340
308 base::ResetAndReturn(&callback_) 341 base::ResetAndReturn(&callback_)
309 .Run(AssignmentSource::Result::RESULT_OK, assignment); 342 .Run(AssignmentSource::Result::RESULT_OK, assignment);
310 } 343 }
311 344
312 } // namespace client 345 } // namespace client
313 } // namespace blimp 346 } // namespace blimp
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698