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

Side by Side Diff: components/quirks_client/quirks_client.cc

Issue 1528963002: Quirks Client for downloading and providing display profiles (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Second round of review fixes, incomplete 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
(Empty)
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
3 // found in the LICENSE file.
4
5 #include "components/quirks_client/quirks_client.h"
6
7 #include "base/base64.h"
8 #include "base/command_line.h"
9 #include "base/files/file_util.h"
10 #include "base/format_macros.h"
11 #include "base/json/json_reader.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/path_service.h"
14 #include "base/prefs/scoped_user_pref_update.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/task_runner_util.h"
17 #include "chromeos/chromeos_paths.h"
18 #include "components/quirks_client/quirks_client_manager.h"
19 #include "components/quirks_client/switches.h"
20 #include "net/base/load_flags.h"
21 #include "net/http/http_status_code.h"
22 #include "net/url_request/url_fetcher.h"
23 #include "net/url_request/url_request_context_getter.h"
24
25 namespace quirks_client {
26
27 namespace {
28
29 const char kQuirksUrlFormat[] =
30 "https://qa-quirksserver-pa.sandbox.googleapis.com/v2/display/%08" PRIx64
31 "/clients/chromeos/M%d";
32
33 // Sleep between Quirks retries (will be multiplied by squared retry number).
34 const unsigned kRetrySleepSeconds = 10;
35
36 // Retry is infinite with increasing intervals. When calculated delay becomes
37 // longer than maximum (kMaxRetrySleepSeconds) it is set to the maximum.
38 const double kMaxRetrySleepSeconds = 6 * 3600; // 6 hours
39
40 // Access to singleton QuirksClientManager.
41 QuirksClientManager* GetManager() {
42 return QuirksClientManager::Get();
43 }
44
45 // Check if file exists, VLOG results.
46 bool CheckAndLogFile(const base::FilePath& path) {
47 DCHECK(!GetManager() ||
48 GetManager()->blocking_pool()->RunsTasksOnCurrentThread());
49 const bool exists = base::PathExists(path);
50 VLOG(1) << (exists ? "File" : "No File") << " found at " << path.value();
51 // TODO(glevin): If file exists, do we want to implement a hash to verify that
52 // the file hasn't been corrupted or tampered with?
53 return exists;
54 }
55
56 } // namespace
57
58 ////////////////////////////////////////////////////////////////////////////////
59 // QuirksClient
60
61 QuirksClient::QuirksClient(int64_t product_id,
62 const DownloadFinishedCallback& on_download_finished)
63 : product_id_(product_id),
64 on_download_finished_(on_download_finished),
65 icc_path_(GetManager()->delegate()->GetDisplayProfileDirectory().Append(
66 IdToHexString(product_id) + ".icc")),
67 request_reason_(FIRST),
68 retries_(0),
69 weak_ptr_factory_(this) {}
70
71 QuirksClient::~QuirksClient() {}
72
73 void QuirksClient::StartDownload() {
74 DCHECK(base::MessageLoopForUI::IsCurrent());
75
76 // URL of icc file on Quirks Server.
77 // TODO(glevin): Replace |44| with actual version. This is fine for now, as
78 // the Quirks Server is not currently using this value.
79 std::string url = base::StringPrintf(kQuirksUrlFormat, product_id_, 44);
80
81 VLOG(2) << "Preparing to download\n " << url << "\nto file "
82 << icc_path_.value();
83
84 url += "?key=";
85 url += GetManager()->delegate()->GetApiKey();
86
87 url_fetcher_ = GetManager()->CreateURLFetcher(url, this);
88 url_fetcher_->SetRequestContext(GetManager()->url_context_getter());
89 url_fetcher_->SetLoadFlags(net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE |
90 net::LOAD_DO_NOT_SAVE_COOKIES |
91 net::LOAD_DO_NOT_SEND_COOKIES |
92 net::LOAD_DO_NOT_SEND_AUTH_DATA);
93 url_fetcher_->Start();
94 }
95
96 // static
97 // Must be called on io thread.
98 base::FilePath QuirksClient::RequestIccProfilePath(
99 int64_t product_id,
100 const DownloadFinishedCallback& on_download_finished) {
101 std::string file_name = IdToHexString(product_id) + ".icc";
102
103 // First, look for icc file in old read-only location. If there, we don't use
104 // the Quirks server.
105 // TODO(glevin): Awaiting final decision on how to handle old read-only files.
106 base::FilePath path;
107 CHECK(
108 PathService::Get(chromeos::DIR_DEVICE_COLOR_CALIBRATION_PROFILES, &path));
109 path = path.Append(file_name);
110 if (CheckAndLogFile(path))
111 return path;
112
113 // If Quirks Client is disabled, no other icc file is available.
114 if (!IsEnabled()) {
115 VLOG(1) << "Quirks Client disabled, no built-in icc file available.";
116 return base::FilePath();
117 }
118
119 if (!GetManager()) {
120 VLOG(1) << "Quirks Client Manager not initialized; can't start Client.";
121 return base::FilePath();
122 }
123
124 // Check if QuirksClient has already downloaded icc file from server.
125 path =
126 GetManager()->delegate()->GetDisplayProfileDirectory().Append(file_name);
127 if (CheckAndLogFile(path))
128 return path;
129
130 // TODO(glevin): Eventually we'll want to check the server for updates to
131 // files, so we'll still want to get down here even if we find the icc file.
132
133 GetManager()->RunClient(product_id, on_download_finished);
Greg Levin 2016/02/09 18:56:38 TODO: Possible refactor needed in next patch.
134
135 return base::FilePath();
136 }
137
138 // static
139 bool QuirksClient::IsEnabled() {
140 return base::CommandLine::ForCurrentProcess()->HasSwitch(
141 switches::kEnableDisplayQuirksClient);
142 }
143
144 // static
145 std::string QuirksClient::IdToHexString(int64_t product_id) {
146 return base::StringPrintf("%08" PRIx64, product_id);
147 }
148
149 void QuirksClient::OnURLFetchComplete(const net::URLFetcher* source) {
150 DCHECK(base::MessageLoopForUI::IsCurrent());
151 DCHECK_EQ(url_fetcher_.get(), source);
152
153 const net::URLRequestStatus status = source->GetStatus();
154 const int response_code = source->GetResponseCode();
155 const bool server_error =
156 !status.is_success() ||
157 (response_code >= net::HTTP_INTERNAL_SERVER_ERROR &&
158 response_code < (net::HTTP_INTERNAL_SERVER_ERROR + 100));
159
160 VLOG(2) << "QuirksClient::OnURLFetchComplete():"
161 << " status=" << status.status()
162 << ", response_code=" << response_code
163 << ", server_error=" << server_error;
164
165 GetManager()->RecordReasonUmaStat(request_reason_);
166
167 if (response_code == net::HTTP_NOT_FOUND) {
168 VLOG(1) << IdToHexString(product_id_) << ".icc not found on Quirks server.";
169 GetManager()->RecordFileFoundUmaStat(false);
170 Shutdown(false);
171 return;
172 }
173
174 if (server_error) {
175 url_fetcher_.reset();
176 Retry();
177 return;
178 }
179
180 GetManager()->RecordFileFoundUmaStat(true);
181 std::string response;
182 url_fetcher_->GetResponseAsString(&response);
183 VLOG(2) << "Quirks server response:\n" << response;
184
185 // Parse response data and write to file on io thread.
186 std::string data;
187 if (!ParseResult(response, &data))
188 return;
189
190 base::PostTaskAndReplyWithResult(
191 GetManager()->blocking_pool(), FROM_HERE,
192 base::Bind(&WriteIccFile, icc_path_, data),
193 base::Bind(&QuirksClient::Shutdown, weak_ptr_factory_.GetWeakPtr()));
194 }
195
196 void QuirksClient::Shutdown(bool success) {
197 DCHECK(base::MessageLoopForUI::IsCurrent());
198 if (!on_download_finished_.is_null())
199 on_download_finished_.Run(success ? icc_path_ : base::FilePath());
200
201 GetManager()->SetLastServerCheck(product_id_, base::Time::Now());
202 base::MessageLoopForUI::current()->DeleteSoon(FROM_HERE, this);
203 }
204
205 void QuirksClient::Retry() {
206 DCHECK(base::MessageLoopForUI::IsCurrent());
207 ++retries_;
208
209 const double delay_seconds =
210 std::min(static_cast<double>(retries_) * retries_ * kRetrySleepSeconds,
211 kMaxRetrySleepSeconds);
212 const base::TimeDelta delay = base::TimeDelta::FromSecondsD(delay_seconds);
213
214 VLOG(1) << "Schedule next Quirks download attempt in " << delay.InSecondsF()
215 << " seconds (retry = " << retries_ << ").";
216 request_scheduled_.Start(FROM_HERE, delay, this,
217 &QuirksClient::StartDownload);
218 }
219
220 // static
221 bool QuirksClient::WriteIccFile(const base::FilePath file_path,
222 const std::string& data) {
223 DCHECK(GetManager()->blocking_pool()->RunsTasksOnCurrentThread());
224 int bytes_written = base::WriteFile(file_path, data.data(), data.length());
225 if (bytes_written == -1)
226 VLOG(1) << "Failed to write: " << file_path.value() << ", err = " << errno;
227 else
228 VLOG(1) << bytes_written << "bytes written to: " << file_path.value();
229
230 return (bytes_written != -1);
231 }
232
233 bool QuirksClient::ParseResult(const std::string& result, std::string* data) {
234 std::string data64;
235 const base::DictionaryValue* dict;
236 scoped_ptr<base::Value> json = base::JSONReader::Read(result);
237 if (!json || !json->GetAsDictionary(&dict) ||
238 !dict->GetString("icc", &data64)) {
239 VLOG(1) << "Failed to parse JSON icc data";
240 return false;
241 }
242
243 if (!base::Base64Decode(data64, data)) {
244 VLOG(1) << "Failed to decode Base64 icc data";
245 return false;
246 }
247
248 return true;
249 }
250
251 } // namespace chromeos
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698