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

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: Added tests and addressed comments 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() {
25 std::string host; 46 std::string host;
26 if (base::CommandLine::ForCurrentProcess()->HasSwitch( 47 int port;
27 switches::kBlimpletHost)) { 48
28 host = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( 49 std::string blimplet_endpoint =
29 switches::kBlimpletHost); 50 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
30 } else { 51 switches::kBlimpletEndpoint);
31 host = kDefaultBlimpletIPAddress; 52 if (blimplet_endpoint.empty() ||
32 } 53 !net::ParseHostAndPort(blimplet_endpoint, &host, &port)) {
54 return Assignment();
55 }
56
33 net::IPAddress ip_address; 57 net::IPAddress ip_address;
34 if (!ip_address.AssignFromIPLiteral(host)) 58 if (!ip_address.AssignFromIPLiteral(host)) {
35 CHECK(false) << "Invalid BlimpletAssignment host " << host; 59 CHECK(false) << "Invalid BlimpletAssignment host " << host;
36 return ip_address; 60 }
37 } 61
38 62 if (!base::IsValueInRangeForNumericType<uint16_t>(port)) {
39 uint16_t GetBlimpletTCPPort() { 63 CHECK(false) << "Invalid BlimpletAssignment port " << port;
40 if (base::CommandLine::ForCurrentProcess()->HasSwitch( 64 }
41 switches::kBlimpletTCPPort)) { 65
42 std::string port_str = 66 Assignment assignment;
43 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( 67 assignment.ip_endpoint = net::IPEndPoint(ip_address, port);
44 switches::kBlimpletTCPPort); 68 assignment.client_token = kDummyClientToken;
45 uint port_64t; 69 return assignment;
46 if (!base::StringToUint(port_str, &port_64t) || 70 }
47 !base::IsValueInRangeForNumericType<uint16_t>(port_64t)) { 71
48 CHECK(false) << "Invalid BlimpletAssignment port " << port_str; 72 GURL GetBlimpAssignerURL() {
73 // TODO(dtrainor): Add a way to specify another assigner.
74 return GURL(kDefaultAssignerURL);
75 }
76
77 class SimpleURLRequestContextGetter : public net::URLRequestContextGetter {
78 public:
79 SimpleURLRequestContextGetter(
80 const scoped_refptr<base::SingleThreadTaskRunner>& io_loop_task_runner)
81 : io_loop_task_runner_(io_loop_task_runner) {}
82
83 // net::URLRequestContextGetter implementation.
84 net::URLRequestContext* GetURLRequestContext() override {
85 if (!url_request_context_) {
86 net::URLRequestContextBuilder builder;
87 builder.set_proxy_config_service(
88 net::ProxyService::CreateSystemProxyConfigService(
89 io_loop_task_runner_, base::ThreadTaskRunnerHandle::Get()));
90 url_request_context_ = builder.Build();
49 } 91 }
50 return base::checked_cast<uint16_t>(port_64t); 92
51 } else { 93 return url_request_context_.get();
52 return kDefaultBlimpletTCPPort; 94 }
53 } 95
54 } 96 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
97 const override {
98 return io_loop_task_runner_;
99 }
100
101 private:
102 ~SimpleURLRequestContextGetter() override {}
103
104 scoped_refptr<base::SingleThreadTaskRunner> io_loop_task_runner_;
105 scoped_ptr<net::URLRequestContext> url_request_context_;
106
107 DISALLOW_COPY_AND_ASSIGN(SimpleURLRequestContextGetter);
108 };
55 109
56 } // namespace 110 } // namespace
57 111
58 namespace client { 112 Assignment::Assignment() {}
113
114 Assignment::~Assignment() {}
115
116 bool Assignment::is_null() const {
117 return ip_endpoint.address().empty() || ip_endpoint.port() == 0;
118 }
59 119
60 AssignmentSource::AssignmentSource( 120 AssignmentSource::AssignmentSource(
61 const scoped_refptr<base::SingleThreadTaskRunner>& main_task_runner) 121 const scoped_refptr<base::SingleThreadTaskRunner>& main_task_runner,
62 : main_task_runner_(main_task_runner) {} 122 const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner)
123 : main_task_runner_(main_task_runner),
124 url_request_context_(new SimpleURLRequestContextGetter(io_task_runner)) {}
63 125
64 AssignmentSource::~AssignmentSource() {} 126 AssignmentSource::~AssignmentSource() {}
65 127
66 void AssignmentSource::GetAssignment(const AssignmentCallback& callback) { 128 void AssignmentSource::GetAssignment(const std::string& client_auth_token,
129 const AssignmentCallback& callback) {
67 DCHECK(main_task_runner_->BelongsToCurrentThread()); 130 DCHECK(main_task_runner_->BelongsToCurrentThread());
131
132 // Cancel any outstanding callback.
133 if (!callback_.is_null()) {
134 base::ResetAndReturn(&callback_)
135 .Run(AssignmentSource::Result::RESULT_SERVER_INTERRUPTED, Assignment());
136 }
137 callback_ = AssignmentCallback(callback);
138
139 Assignment assignment = GetCustomBlimpletAssignment();
140 if (!assignment.is_null()) {
141 // Post the result so that the behavior of this function is consistent.
142 main_task_runner_->PostTask(
143 FROM_HERE, base::Bind(base::ResetAndReturn(&callback_),
144 AssignmentSource::Result::RESULT_OK, assignment));
145 return;
146 }
147
148 // Call out to the network for a real assignment. Build the network request
149 // to hit the assigner.
150 url_fetcher_ = net::URLFetcher::Create(GetBlimpAssignerURL(),
151 net::URLFetcher::POST, this);
152 url_fetcher_->SetRequestContext(url_request_context_.get());
153 url_fetcher_->SetAutomaticallyRetryOn5xx(false);
154 url_fetcher_->SetAutomaticallyRetryOnNetworkChanges(0);
155 url_fetcher_->SetLoadFlags(net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE |
156 net::LOAD_DO_NOT_SAVE_COOKIES |
157 net::LOAD_DO_NOT_SEND_COOKIES);
158 url_fetcher_->AddExtraRequestHeader("Authorization: Bearer " +
159 client_auth_token);
160
161 // Write the JSON for the request data.
162 base::DictionaryValue dictionary;
163 dictionary.SetString(kProtocolVersionKey, blimp::kEngineVersion);
164 std::string json;
165 base::JSONWriter::Write(dictionary, &json);
166 url_fetcher_->SetUploadData("application/json", json);
167
168 url_fetcher_->Start();
169 }
170
171 void AssignmentSource::OnURLFetchComplete(const net::URLFetcher* source) {
172 DCHECK(!callback_.is_null());
173 DCHECK_EQ(url_fetcher_.get(), source);
174
175 if (!source->GetStatus().is_success()) {
176 base::ResetAndReturn(&callback_)
177 .Run(AssignmentSource::Result::RESULT_NETWORK_FAILURE, Assignment());
178 return;
179 }
180
181 switch (source->GetResponseCode()) {
182 case net::HTTP_OK:
183 ParseAssignerResponse();
184 break;
185 case net::HTTP_BAD_REQUEST:
186 base::ResetAndReturn(&callback_)
187 .Run(AssignmentSource::Result::RESULT_BAD_REQUEST, Assignment());
188 break;
189 case net::HTTP_UNAUTHORIZED:
190 base::ResetAndReturn(&callback_)
191 .Run(AssignmentSource::Result::RESULT_EXPIRED_ACCESS_TOKEN,
192 Assignment());
193 break;
194 case net::HTTP_FORBIDDEN:
195 base::ResetAndReturn(&callback_)
196 .Run(AssignmentSource::Result::RESULT_USER_INVALID, Assignment());
197 break;
198 case 429: // Too Many Requests
199 base::ResetAndReturn(&callback_)
200 .Run(AssignmentSource::Result::RESULT_OUT_OF_VMS, Assignment());
201 break;
202 case net::HTTP_INTERNAL_SERVER_ERROR:
203 base::ResetAndReturn(&callback_)
204 .Run(AssignmentSource::Result::RESULT_SERVER_ERROR, Assignment());
205 break;
206 default:
207 base::ResetAndReturn(&callback_)
208 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
209 break;
210 }
211 }
212
213 void AssignmentSource::ParseAssignerResponse() {
214 DCHECK(url_fetcher_.get());
215 DCHECK(url_fetcher_->GetStatus().is_success());
216 DCHECK_EQ(net::HTTP_OK, url_fetcher_->GetResponseCode());
217
218 // Grab the response from the assigner request.
219 std::string response;
220 if (!url_fetcher_->GetResponseAsString(&response)) {
221 base::ResetAndReturn(&callback_)
222 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
223 return;
224 }
225
226 // Attempt to interpret the response as JSON and treat it as a dictionary.
227 scoped_ptr<base::Value> json = base::JSONReader::Read(response);
228 if (!json) {
229 base::ResetAndReturn(&callback_)
230 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
231 return;
232 }
233
234 const base::DictionaryValue* dict;
235 if (!json->GetAsDictionary(&dict)) {
236 base::ResetAndReturn(&callback_)
237 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
238 return;
239 }
240
241 // Validate that all the expected fields are present.
242 std::string client_token;
243 std::string host;
244 int port;
245 std::string cert_fingerprint;
246 std::string cert;
247 if (!(dict->GetString(kClientTokenKey, &client_token) &&
248 dict->GetString(kHostKey, &host) && dict->GetInteger(kPortKey, &port) &&
249 dict->GetString(kCertificateFingerprintKey, &cert_fingerprint) &&
250 dict->GetString(kCertificateKey, &cert))) {
251 base::ResetAndReturn(&callback_)
252 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
253 return;
254 }
255
256 net::IPAddress ip_address;
257 if (!ip_address.AssignFromIPLiteral(host)) {
258 base::ResetAndReturn(&callback_)
259 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
260 return;
261 }
262
263 if (!base::IsValueInRangeForNumericType<uint16_t>(port)) {
264 base::ResetAndReturn(&callback_)
265 .Run(AssignmentSource::Result::RESULT_BAD_RESPONSE, Assignment());
266 return;
267 }
268
68 Assignment assignment; 269 Assignment assignment;
69 assignment.ip_endpoint = 270 assignment.ip_endpoint = net::IPEndPoint(ip_address, port);
70 net::IPEndPoint(GetBlimpletIPAddress(), GetBlimpletTCPPort()); 271 assignment.client_token = client_token;
71 assignment.client_token = kDummyClientToken; 272 assignment.certificate = cert;
72 main_task_runner_->PostTask(FROM_HERE, base::Bind(callback, assignment)); 273 assignment.certificate_fingerprint = cert_fingerprint;
274
275 base::ResetAndReturn(&callback_)
276 .Run(AssignmentSource::Result::RESULT_OK, assignment);
73 } 277 }
74 278
75 } // namespace client 279 } // namespace client
76 } // namespace blimp 280 } // namespace blimp
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698