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

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

Issue 1687393002: Add assigner support to Blimp (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Build the ProxyConfigService on the main thread. 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/command_line.h" 9 #include "base/command_line.h"
10 #include "base/json/json_reader.h"
11 #include "base/json/json_writer.h"
9 #include "base/location.h" 12 #include "base/location.h"
10 #include "base/numerics/safe_conversions.h" 13 #include "base/numerics/safe_conversions.h"
11 #include "base/strings/string_number_conversions.h" 14 #include "base/strings/string_number_conversions.h"
15 #include "base/values.h"
12 #include "blimp/client/app/blimp_client_switches.h" 16 #include "blimp/client/app/blimp_client_switches.h"
17 #include "blimp/common/protocol_version.h"
13 #include "net/base/ip_address.h" 18 #include "net/base/ip_address.h"
14 #include "net/base/ip_endpoint.h" 19 #include "net/base/ip_endpoint.h"
20 #include "net/base/load_flags.h"
21 #include "net/base/url_util.h"
22 #include "net/http/http_status_code.h"
23 #include "net/proxy/proxy_config_service.h"
24 #include "net/proxy/proxy_service.h"
25 #include "net/url_request/url_fetcher.h"
26 #include "net/url_request/url_request_context.h"
27 #include "net/url_request/url_request_context_builder.h"
28 #include "net/url_request/url_request_context_getter.h"
15 29
16 namespace blimp { 30 namespace blimp {
31 namespace client {
32
17 namespace { 33 namespace {
18 34
19 // TODO(kmarshall): Take values from configuration data. 35 // Assignment request JSON keys.
20 const char kDummyClientToken[] = "MyVoiceIsMyPassport"; 36 const char kProtocolVersionKey[] = "protocol_version";
21 const std::string kDefaultBlimpletIPAddress = "127.0.0.1"; 37
22 const uint16_t kDefaultBlimpletTCPPort = 25467; 38 // Assignment response JSON keys.
23 39 const char kClientTokenKey[] = "clientToken";
24 net::IPAddress GetBlimpletIPAddress() { 40 const char kHostKey[] = "host";
41 const char kPortKey[] = "port";
42 const char kCertificateFingerprintKey[] = "certificateFingerprint";
43 const char kCertificateKey[] = "certificate";
44
45 Assignment GetCustomBlimpletAssignment() {
46 GURL url(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
47 switches::kBlimpletEndpoint));
48
25 std::string host; 49 std::string host;
26 if (base::CommandLine::ForCurrentProcess()->HasSwitch( 50 int port;
27 switches::kBlimpletHost)) { 51 if (url.is_empty() || !url.is_valid() || !url.has_scheme() ||
28 host = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( 52 !net::ParseHostAndPort(url.path(), &host, &port)) {
29 switches::kBlimpletHost); 53 return Assignment();
30 } else { 54 }
31 host = kDefaultBlimpletIPAddress; 55
32 }
33 net::IPAddress ip_address; 56 net::IPAddress ip_address;
34 if (!ip_address.AssignFromIPLiteral(host)) 57 if (!ip_address.AssignFromIPLiteral(host)) {
35 CHECK(false) << "Invalid BlimpletAssignment host " << host; 58 CHECK(false) << "Invalid BlimpletAssignment host " << host;
36 return ip_address; 59 }
37 } 60
38 61 if (!base::IsValueInRangeForNumericType<uint16_t>(port)) {
39 uint16_t GetBlimpletTCPPort() { 62 CHECK(false) << "Invalid BlimpletAssignment port " << port;
40 if (base::CommandLine::ForCurrentProcess()->HasSwitch( 63 }
41 switches::kBlimpletTCPPort)) { 64
42 std::string port_str = 65 Assignment::TransportProtocol protocol =
43 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( 66 Assignment::TransportProtocol::UNKNOWN;
44 switches::kBlimpletTCPPort); 67 if (url.has_scheme()) {
45 uint port_64t; 68 if (url.SchemeIs("ssl")) {
46 if (!base::StringToUint(port_str, &port_64t) || 69 protocol = Assignment::TransportProtocol::SSL;
47 !base::IsValueInRangeForNumericType<uint16_t>(port_64t)) { 70 } else if (url.SchemeIs("tcp")) {
48 CHECK(false) << "Invalid BlimpletAssignment port " << port_str; 71 protocol = Assignment::TransportProtocol::TCP;
72 } else if (url.SchemeIs("quic")) {
73 protocol = Assignment::TransportProtocol::QUIC;
74 } else {
75 CHECK(false) << "Invalid BlimpletAssignment scheme " << url.scheme();
49 } 76 }
50 return base::checked_cast<uint16_t>(port_64t); 77 }
51 } else { 78
52 return kDefaultBlimpletTCPPort; 79 Assignment assignment;
53 } 80 assignment.transport_protocol = protocol;
54 } 81 assignment.ip_endpoint = net::IPEndPoint(ip_address, port);
82 assignment.client_token = kDummyClientToken;
83 return assignment;
84 }
85
86 GURL GetBlimpAssignerURL() {
87 // TODO(dtrainor): Add a way to specify another assigner.
88 return GURL(kDefaultAssignerURL);
89 }
90
91 class SimpleURLRequestContextGetter : public net::URLRequestContextGetter {
92 public:
93 SimpleURLRequestContextGetter(
94 const scoped_refptr<base::SingleThreadTaskRunner>& io_loop_task_runner)
95 : io_loop_task_runner_(io_loop_task_runner),
96 proxy_config_service_(net::ProxyService::CreateSystemProxyConfigService(
97 io_loop_task_runner_, io_loop_task_runner_)) {}
98
99 // net::URLRequestContextGetter implementation.
100 net::URLRequestContext* GetURLRequestContext() override {
101 if (!url_request_context_) {
102 net::URLRequestContextBuilder builder;
103 builder.set_proxy_config_service(std::move(proxy_config_service_));
104 url_request_context_ = builder.Build();
105 }
106
107 return url_request_context_.get();
108 }
109
110 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
111 const override {
112 return io_loop_task_runner_;
113 }
114
115 private:
116 ~SimpleURLRequestContextGetter() override {}
117
118 scoped_refptr<base::SingleThreadTaskRunner> io_loop_task_runner_;
119 scoped_ptr<net::URLRequestContext> url_request_context_;
120
121 // Temporary storage for the ProxyConfigService, which needs to be created on
122 // the main thread but cleared on the IO thread. This will be built in the
123 // constructor and cleared on the IO thread. Due to the usage of this class
124 // this is safe.
125 scoped_ptr<net::ProxyConfigService> proxy_config_service_;
126
127 DISALLOW_COPY_AND_ASSIGN(SimpleURLRequestContextGetter);
128 };
55 129
56 } // namespace 130 } // namespace
57 131
58 namespace client { 132 Assignment::Assignment() : transport_protocol(TransportProtocol::UNKNOWN) {}
133
134 Assignment::~Assignment() {}
135
136 bool Assignment::is_null() const {
137 return ip_endpoint.address().empty() || ip_endpoint.port() == 0 ||
138 transport_protocol == TransportProtocol::UNKNOWN;
139 }
59 140
60 AssignmentSource::AssignmentSource( 141 AssignmentSource::AssignmentSource(
61 const scoped_refptr<base::SingleThreadTaskRunner>& main_task_runner) 142 const scoped_refptr<base::SingleThreadTaskRunner>& main_task_runner,
62 : main_task_runner_(main_task_runner) {} 143 const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner)
144 : main_task_runner_(main_task_runner),
145 url_request_context_(new SimpleURLRequestContextGetter(io_task_runner)) {}
63 146
64 AssignmentSource::~AssignmentSource() {} 147 AssignmentSource::~AssignmentSource() {}
65 148
66 void AssignmentSource::GetAssignment(const AssignmentCallback& callback) { 149 void AssignmentSource::GetAssignment(const std::string& client_auth_token,
150 const AssignmentCallback& callback) {
67 DCHECK(main_task_runner_->BelongsToCurrentThread()); 151 DCHECK(main_task_runner_->BelongsToCurrentThread());
152
153 // Cancel any outstanding callback.
154 if (!callback_.is_null()) {
155 base::ResetAndReturn(&callback_)
156 .Run(AssignmentSource::Result::RESULT_SERVER_INTERRUPTED, Assignment());
157 }
158 callback_ = AssignmentCallback(callback);
159
160 Assignment assignment = GetCustomBlimpletAssignment();
161 if (!assignment.is_null()) {
162 // Post the result so that the behavior of this function is consistent.
163 main_task_runner_->PostTask(
164 FROM_HERE, base::Bind(base::ResetAndReturn(&callback_),
165 AssignmentSource::Result::RESULT_OK, assignment));
166 return;
167 }
168
169 // Call out to the network for a real assignment. Build the network request
170 // to hit the assigner.
171 url_fetcher_ = net::URLFetcher::Create(GetBlimpAssignerURL(),
172 net::URLFetcher::POST, this);
173 url_fetcher_->SetRequestContext(url_request_context_.get());
174 url_fetcher_->SetAutomaticallyRetryOn5xx(false);
175 url_fetcher_->SetAutomaticallyRetryOnNetworkChanges(0);
mmenke 2016/02/18 16:06:11 optional: Suggest just leaving these as defaults,
David Trainor- moved to gerrit 2016/02/18 17:38:25 Ah good point thanks!
176 url_fetcher_->SetLoadFlags(net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE |
mmenke 2016/02/18 16:06:11 These first two flags also disable the DNS cache,
David Trainor- moved to gerrit 2016/02/18 17:38:25 Yeah it's only ever used for querying assignments
177 net::LOAD_DO_NOT_SAVE_COOKIES |
178 net::LOAD_DO_NOT_SEND_COOKIES);
179 url_fetcher_->AddExtraRequestHeader("Authorization: Bearer " +
180 client_auth_token);
181
182 // Write the JSON for the request data.
183 base::DictionaryValue dictionary;
184 dictionary.SetString(kProtocolVersionKey, blimp::kEngineVersion);
185 std::string json;
186 base::JSONWriter::Write(dictionary, &json);
187 url_fetcher_->SetUploadData("application/json", json);
188
189 url_fetcher_->Start();
mmenke 2016/02/18 16:06:11 Just FYI: The URLFetcher continues downloading th
David Trainor- moved to gerrit 2016/02/18 17:38:25 Ah that's good to know. I think we're okay becaus
190 }
191
192 void AssignmentSource::OnURLFetchComplete(const net::URLFetcher* source) {
193 DCHECK(!callback_.is_null());
nyquist 2016/02/18 01:58:40 Optional nit: How do you feel about DCHECK-ing Bel
David Trainor- moved to gerrit 2016/02/18 16:01:54 Ah I didn't really assume. The URLFetcher documen
194 DCHECK_EQ(url_fetcher_.get(), source);
195
196 if (!source->GetStatus().is_success()) {
197 base::ResetAndReturn(&callback_)
198 .Run(AssignmentSource::Result::RESULT_NETWORK_FAILURE, Assignment());
mmenke 2016/02/18 16:06:11 You may be interested in looking at the specific e
David Trainor- moved to gerrit 2016/02/18 17:38:25 Yeah it might be useful to do this in the future.
199 return;
200 }
201
202 switch (source->GetResponseCode()) {
203 case net::HTTP_OK:
204 ParseAssignerResponse();
205 break;
206 case net::HTTP_BAD_REQUEST:
207 base::ResetAndReturn(&callback_)
208 .Run(AssignmentSource::Result::RESULT_BAD_REQUEST, Assignment());
209 break;
210 case net::HTTP_UNAUTHORIZED:
211 base::ResetAndReturn(&callback_)
212 .Run(AssignmentSource::Result::RESULT_EXPIRED_ACCESS_TOKEN,
213 Assignment());
214 break;
215 case net::HTTP_FORBIDDEN:
216 base::ResetAndReturn(&callback_)
217 .Run(AssignmentSource::Result::RESULT_USER_INVALID, Assignment());
218 break;
219 case 429: // Too Many Requests
220 base::ResetAndReturn(&callback_)
221 .Run(AssignmentSource::Result::RESULT_OUT_OF_VMS, Assignment());
222 break;
223 case net::HTTP_INTERNAL_SERVER_ERROR:
224 base::ResetAndReturn(&callback_)
225 .Run(AssignmentSource::Result::RESULT_SERVER_ERROR, Assignment());
226 break;
227 default:
228 base::ResetAndReturn(&callback_)
229 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
230 break;
231 }
232 }
233
234 void AssignmentSource::ParseAssignerResponse() {
235 DCHECK(url_fetcher_.get());
236 DCHECK(url_fetcher_->GetStatus().is_success());
237 DCHECK_EQ(net::HTTP_OK, url_fetcher_->GetResponseCode());
238
239 // Grab the response from the assigner request.
240 std::string response;
241 if (!url_fetcher_->GetResponseAsString(&response)) {
242 base::ResetAndReturn(&callback_)
243 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
244 return;
245 }
246
247 // Attempt to interpret the response as JSON and treat it as a dictionary.
248 scoped_ptr<base::Value> json = base::JSONReader::Read(response);
249 if (!json) {
250 base::ResetAndReturn(&callback_)
251 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
252 return;
253 }
254
255 const base::DictionaryValue* dict;
256 if (!json->GetAsDictionary(&dict)) {
257 base::ResetAndReturn(&callback_)
258 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
259 return;
260 }
261
262 // Validate that all the expected fields are present.
263 std::string client_token;
264 std::string host;
265 int port;
266 std::string cert_fingerprint;
267 std::string cert;
268 if (!(dict->GetString(kClientTokenKey, &client_token) &&
269 dict->GetString(kHostKey, &host) && dict->GetInteger(kPortKey, &port) &&
270 dict->GetString(kCertificateFingerprintKey, &cert_fingerprint) &&
271 dict->GetString(kCertificateKey, &cert))) {
272 base::ResetAndReturn(&callback_)
273 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
274 return;
275 }
276
277 net::IPAddress ip_address;
278 if (!ip_address.AssignFromIPLiteral(host)) {
279 base::ResetAndReturn(&callback_)
280 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
281 return;
282 }
283
284 if (!base::IsValueInRangeForNumericType<uint16_t>(port)) {
285 base::ResetAndReturn(&callback_)
286 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
287 return;
288 }
289
68 Assignment assignment; 290 Assignment assignment;
69 assignment.ip_endpoint = 291 assignment.transport_protocol = Assignment::TransportProtocol::SSL;
nyquist 2016/02/18 01:58:40 Nit: Could you clarify that this is intentional, a
David Trainor- moved to gerrit 2016/02/18 16:01:54 Done.
70 net::IPEndPoint(GetBlimpletIPAddress(), GetBlimpletTCPPort()); 292 assignment.ip_endpoint = net::IPEndPoint(ip_address, port);
71 assignment.client_token = kDummyClientToken; 293 assignment.client_token = client_token;
72 main_task_runner_->PostTask(FROM_HERE, base::Bind(callback, assignment)); 294 assignment.certificate = cert;
295 assignment.certificate_fingerprint = cert_fingerprint;
296
297 base::ResetAndReturn(&callback_)
298 .Run(AssignmentSource::Result::RESULT_OK, assignment);
73 } 299 }
74 300
75 } // namespace client 301 } // namespace client
76 } // namespace blimp 302 } // namespace blimp
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698