quirks_client.cc 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. #include "components/quirks/quirks_client.h"
  5. #include "base/base64.h"
  6. #include "base/bind.h"
  7. #include "base/files/file_util.h"
  8. #include "base/json/json_reader.h"
  9. #include "base/strings/escape.h"
  10. #include "base/strings/stringprintf.h"
  11. #include "base/task/task_runner_util.h"
  12. #include "components/prefs/scoped_user_pref_update.h"
  13. #include "components/quirks/quirks_manager.h"
  14. #include "components/version_info/version_info.h"
  15. #include "net/base/load_flags.h"
  16. #include "net/http/http_status_code.h"
  17. #include "services/network/public/cpp/resource_request.h"
  18. #include "services/network/public/cpp/simple_url_loader.h"
  19. #include "services/network/public/mojom/url_response_head.mojom.h"
  20. namespace quirks {
  21. namespace {
  22. const char kQuirksUrlFormat[] =
  23. "https://chromeosquirksserver-pa.googleapis.com/v2/display/%s/clients"
  24. "/chromeos/M%d?";
  25. const int kMaxServerFailures = 10;
  26. const net::BackoffEntry::Policy kDefaultBackoffPolicy = {
  27. 1, // Initial errors before applying backoff
  28. 10000, // 10 seconds.
  29. 2, // Factor by which the waiting time will be multiplied.
  30. 0, // Random fuzzing percentage.
  31. 1000 * 3600 * 6, // Max wait between requests = 6 hours.
  32. -1, // Don't discard entry.
  33. true, // Use initial delay after first error.
  34. };
  35. bool WriteIccFile(const base::FilePath file_path, const std::string& data) {
  36. int bytes_written = base::WriteFile(file_path, data.data(), data.length());
  37. if (bytes_written == -1)
  38. PLOG(ERROR) << "Write failed: " << file_path.value();
  39. else
  40. VLOG(1) << bytes_written << "bytes written to: " << file_path.value();
  41. return (bytes_written != -1);
  42. }
  43. } // namespace
  44. ////////////////////////////////////////////////////////////////////////////////
  45. // QuirksClient
  46. QuirksClient::QuirksClient(int64_t product_id,
  47. const std::string& display_name,
  48. RequestFinishedCallback on_request_finished,
  49. QuirksManager* manager)
  50. : product_id_(product_id),
  51. display_name_(display_name),
  52. on_request_finished_(std::move(on_request_finished)),
  53. manager_(manager),
  54. icc_path_(manager->delegate()->GetDisplayProfileDirectory().Append(
  55. IdToFileName(product_id))),
  56. backoff_entry_(&kDefaultBackoffPolicy) {}
  57. QuirksClient::~QuirksClient() {}
  58. void QuirksClient::StartDownload() {
  59. DCHECK(thread_checker_.CalledOnValidThread());
  60. // URL of icc file on Quirks Server.
  61. int major_version = atoi(version_info::GetVersionNumber().c_str());
  62. std::string url = base::StringPrintf(
  63. kQuirksUrlFormat, IdToHexString(product_id_).c_str(), major_version);
  64. if (!display_name_.empty()) {
  65. url += "display_name=" + base::EscapeQueryParamValue(display_name_, true) +
  66. "&";
  67. }
  68. VLOG(2) << "Preparing to download\n " << url << "\nto file "
  69. << icc_path_.value();
  70. url += "key=" + manager_->delegate()->GetApiKey();
  71. auto resource_request = std::make_unique<network::ResourceRequest>();
  72. resource_request->url = GURL(url);
  73. resource_request->load_flags =
  74. net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE;
  75. resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  76. net::NetworkTrafficAnnotationTag traffic_annotation =
  77. net::DefineNetworkTrafficAnnotation("quirks_display_fetcher", R"(
  78. semantics {
  79. sender: "Quirks"
  80. description: "Download custom display calibration file."
  81. trigger:
  82. "Chrome OS attempts to download monitor calibration files on"
  83. "first device login, and then once every 30 days."
  84. data: "ICC files to calibrate and improve the quality of a display."
  85. destination: GOOGLE_OWNED_SERVICE
  86. }
  87. policy {
  88. cookies_allowed: NO
  89. chrome_policy {
  90. DeviceQuirksDownloadEnabled {
  91. DeviceQuirksDownloadEnabled: false
  92. }
  93. }
  94. }
  95. )");
  96. url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
  97. traffic_annotation);
  98. url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
  99. manager_->url_loader_factory(),
  100. base::BindOnce(&QuirksClient::OnDownloadComplete,
  101. base::Unretained(this)));
  102. }
  103. void QuirksClient::OnDownloadComplete(
  104. std::unique_ptr<std::string> response_body) {
  105. DCHECK(thread_checker_.CalledOnValidThread());
  106. // Take ownership of the loader in this scope.
  107. std::unique_ptr<network::SimpleURLLoader> url_loader = std::move(url_loader_);
  108. int response_code = 0;
  109. if (url_loader->ResponseInfo() && url_loader->ResponseInfo()->headers)
  110. response_code = url_loader->ResponseInfo()->headers->response_code();
  111. VLOG(2) << "QuirksClient::OnURLFetchComplete():"
  112. << " net_error=" << url_loader->NetError()
  113. << ", response_code=" << response_code;
  114. if (response_code == net::HTTP_NOT_FOUND) {
  115. VLOG(1) << IdToFileName(product_id_) << " not found on Quirks server.";
  116. Shutdown(false);
  117. return;
  118. }
  119. if (url_loader->NetError() != net::OK) {
  120. if (backoff_entry_.failure_count() >= kMaxServerFailures) {
  121. // After 10 retires (5+ hours), give up, and try again in a month.
  122. VLOG(1) << "Too many retries; Quirks Client shutting down.";
  123. Shutdown(false);
  124. return;
  125. }
  126. Retry();
  127. return;
  128. }
  129. DCHECK(response_body); // Guaranteed to be valid if NetError() is net::OK.
  130. VLOG(2) << "Quirks server response:\n" << *response_body;
  131. // Parse response data and write to file on file thread.
  132. std::string data;
  133. if (!ParseResult(*response_body, &data)) {
  134. Shutdown(false);
  135. return;
  136. }
  137. base::PostTaskAndReplyWithResult(
  138. manager_->task_runner(), FROM_HERE,
  139. base::BindOnce(&WriteIccFile, icc_path_, data),
  140. base::BindOnce(&QuirksClient::Shutdown, weak_ptr_factory_.GetWeakPtr()));
  141. }
  142. void QuirksClient::Shutdown(bool success) {
  143. DCHECK(thread_checker_.CalledOnValidThread());
  144. std::move(on_request_finished_)
  145. .Run(success ? icc_path_ : base::FilePath(), true);
  146. manager_->ClientFinished(this);
  147. }
  148. void QuirksClient::Retry() {
  149. DCHECK(thread_checker_.CalledOnValidThread());
  150. backoff_entry_.InformOfRequest(false);
  151. const base::TimeDelta delay = backoff_entry_.GetTimeUntilRelease();
  152. VLOG(1) << "Schedule next Quirks download attempt in " << delay.InSecondsF()
  153. << " seconds (retry = " << backoff_entry_.failure_count() << ").";
  154. request_scheduled_.Start(FROM_HERE, delay, this,
  155. &QuirksClient::StartDownload);
  156. }
  157. bool QuirksClient::ParseResult(const std::string& result, std::string* data) {
  158. std::string data64;
  159. const base::DictionaryValue* dict;
  160. std::unique_ptr<base::Value> json = base::JSONReader::ReadDeprecated(result);
  161. if (!json || !json->GetAsDictionary(&dict) ||
  162. !dict->GetString("icc", &data64)) {
  163. VLOG(1) << "Failed to parse JSON icc data";
  164. return false;
  165. }
  166. if (!base::Base64Decode(data64, data)) {
  167. VLOG(1) << "Failed to decode Base64 icc data";
  168. return false;
  169. }
  170. return true;
  171. }
  172. } // namespace quirks