blob: 4d865868fbe48d25fc3fa247fce937d303631268 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
rspangler@google.com49fdf182009-10-10 00:57:34 +000016
Darin Petkov6a5b3222010-07-13 14:55:28 -070017#include "update_engine/omaha_request_action.h"
Darin Petkov85ced132010-09-01 10:20:56 -070018
Andrew de los Reyes08c4e272010-04-15 14:02:17 -070019#include <inttypes.h>
Darin Petkov85ced132010-09-01 10:20:56 -070020
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070021#include <limits>
David Zeuthene8ed8632014-07-24 13:38:10 -040022#include <map>
rspangler@google.com49fdf182009-10-10 00:57:34 +000023#include <sstream>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070024#include <string>
Sen Jiang8cd42342018-01-31 12:06:59 -080025#include <utility>
David Zeuthene8ed8632014-07-24 13:38:10 -040026#include <vector>
rspangler@google.com49fdf182009-10-10 00:57:34 +000027
David Zeuthen8f191b22013-08-06 12:27:50 -070028#include <base/bind.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070029#include <base/logging.h>
30#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070031#include <base/strings/string_number_conversions.h>
Sen Jiang0affc2c2017-02-10 15:55:05 -080032#include <base/strings/string_split.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070033#include <base/strings/string_util.h>
34#include <base/strings/stringprintf.h>
35#include <base/time/time.h>
Sen Jiang684c9cd2017-10-17 16:26:45 -070036#include <brillo/key_value_store.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040037#include <expat.h>
Alex Deymoa2591792015-11-17 00:39:40 -030038#include <metrics/metrics_library.h>
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080039#include <policy/libpolicy.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000040
Alex Deymo39910dc2015-11-09 17:04:30 -080041#include "update_engine/common/action_pipe.h"
42#include "update_engine/common/constants.h"
43#include "update_engine/common/hardware_interface.h"
44#include "update_engine/common/hash_calculator.h"
45#include "update_engine/common/platform_constants.h"
46#include "update_engine/common/prefs_interface.h"
47#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070048#include "update_engine/connection_manager_interface.h"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070049#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080050#include "update_engine/metrics_utils.h"
Amin Hassani7fca2862019-03-28 16:09:22 -070051#include "update_engine/omaha_request_builder_xml.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070052#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070053#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080054#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000055
Darin Petkov1cbd78f2010-07-29 12:38:34 -070056using base::Time;
57using base::TimeDelta;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080058using chromeos_update_manager::kRollforwardInfinity;
David Zeuthene8ed8632014-07-24 13:38:10 -040059using std::map;
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070060using std::numeric_limits;
rspangler@google.com49fdf182009-10-10 00:57:34 +000061using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040062using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000063
64namespace chromeos_update_engine {
65
Amin Hassani6600a562018-09-24 15:17:19 -070066// List of custom attributes that we interpret in the Omaha response:
67constexpr char kAttrDeadline[] = "deadline";
68constexpr char kAttrDisableP2PForDownloading[] = "DisableP2PForDownloading";
69constexpr char kAttrDisableP2PForSharing[] = "DisableP2PForSharing";
70constexpr char kAttrDisablePayloadBackoff[] = "DisablePayloadBackoff";
71constexpr char kAttrVersion[] = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080072// Deprecated: "IsDelta"
Amin Hassani6600a562018-09-24 15:17:19 -070073constexpr char kAttrIsDeltaPayload[] = "IsDeltaPayload";
74constexpr char kAttrMaxFailureCountPerUrl[] = "MaxFailureCountPerUrl";
75constexpr char kAttrMaxDaysToScatter[] = "MaxDaysToScatter";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080076// Deprecated: "ManifestSignatureRsa"
77// Deprecated: "ManifestSize"
Amin Hassani6600a562018-09-24 15:17:19 -070078constexpr char kAttrMetadataSignatureRsa[] = "MetadataSignatureRsa";
79constexpr char kAttrMetadataSize[] = "MetadataSize";
80constexpr char kAttrMoreInfo[] = "MoreInfo";
81constexpr char kAttrNoUpdate[] = "noupdate";
Don Garrett42bd3aa2013-04-10 18:14:56 -070082// Deprecated: "NeedsAdmin"
Amin Hassani6600a562018-09-24 15:17:19 -070083constexpr char kAttrPollInterval[] = "PollInterval";
84constexpr char kAttrPowerwash[] = "Powerwash";
85constexpr char kAttrPrompt[] = "Prompt";
86constexpr char kAttrPublicKeyRsa[] = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080087
Amin Hassani6600a562018-09-24 15:17:19 -070088// List of attributes that we interpret in the Omaha response:
89constexpr char kAttrAppId[] = "appid";
90constexpr char kAttrCodeBase[] = "codebase";
91constexpr char kAttrCohort[] = "cohort";
92constexpr char kAttrCohortHint[] = "cohorthint";
93constexpr char kAttrCohortName[] = "cohortname";
94constexpr char kAttrElapsedDays[] = "elapsed_days";
95constexpr char kAttrElapsedSeconds[] = "elapsed_seconds";
96constexpr char kAttrEvent[] = "event";
97constexpr char kAttrHashSha256[] = "hash_sha256";
98// Deprecated: "hash"; Although we still need to pass it from the server for
99// backward compatibility.
100constexpr char kAttrName[] = "name";
101// Deprecated: "sha256"; Although we still need to pass it from the server for
102// backward compatibility.
103constexpr char kAttrSize[] = "size";
104constexpr char kAttrStatus[] = "status";
105
106// List of values that we interpret in the Omaha response:
107constexpr char kValPostInstall[] = "postinstall";
108constexpr char kValNoUpdate[] = "noupdate";
109
Alex Deymob3fa53b2016-04-18 19:57:58 -0700110// updatecheck attributes (without the underscore prefix).
Amin Hassani6600a562018-09-24 15:17:19 -0700111constexpr char kAttrEol[] = "eol";
112constexpr char kAttrRollback[] = "rollback";
113constexpr char kAttrFirmwareVersion[] = "firmware_version";
114constexpr char kAttrKernelVersion[] = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -0700115
David Zeuthene8ed8632014-07-24 13:38:10 -0400116// Struct used for holding data obtained when parsing the XML.
117struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400118 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
119
120 // Pointer to the expat XML_Parser object.
121 XML_Parser xml_parser;
122
David Zeuthene8ed8632014-07-24 13:38:10 -0400123 // This is the state of the parser as it's processing the XML.
124 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400125 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400126 string current_path;
127
128 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400129 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700130 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400131 string daystart_elapsed_days;
132 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800133
Sen Jiang81259682017-03-30 15:11:30 -0700134 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700135 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700136 vector<string> url_codebase;
137 string manifest_version;
138 map<string, string> action_postinstall_attrs;
139 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700140 string cohort;
141 string cohorthint;
142 string cohortname;
143 bool cohort_set = false;
144 bool cohorthint_set = false;
145 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700146
147 struct Package {
148 string name;
149 string size;
150 string hash;
151 };
152 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800153 };
Sen Jiang81259682017-03-30 15:11:30 -0700154 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400155};
156
157namespace {
158
159// Callback function invoked by expat.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800160void ParserHandlerStart(void* user_data,
161 const XML_Char* element,
David Zeuthene8ed8632014-07-24 13:38:10 -0400162 const XML_Char** attr) {
163 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
164
165 if (data->failed)
166 return;
167
168 data->current_path += string("/") + element;
169
170 map<string, string> attrs;
171 if (attr != nullptr) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800172 for (int n = 0; attr[n] != nullptr && attr[n + 1] != nullptr; n += 2) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400173 string key = attr[n];
174 string value = attr[n + 1];
175 attrs[key] = value;
176 }
177 }
178
Alex Deymo8e18f932015-03-27 16:16:59 -0700179 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700180 OmahaParserData::App app;
Amin Hassani6600a562018-09-24 15:17:19 -0700181 if (attrs.find(kAttrAppId) != attrs.end()) {
182 app.id = attrs[kAttrAppId];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700183 }
Amin Hassani6600a562018-09-24 15:17:19 -0700184 if (attrs.find(kAttrCohort) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700185 app.cohort_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700186 app.cohort = attrs[kAttrCohort];
Alex Deymo8e18f932015-03-27 16:16:59 -0700187 }
Amin Hassani6600a562018-09-24 15:17:19 -0700188 if (attrs.find(kAttrCohortHint) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700189 app.cohorthint_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700190 app.cohorthint = attrs[kAttrCohortHint];
Alex Deymo8e18f932015-03-27 16:16:59 -0700191 }
Amin Hassani6600a562018-09-24 15:17:19 -0700192 if (attrs.find(kAttrCohortName) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700193 app.cohortname_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700194 app.cohortname = attrs[kAttrCohortName];
Alex Deymo8e18f932015-03-27 16:16:59 -0700195 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700196 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700197 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700198 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700199 data->apps.back().updatecheck_status = attrs[kAttrStatus];
Sen Jiang81259682017-03-30 15:11:30 -0700200 if (data->updatecheck_poll_interval.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700201 data->updatecheck_poll_interval = attrs[kAttrPollInterval];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700202 // Omaha sends arbitrary key-value pairs as extra attributes starting with
203 // an underscore.
204 for (const auto& attr : attrs) {
205 if (!attr.first.empty() && attr.first[0] == '_')
206 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
207 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400208 } else if (data->current_path == "/response/daystart") {
209 // Get the install-date.
Amin Hassani6600a562018-09-24 15:17:19 -0700210 data->daystart_elapsed_days = attrs[kAttrElapsedDays];
211 data->daystart_elapsed_seconds = attrs[kAttrElapsedSeconds];
David Zeuthene8ed8632014-07-24 13:38:10 -0400212 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
213 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700214 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700215 data->apps.back().url_codebase.push_back(attrs[kAttrCodeBase]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800216 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400217 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800218 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700219 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700220 data->apps.back().packages.push_back({.name = attrs[kAttrName],
221 .size = attrs[kAttrSize],
222 .hash = attrs[kAttrHashSha256]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400223 } else if (data->current_path == "/response/app/updatecheck/manifest") {
224 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700225 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700226 data->apps.back().manifest_version = attrs[kAttrVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400227 } else if (data->current_path ==
228 "/response/app/updatecheck/manifest/actions/action") {
229 // We only care about the postinstall action.
Amin Hassani6600a562018-09-24 15:17:19 -0700230 if (attrs[kAttrEvent] == kValPostInstall && !data->apps.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700231 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400232 }
233 }
234}
235
236// Callback function invoked by expat.
237void ParserHandlerEnd(void* user_data, const XML_Char* element) {
238 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
239 if (data->failed)
240 return;
241
242 const string path_suffix = string("/") + element;
243
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800244 if (!base::EndsWith(
245 data->current_path, path_suffix, base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400246 LOG(ERROR) << "Unexpected end element '" << element
247 << "' with current_path='" << data->current_path << "'";
248 data->failed = true;
249 return;
250 }
251 data->current_path.resize(data->current_path.size() - path_suffix.size());
252}
253
David Zeuthenf3e28012014-08-26 18:23:52 -0400254// Callback function invoked by expat.
255//
256// This is called for entity declarations. Since Omaha is guaranteed
257// to never return any XML with entities our course of action is to
258// just stop parsing. This avoids potential resource exhaustion
259// problems AKA the "billion laughs". CVE-2013-0340.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800260void ParserHandlerEntityDecl(void* user_data,
261 const XML_Char* entity_name,
David Zeuthenf3e28012014-08-26 18:23:52 -0400262 int is_parameter_entity,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800263 const XML_Char* value,
David Zeuthenf3e28012014-08-26 18:23:52 -0400264 int value_length,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800265 const XML_Char* base,
266 const XML_Char* system_id,
267 const XML_Char* public_id,
268 const XML_Char* notation_name) {
David Zeuthenf3e28012014-08-26 18:23:52 -0400269 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
270
271 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
272 data->failed = true;
273 data->entity_decl = true;
274 XML_StopParser(data->xml_parser, false);
275}
276
David Zeuthene8ed8632014-07-24 13:38:10 -0400277} // namespace
278
Alex Deymoc1c17b42015-11-23 03:53:15 -0300279OmahaRequestAction::OmahaRequestAction(
280 SystemState* system_state,
281 OmahaEvent* event,
282 std::unique_ptr<HttpFetcher> http_fetcher,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700283 bool ping_only,
284 const string& session_id)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800285 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800286 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700287 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300288 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800289 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700290 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700291 ping_active_days_(0),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700292 ping_roll_call_days_(0),
293 session_id_(session_id) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800294 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700295}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000296
Darin Petkov6a5b3222010-07-13 14:55:28 -0700297OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000298
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700299// Calculates the value to use for the ping days parameter.
300int OmahaRequestAction::CalculatePingDays(const string& key) {
301 int days = kNeverPinged;
302 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800303 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700304 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
305 if (days < 0) {
306 // If |days| is negative, then the system clock must have jumped
307 // back in time since the ping was sent. Mark the value so that
308 // it doesn't get sent to the server but we still update the
309 // last ping daystart preference. This way the next ping time
310 // will be correct, hopefully.
311 days = kPingTimeJump;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800312 LOG(WARNING)
313 << "System clock jumped back in time. Resetting ping daystarts.";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700314 }
315 }
316 return days;
317}
318
319void OmahaRequestAction::InitPingDays() {
320 // We send pings only along with update checks, not with events.
321 if (IsEvent()) {
322 return;
323 }
324 // TODO(petkov): Figure a way to distinguish active use pings
325 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700326 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700327 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
328 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
329}
330
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700331bool OmahaRequestAction::ShouldPing() const {
Amin Hassani7fca2862019-03-28 16:09:22 -0700332 if (ping_active_days_ == kNeverPinged &&
333 ping_roll_call_days_ == kNeverPinged) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700334 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
335 if (powerwash_count > 0) {
336 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
337 << "powerwash_count is " << powerwash_count;
338 return false;
339 }
Amin Hassani1677e812017-06-21 13:36:36 -0700340 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
341 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
342 << "the first_active_omaha_ping_sent is true";
343 return false;
344 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700345 return true;
346 }
347 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
348}
349
David Zeuthen639aa362014-02-03 16:23:44 -0800350// static
351int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
352 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700353 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800354 return -1;
355
356 // If we have the value stored on disk, just return it.
357 int64_t stored_value;
358 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
359 // Convert and sanity-check.
360 int install_date_days = static_cast<int>(stored_value);
361 if (install_date_days >= 0)
362 return install_date_days;
363 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
364 << install_date_days << " looks suspicious.";
365 prefs->Delete(kPrefsInstallDateDays);
366 }
367
368 // Otherwise, if OOBE is not complete then do nothing and wait for
369 // ParseResponse() to call ParseInstallDate() and then
370 // PersistInstallDate() to set the kPrefsInstallDateDays state
371 // variable. Once that is done, we'll then report back in future
372 // Omaha requests. This works exactly because OOBE triggers an
373 // update check.
374 //
375 // However, if OOBE is complete and the kPrefsInstallDateDays state
376 // variable is not set, there are two possibilities
377 //
378 // 1. The update check in OOBE failed so we never got a response
379 // from Omaha (no network etc.); or
380 //
381 // 2. OOBE was done on an older version that didn't write to the
382 // kPrefsInstallDateDays state variable.
383 //
384 // In both cases, we approximate the install date by simply
385 // inspecting the timestamp of when OOBE happened.
386
387 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700388 if (!system_state->hardware()->IsOOBEEnabled() ||
389 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800390 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700391 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800392 return -1;
393 }
394
395 int num_days;
396 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
397 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
398 << "as its value '" << utils::ToString(time_of_oobe)
399 << "' looks suspicious.";
400 return -1;
401 }
402
403 // Persist this to disk, for future use.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800404 if (!OmahaRequestAction::PersistInstallDate(
405 system_state, num_days, kProvisionedFromOOBEMarker))
David Zeuthen639aa362014-02-03 16:23:44 -0800406 return -1;
407
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800408 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to " << num_days
409 << " days";
David Zeuthen639aa362014-02-03 16:23:44 -0800410
411 return num_days;
412}
413
Darin Petkov6a5b3222010-07-13 14:55:28 -0700414void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000415 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700416 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700417 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700418 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700419 return;
420 }
David Zeuthen639aa362014-02-03 16:23:44 -0800421
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700422 OmahaRequestBuilderXml omaha_request(event_.get(),
423 params_,
424 ping_only_,
425 ShouldPing(), // include_ping
426 ping_active_days_,
427 ping_roll_call_days_,
428 GetInstallDate(system_state_),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700429 system_state_->prefs(),
430 session_id_);
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700431 string request_post = omaha_request.GetRequest();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700432
Sen Jiang42fa45e2018-03-12 11:02:14 -0700433 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700434 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
435 params_->interactive() ? "fg" : "bg");
436 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
437 http_fetcher_->SetHeader(
438 kXGoogleUpdateUpdater,
439 base::StringPrintf(
440 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
441
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800442 http_fetcher_->SetPostData(
443 request_post.data(), request_post.size(), kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700444 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700445 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700446 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000447}
448
Darin Petkov6a5b3222010-07-13 14:55:28 -0700449void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000450 http_fetcher_->TerminateTransfer();
451}
452
453// We just store the response in the buffer. Once we've received all bytes,
454// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700455bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800456 const void* bytes,
457 size_t length) {
458 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
459 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700460 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000461}
462
463namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000464
465// Parses a 64 bit base-10 int from a string and returns it. Returns 0
466// on error. If the string contains "0", that's indistinguishable from
467// error.
468off_t ParseInt(const string& str) {
469 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700470 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000471 if (rc < 1) {
472 // failure
473 return 0;
474 }
475 return ret;
476}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700477
David Zeuthene8ed8632014-07-24 13:38:10 -0400478// Parses |str| and returns |true| if, and only if, its value is "true".
479bool ParseBool(const string& str) {
480 return str == "true";
481}
482
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700483// Update the last ping day preferences based on the server daystart
484// response. Returns true on success, false otherwise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800485bool UpdateLastPingDays(OmahaParserData* parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700486 int64_t elapsed_seconds = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800487 TEST_AND_RETURN_FALSE(base::StringToInt64(
488 parser_data->daystart_elapsed_seconds, &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700489 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
490
491 // Remember the local time that matches the server's last midnight
492 // time.
493 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
494 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
495 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
496 return true;
497}
Sen Jiang81259682017-03-30 15:11:30 -0700498
499// Parses the package node in the given XML document and populates
500// |output_object| if valid. Returns true if we should continue the parsing.
501// False otherwise, in which case it sets any error code using |completer|.
502bool ParsePackage(OmahaParserData::App* app,
503 OmahaResponse* output_object,
504 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700505 if (app->updatecheck_status.empty() ||
506 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700507 if (!app->packages.empty()) {
508 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
509 completer->set_code(ErrorCode::kOmahaResponseInvalid);
510 return false;
511 }
512 return true;
513 }
514 if (app->packages.empty()) {
515 LOG(ERROR) << "Omaha Response has no packages";
516 completer->set_code(ErrorCode::kOmahaResponseInvalid);
517 return false;
518 }
519 if (app->url_codebase.empty()) {
520 LOG(ERROR) << "No Omaha Response URLs";
521 completer->set_code(ErrorCode::kOmahaResponseInvalid);
522 return false;
523 }
524 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
525 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700526 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700527 ":",
528 base::TRIM_WHITESPACE,
529 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700530 vector<string> metadata_signatures = base::SplitString(
531 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
532 ":",
533 base::TRIM_WHITESPACE,
534 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700535 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700536 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700537 ":",
538 base::TRIM_WHITESPACE,
539 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700540 for (size_t i = 0; i < app->packages.size(); i++) {
541 const auto& package = app->packages[i];
542 if (package.name.empty()) {
543 LOG(ERROR) << "Omaha Response has empty package name";
544 completer->set_code(ErrorCode::kOmahaResponseInvalid);
545 return false;
546 }
547 LOG(INFO) << "Found package " << package.name;
548
549 OmahaResponse::Package out_package;
550 for (const string& codebase : app->url_codebase) {
551 if (codebase.empty()) {
552 LOG(ERROR) << "Omaha Response URL has empty codebase";
553 completer->set_code(ErrorCode::kOmahaResponseInvalid);
554 return false;
555 }
556 out_package.payload_urls.push_back(codebase + package.name);
557 }
558 // Parse the payload size.
559 base::StringToUint64(package.size, &out_package.size);
560 if (out_package.size <= 0) {
561 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
562 completer->set_code(ErrorCode::kOmahaResponseInvalid);
563 return false;
564 }
565 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
566
567 if (i < metadata_sizes.size())
568 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
569 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
570 << " bytes";
571
572 if (i < metadata_signatures.size())
573 out_package.metadata_signature = metadata_signatures[i];
574 LOG(INFO) << "Payload metadata signature = "
575 << out_package.metadata_signature;
576
577 out_package.hash = package.hash;
578 if (out_package.hash.empty()) {
579 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
580 completer->set_code(ErrorCode::kOmahaResponseInvalid);
581 return false;
582 }
583 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700584
585 if (i < is_delta_payloads.size())
586 out_package.is_delta = ParseBool(is_delta_payloads[i]);
587 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
588
Sen Jiang81259682017-03-30 15:11:30 -0700589 output_object->packages.push_back(std::move(out_package));
590 }
591
592 return true;
593}
594
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700595// Parses the 2 key version strings kernel_version and firmware_version. If the
596// field is not present, or cannot be parsed the values default to 0xffff.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700597void ParseRollbackVersions(int allowed_milestones,
598 OmahaParserData* parser_data,
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700599 OmahaResponse* output_object) {
600 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700601 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700602 &output_object->rollback_key_version.firmware_key,
603 &output_object->rollback_key_version.firmware);
604 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700605 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700606 &output_object->rollback_key_version.kernel_key,
607 &output_object->rollback_key_version.kernel);
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700608
609 // Create the attribute name strings for milestone N - allowed_milestones.
610 const string firmware_max_rollforward_attr =
611 base::StringPrintf("%s_%i", kAttrFirmwareVersion, allowed_milestones);
612 const string kernel_max_rollforward_attr =
613 base::StringPrintf("%s_%i", kAttrKernelVersion, allowed_milestones);
614
615 const bool max_firmware_and_kernel_exist =
616 parser_data->updatecheck_attrs.count(firmware_max_rollforward_attr) > 0 &&
617 parser_data->updatecheck_attrs.count(kernel_max_rollforward_attr) > 0;
618
619 string firmware_version;
620 string kernel_version;
621 if (max_firmware_and_kernel_exist) {
622 firmware_version =
623 parser_data->updatecheck_attrs[firmware_max_rollforward_attr];
624 kernel_version =
625 parser_data->updatecheck_attrs[kernel_max_rollforward_attr];
626 }
627
628 LOG(INFO) << "For milestone N-" << allowed_milestones
629 << " firmware_key_version=" << firmware_version
630 << " kernel_key_version=" << kernel_version;
631
632 OmahaResponse::RollbackKeyVersion version;
633 utils::ParseRollbackKeyVersion(
634 firmware_version, &version.firmware_key, &version.firmware);
635 utils::ParseRollbackKeyVersion(
636 kernel_version, &version.kernel_key, &version.kernel);
637
638 output_object->past_rollback_key_version = std::move(version);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700639}
640
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700641} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000642
David Zeuthene8ed8632014-07-24 13:38:10 -0400643bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700644 OmahaResponse* output_object,
645 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700646 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700647 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700648 return false;
649 }
Sen Jiang81259682017-03-30 15:11:30 -0700650 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700651
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800652 // chromium-os:37289: The PollInterval is not supported by Omaha server
653 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700654 // slow down the request rate from the server-side. Note that the PollInterval
655 // is not persisted, so it has to be sent by the server on every response to
656 // guarantee that the scheduler uses this value (otherwise, if the device got
657 // rebooted after the last server-indicated value, it'll revert to the default
658 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
659 // based on the assumption that we perform an update check every hour so that
660 // the max value of 8 will roughly be equivalent to one work day. If we decide
661 // to use PollInterval permanently, we should update the
662 // max_update_checks_allowed to take PollInterval into account. Note: The
663 // parsing for PollInterval happens even before parsing of the status because
664 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400665 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700666 &output_object->poll_interval);
667
David Zeuthen639aa362014-02-03 16:23:44 -0800668 // Check for the "elapsed_days" attribute in the "daystart"
669 // element. This is the number of days since Jan 1 2007, 0:00
670 // PST. If we don't have a persisted value of the Omaha InstallDate,
671 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400672 if (ParseInstallDate(parser_data, output_object) &&
673 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800674 // Since output_object->install_date_days is never negative, the
675 // elapsed_days -> install-date calculation is reduced to simply
676 // rounding down to the nearest number divisible by 7.
677 int remainder = output_object->install_date_days % 7;
678 int install_date_days_rounded =
679 output_object->install_date_days - remainder;
680 if (PersistInstallDate(system_state_,
681 install_date_days_rounded,
682 kProvisionedFromOmahaResponse)) {
683 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
684 << install_date_days_rounded << " days";
685 }
686 }
687
Alex Deymo00d79ac2015-06-29 15:41:49 -0700688 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700689 for (const auto& app : parser_data->apps) {
690 if (app.id == params_->GetAppId()) {
691 if (app.cohort_set)
692 PersistCohortData(kPrefsOmahaCohort, app.cohort);
693 if (app.cohorthint_set)
694 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
695 if (app.cohortname_set)
696 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
697 break;
698 }
699 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700700
Alex Deymob3fa53b2016-04-18 19:57:58 -0700701 // Parse the updatecheck attributes.
702 PersistEolStatus(parser_data->updatecheck_attrs);
Marton Hunyady199152d2018-05-07 19:08:48 +0200703 // Rollback-related updatecheck attributes.
704 // Defaults to false if attribute is not present.
705 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -0700706 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700707
708 // Parses the rollback versions of the current image. If the fields do not
709 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700710 ParseRollbackVersions(
711 params_->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -0700712
David Zeuthene8ed8632014-07-24 13:38:10 -0400713 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700714 return false;
715
David Zeuthene8ed8632014-07-24 13:38:10 -0400716 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700717 return false;
718
Sen Jiang0affc2c2017-02-10 15:55:05 -0800719 // Package has to be parsed after Params now because ParseParams need to make
720 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -0700721 for (auto& app : parser_data->apps)
722 if (!ParsePackage(&app, output_object, completer))
723 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800724
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700725 return true;
726}
727
David Zeuthene8ed8632014-07-24 13:38:10 -0400728bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700729 OmahaResponse* output_object,
730 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700731 output_object->update_exists = false;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700732 for (const auto& app : parser_data->apps) {
733 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -0700734 if (status == kValNoUpdate) {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700735 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -0700736 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700737 output_object->update_exists = false;
738 break;
Sen Jiang81259682017-03-30 15:11:30 -0700739 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700740 auto const& attr_no_update =
741 app.action_postinstall_attrs.find(kAttrNoUpdate);
742 if (attr_no_update != app.action_postinstall_attrs.end() &&
743 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700744 // noupdate="true" in postinstall attributes means it's an update to
745 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -0700746 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700747 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700748 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700749 output_object->update_exists = true;
750 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700751 } else if (status.empty() && params_->is_install() &&
752 params_->GetAppId() == app.id) {
753 // Skips the platform app for install operation.
754 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -0700755 } else {
756 LOG(ERROR) << "Unknown Omaha response status: " << status;
757 completer->set_code(ErrorCode::kOmahaResponseInvalid);
758 return false;
759 }
760 }
761 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700762 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700763 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700764 }
765
Sen Jiang81259682017-03-30 15:11:30 -0700766 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700767}
768
David Zeuthene8ed8632014-07-24 13:38:10 -0400769bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700770 OmahaResponse* output_object,
771 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700772 map<string, string> attrs;
773 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700774 if (app.id == params_->GetAppId()) {
775 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -0700776 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700777 } else if (!params_->system_app_id().empty() &&
778 app.id == params_->system_app_id()) {
779 // this is the system app (this check is intentionally skipped if there is
780 // no system_app_id set)
781 output_object->system_version = app.manifest_version;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700782 } else if (params_->is_install() &&
783 app.manifest_version != params_->app_version()) {
784 LOG(WARNING) << "An app has a different version (" << app.manifest_version
785 << ") that is different than platform app version ("
786 << params_->app_version() << ")";
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700787 }
788 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700789 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700790 }
Sen Jiang81259682017-03-30 15:11:30 -0700791 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700792 if (params_->is_install()) {
793 LOG(INFO) << "Use request version for Install operation.";
794 output_object->version = params_->app_version();
795 }
Chris Sosa3b748432013-06-20 16:42:59 -0700796 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700797 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700798 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700799 return false;
800 }
801
802 LOG(INFO) << "Received omaha response to update to version "
803 << output_object->version;
804
David Zeuthene8ed8632014-07-24 13:38:10 -0400805 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700806 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700807 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700808 return false;
809 }
810
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800811 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -0700812 output_object->more_info_url = attrs[kAttrMoreInfo];
813 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
814 output_object->deadline = attrs[kAttrDeadline];
815 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700816 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -0700817 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700818 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -0700819 ParseBool(attrs[kAttrDisableP2PForSharing]);
820 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800821
Amin Hassani6600a562018-09-24 15:17:19 -0700822 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800823 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800824 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700825
Jay Srinivasan08262882012-12-28 19:29:43 -0800826 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -0700827 ParseBool(attrs[kAttrDisablePayloadBackoff]);
828 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800829
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700830 return true;
831}
832
David Zeuthene8ed8632014-07-24 13:38:10 -0400833// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000834// and fill in the appropriate fields of the output object. Also, notifies
835// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800836void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -0700837 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000838 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800839 string current_response(response_buffer_.begin(), response_buffer_.end());
840 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700841
Gilad Arnold74b5f552014-10-07 08:17:16 -0700842 PayloadStateInterface* const payload_state = system_state_->payload_state();
843
Zentaro Kavanagh76af2662018-05-15 10:54:53 -0700844 // Set the max kernel key version based on whether rollback is allowed.
845 SetMaxKernelKeyVersionForRollback();
846
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700847 // Events are best effort transactions -- assume they always succeed.
848 if (IsEvent()) {
849 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700850 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700851 return;
852 }
853
Amin Hassanid3d84212019-08-17 00:27:44 -0700854 ErrorCode aux_error_code = fetcher->GetAuxiliaryErrorCode();
855 if (aux_error_code != ErrorCode::kSuccess) {
856 metrics::DownloadErrorCode download_error_code =
857 metrics_utils::GetDownloadErrorCode(aux_error_code);
858 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
859 system_state_,
860 metrics::CheckResult::kUnset,
861 metrics::CheckReaction::kUnset,
862 download_error_code);
863 }
864
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700865 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700866 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700867 int code = GetHTTPResponseCode();
868 // Makes sure we send sane error values.
869 if (code < 0 || code >= 1000) {
870 code = 999;
871 }
David Zeuthena99981f2013-04-29 13:42:47 -0700872 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700873 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000874 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700875 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000876
David Zeuthene8ed8632014-07-24 13:38:10 -0400877 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400878 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400879 XML_SetUserData(parser, &parser_data);
880 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400881 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800882 XML_Status res =
883 XML_Parse(parser,
884 reinterpret_cast<const char*>(response_buffer_.data()),
885 response_buffer_.size(),
886 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400887
888 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700889 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800890 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
891 << XML_GetCurrentLineNumber(parser) << " col "
892 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -0700893 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400894 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
895 if (response_buffer_.empty()) {
896 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
897 } else if (parser_data.entity_decl) {
898 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
899 }
900 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000901 return;
902 }
Amin Hassani91f48b42018-08-06 17:47:14 -0700903 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000904
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700905 // Update the last ping day preferences based on the server daystart response
906 // even if we didn't send a ping. Omaha always includes the daystart in the
907 // response, but log the error if it didn't.
908 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
909 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700910
Amin Hassani1677e812017-06-21 13:36:36 -0700911 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
912 // we have got a response from omaha and if its value has never been set to
913 // true before. Failure of this function should be ignored. There should be no
914 // need to check if a=-1 has been sent because older devices have already sent
915 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
916 // future checks.
917 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700918 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
919 system_state_->metrics_reporter()->ReportInternalErrorCode(
920 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
921 }
Amin Hassani1677e812017-06-21 13:36:36 -0700922 }
923
Thieu Le116fda32011-04-19 11:01:54 -0700924 if (!HasOutputPipe()) {
925 // Just set success to whether or not the http transfer succeeded,
926 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700927 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700928 return;
929 }
930
Darin Petkov6a5b3222010-07-13 14:55:28 -0700931 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400932 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000933 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700934 output_object.update_exists = true;
935 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000936
Toni Barzic61544e62018-10-11 14:37:30 -0700937 LoadOrPersistUpdateFirstSeenAtPref();
938
Weidong Guo421ff332017-04-17 10:08:38 -0700939 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -0700940 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -0700941 // No need to change output_object.update_exists here, since the value
942 // has been output to the pipe.
943 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700944 return;
945 }
946
David Zeuthen8f191b22013-08-06 12:27:50 -0700947 // If Omaha says to disable p2p, respect that
948 if (output_object.disable_p2p_for_downloading) {
949 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
950 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700951 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700952 }
953 if (output_object.disable_p2p_for_sharing) {
954 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
955 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700956 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700957 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800958
959 // Update the payload state with the current response. The payload state
960 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800961 // from what's stored already. We are updating the payload state as late
962 // as possible in this method so that if a new release gets pushed and then
963 // got pulled back due to some issues, we don't want to clear our internal
964 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800965 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800966
David Zeuthen8f191b22013-08-06 12:27:50 -0700967 // It could be we've already exceeded the deadline for when p2p is
968 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700969 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700970 payload_state->P2PNewAttempt();
971 if (!payload_state->P2PAttemptAllowed()) {
972 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
973 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700974 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700975 }
976 }
977
978 // From here on, we'll complete stuff in CompleteProcessing() so
979 // disable |completer| since we'll create a new one in that
980 // function.
981 completer.set_should_complete(false);
982
983 // If we're allowed to use p2p for downloading we do not pay
984 // attention to wall-clock-based waiting if the URL is indeed
985 // available via p2p. Therefore, check if the file is available via
986 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -0700987 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700988 LookupPayloadViaP2P(output_object);
989 } else {
990 CompleteProcessing();
991 }
992}
993
994void OmahaRequestAction::CompleteProcessing() {
995 ScopedActionCompleter completer(processor_, this);
996 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
997 PayloadStateInterface* payload_state = system_state_->payload_state();
998
999 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001000 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001001 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001002 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001003 return;
1004 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001005
Chris Sosa20f005c2013-09-05 13:53:08 -07001006 if (payload_state->ShouldBackoffDownload()) {
1007 output_object.update_exists = false;
1008 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1009 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001010 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001011 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001012 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001013 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001014}
1015
1016void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1017 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1018 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001019 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001020 } else {
1021 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1022 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001023 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001024 }
1025 CompleteProcessing();
1026}
1027
1028void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001029 // If the device is in the middle of an update, the state variables
1030 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1031 // tracks the offset and length of the operation currently in
1032 // progress. The offset is based from the end of the manifest which
1033 // is kPrefsManifestMetadataSize bytes long.
1034 //
1035 // To make forward progress and avoid deadlocks, we need to find a
1036 // peer that has at least the entire operation we're currently
1037 // working on. Otherwise we may end up in a situation where two
1038 // devices bounce back and forth downloading from each other,
1039 // neither making any forward progress until one of them decides to
1040 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1041 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001042 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001043 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001044 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001045 int64_t next_data_offset = 0;
1046 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001047 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001048 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1049 &manifest_metadata_size) &&
1050 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001051 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1052 &manifest_signature_size) &&
1053 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001054 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001055 &next_data_offset) &&
1056 next_data_offset != -1 &&
1057 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1058 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001059 minimum_size = manifest_metadata_size + manifest_signature_size +
1060 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001061 }
1062
Sen Jiang0affc2c2017-02-10 15:55:05 -08001063 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001064 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001065 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001066 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001067 string file_id =
1068 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001069 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001070 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1071 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001072 system_state_->p2p_manager()->LookupUrlForFile(
1073 file_id,
1074 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001075 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001076 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1077 base::Unretained(this)));
1078 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001079}
1080
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001081bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001082 if (params_->interactive()) {
1083 LOG(INFO) << "Not deferring download because update is interactive.";
1084 return false;
1085 }
1086
David Zeuthen8f191b22013-08-06 12:27:50 -07001087 // If we're using p2p to download _and_ we have a p2p URL, we never
1088 // defer the download. This is because the download will always
1089 // happen from a peer on the LAN and we've been waiting in line for
1090 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001091 const PayloadStateInterface* payload_state = system_state_->payload_state();
1092 if (payload_state->GetUsingP2PForDownloading() &&
1093 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001094 LOG(INFO) << "Download not deferred because download "
1095 << "will happen from a local peer (via p2p).";
1096 return false;
1097 }
1098
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001099 // We should defer the downloads only if we've first satisfied the
1100 // wall-clock-based-waiting period and then the update-check-based waiting
1101 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001102 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001103 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1104 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001105 return false;
1106 }
1107
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001108 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001109 case kWallClockWaitNotSatisfied:
1110 // We haven't even satisfied the first condition, passing the
1111 // wall-clock-based waiting period, so we should defer the downloads
1112 // until that happens.
1113 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1114 return true;
1115
1116 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1117 LOG(INFO) << "wall-clock-based-wait satisfied and "
1118 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001119 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001120
1121 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1122 // Wall-clock-based waiting period is satisfied, and it's determined
1123 // that we do not need the update-check-based wait. so no need to
1124 // defer downloads.
1125 LOG(INFO) << "wall-clock-based-wait satisfied and "
1126 << "update-check-based-wait is not required.";
1127 return false;
1128
1129 default:
1130 // Returning false for this default case so we err on the
1131 // side of downloading updates than deferring in case of any bugs.
1132 NOTREACHED();
1133 return false;
1134 }
1135}
1136
1137OmahaRequestAction::WallClockWaitResult
1138OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001139 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001140 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1141 if (update_first_seen_at == base::Time()) {
1142 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
1143 "persisted";
1144 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001145 }
1146
Sen Jiang7c1171e2016-06-23 11:35:40 -07001147 TimeDelta elapsed_time =
1148 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1149 TimeDelta max_scatter_period =
1150 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001151 int64_t staging_wait_time_in_days = 0;
1152 // Use staging and its default max value if staging is on.
1153 if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1154 &staging_wait_time_in_days) &&
1155 staging_wait_time_in_days > 0)
1156 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001157
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001158 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001159 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001160 << ", Time Elapsed = "
1161 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001162 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001163
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001164 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001165 // The deadline is set for all rules which serve a delta update from a
1166 // previous FSI, which means this update will be applied mostly in OOBE
1167 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1168 // quickly.
1169 LOG(INFO) << "Not scattering as deadline flag is set";
1170 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1171 }
1172
1173 if (max_scatter_period.InDays() == 0) {
1174 // This means the Omaha rule creator decides that this rule
1175 // should not be scattered irrespective of the policy.
1176 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1177 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1178 }
1179
1180 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001181 // This means we've waited more than the upperbound wait in the rule
1182 // from the time we first saw a valid update available to us.
1183 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001184 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1185 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1186 }
1187
1188 // This means we are required to participate in scattering.
1189 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001190 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001191 if (remaining_wait_time.InSeconds() <= 0) {
1192 // Yes, it's our turn now.
1193 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1194
1195 // But we can't download until the update-check-count-based wait is also
1196 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001197 return params_->update_check_count_wait_enabled()
1198 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1199 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001200 }
1201
1202 // Not our turn yet, so we have to wait until our turn to
1203 // help scatter the downloads across all clients of the enterprise.
1204 LOG(INFO) << "Update deferred for another "
1205 << utils::FormatSecs(remaining_wait_time.InSeconds())
1206 << " per policy.";
1207 return kWallClockWaitNotSatisfied;
1208}
1209
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001210bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001211 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001212
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001213 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1214 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1215 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001216 // We are unable to read the update check count from file for some reason.
1217 // So let's proceed anyway so as to not stall the update.
1218 LOG(ERROR) << "Unable to read update check count. "
1219 << "Skipping update-check-count-based-wait.";
1220 return true;
1221 }
1222 } else {
1223 // This file does not exist. This means we haven't started our update
1224 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001225 update_check_count_value =
1226 base::RandInt(params_->min_update_checks_needed(),
1227 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001228
1229 LOG(INFO) << "Randomly picked update check count value = "
1230 << update_check_count_value;
1231
1232 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001233 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1234 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001235 // We weren't able to write the update check count file for some reason.
1236 // So let's proceed anyway so as to not stall the update.
1237 LOG(ERROR) << "Unable to write update check count. "
1238 << "Skipping update-check-count-based-wait.";
1239 return true;
1240 }
1241 }
1242
1243 if (update_check_count_value == 0) {
1244 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1245 return true;
1246 }
1247
1248 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001249 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001250 // We err on the side of skipping scattering logic instead of stalling
1251 // a machine from receiving any updates in case of any unexpected state.
1252 LOG(ERROR) << "Invalid value for update check count detected. "
1253 << "Skipping update-check-count-based-wait.";
1254 return true;
1255 }
1256
1257 // Legal value, we need to wait for more update checks to happen
1258 // until this becomes 0.
1259 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001260 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001261 return false;
1262}
1263
David Zeuthen639aa362014-02-03 16:23:44 -08001264// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001265bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001266 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001267 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001268 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001269 return false;
1270
1271 if (elapsed_days < 0)
1272 return false;
1273
1274 output_object->install_date_days = elapsed_days;
1275 return true;
1276}
1277
1278// static
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001279bool OmahaRequestAction::HasInstallDate(SystemState* system_state) {
David Zeuthen639aa362014-02-03 16:23:44 -08001280 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001281 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001282 return false;
1283
1284 return prefs->Exists(kPrefsInstallDateDays);
1285}
1286
1287// static
1288bool OmahaRequestAction::PersistInstallDate(
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001289 SystemState* system_state,
David Zeuthen639aa362014-02-03 16:23:44 -08001290 int install_date_days,
1291 InstallDateProvisioningSource source) {
1292 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1293
1294 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001295 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001296 return false;
1297
1298 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1299 return false;
1300
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001301 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001302 static_cast<int>(source), // Sample.
1303 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001304 return true;
1305}
1306
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001307bool OmahaRequestAction::PersistCohortData(const string& prefs_key,
1308 const string& new_value) {
Alex Deymo8e18f932015-03-27 16:16:59 -07001309 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1310 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1311 return system_state_->prefs()->Delete(prefs_key);
1312 } else if (!new_value.empty()) {
1313 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1314 return system_state_->prefs()->SetString(prefs_key, new_value);
1315 }
1316 return true;
1317}
1318
Alex Deymob3fa53b2016-04-18 19:57:58 -07001319bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
Amin Hassani6600a562018-09-24 15:17:19 -07001320 auto eol_attr = attrs.find(kAttrEol);
Jae Hoon Kima1f4a7d2019-09-03 18:12:33 +00001321 if (eol_attr != attrs.end()) {
1322 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1323 eol_attr->second);
1324 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1325 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
Alex Deymob3fa53b2016-04-18 19:57:58 -07001326 }
Jae Hoon Kima1f4a7d2019-09-03 18:12:33 +00001327 return true;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001328}
1329
David Zeuthen33bae492014-02-25 16:16:18 -08001330void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1331 // We only want to report this on "update check".
1332 if (ping_only_ || event_ != nullptr)
1333 return;
1334
1335 metrics::CheckResult result = metrics::CheckResult::kUnset;
1336 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1337 metrics::DownloadErrorCode download_error_code =
1338 metrics::DownloadErrorCode::kUnset;
1339
1340 // Regular update attempt.
1341 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001342 case ErrorCode::kSuccess:
1343 // OK, we parsed the response successfully but that does
1344 // necessarily mean that an update is available.
1345 if (HasOutputPipe()) {
1346 const OmahaResponse& response = GetOutputObject();
1347 if (response.update_exists) {
1348 result = metrics::CheckResult::kUpdateAvailable;
1349 reaction = metrics::CheckReaction::kUpdating;
1350 } else {
1351 result = metrics::CheckResult::kNoUpdateAvailable;
1352 }
David Zeuthen33bae492014-02-25 16:16:18 -08001353 } else {
1354 result = metrics::CheckResult::kNoUpdateAvailable;
1355 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001356 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001357
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001358 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1359 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1360 result = metrics::CheckResult::kUpdateAvailable;
1361 reaction = metrics::CheckReaction::kIgnored;
1362 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001363
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001364 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1365 result = metrics::CheckResult::kUpdateAvailable;
1366 reaction = metrics::CheckReaction::kDeferring;
1367 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001368
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001369 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1370 result = metrics::CheckResult::kUpdateAvailable;
1371 reaction = metrics::CheckReaction::kBackingOff;
1372 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001373
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001374 default:
1375 // We report two flavors of errors, "Download errors" and "Parsing
1376 // error". Try to convert to the former and if that doesn't work
1377 // we know it's the latter.
1378 metrics::DownloadErrorCode tmp_error =
1379 metrics_utils::GetDownloadErrorCode(code);
1380 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1381 result = metrics::CheckResult::kDownloadError;
1382 download_error_code = tmp_error;
1383 } else {
1384 result = metrics::CheckResult::kParsingError;
1385 }
1386 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001387 }
1388
Amin Hassanid3d84212019-08-17 00:27:44 -07001389 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1390 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001391}
1392
Toni Barzic61544e62018-10-11 14:37:30 -07001393bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1394 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001395 // Note: policy decision to not update to a version we rolled back from.
1396 string rollback_version =
1397 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001398 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001399 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001400 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001401 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001402 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001403 return true;
1404 }
1405 }
1406
Toni Barzic61544e62018-10-11 14:37:30 -07001407 if (system_state_->hardware()->IsOOBEEnabled() &&
1408 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
1409 (response.deadline.empty() ||
1410 system_state_->payload_state()->GetRollbackHappened()) &&
1411 params_->app_version() != "ForcedUpdate") {
1412 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1413 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1414 return true;
1415 }
1416
Weidong Guo421ff332017-04-17 10:08:38 -07001417 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001418 LOG(INFO) << "Update is not allowed over current connection.";
1419 return true;
1420 }
1421
1422 // Note: We could technically delete the UpdateFirstSeenAt state when we
1423 // return true. If we do, it'll mean a device has to restart the
1424 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1425 // turned on again. On the other hand, it also increases the chance of update
1426 // starvation if an admin turns AU on/off more frequently. We choose to err on
1427 // the side of preventing starvation at the cost of not applying scattering in
1428 // those cases.
1429 return false;
1430}
1431
Weidong Guo421ff332017-04-17 10:08:38 -07001432bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1433 const OmahaResponse& response) const {
1434 PrefsInterface* prefs = system_state_->prefs();
1435
1436 if (!prefs) {
1437 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1438 "not available.";
1439 return false;
1440 }
1441
1442 bool is_allowed;
1443
1444 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1445 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1446 is_allowed) {
1447 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1448 "set to true.";
1449 return true;
1450 }
1451
1452 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1453 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1454 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1455 "set to false or does not exist while target does not exist.";
1456 return false;
1457 }
1458
1459 std::string target_version;
1460 int64_t target_size;
1461
1462 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1463 &target_version) ||
1464 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1465 LOG(INFO) << "Disabling updates over cellular as the target version or "
1466 "size is not accessible.";
1467 return false;
1468 }
1469
1470 uint64_t total_packages_size = 0;
1471 for (const auto& package : response.packages) {
1472 total_packages_size += package.size;
1473 }
1474 if (target_version == response.version &&
1475 static_cast<uint64_t>(target_size) == total_packages_size) {
1476 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1477 "omaha response.";
1478 return true;
1479 } else {
1480 LOG(INFO) << "Disabling updates over cellular as the target does not"
1481 "match the omaha response.";
1482 return false;
1483 }
1484}
1485
1486bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1487 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001488 ConnectionType type;
1489 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001490 ConnectionManagerInterface* connection_manager =
1491 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001492 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001493 LOG(INFO) << "We could not determine our connection type. "
1494 << "Defaulting to allow updates.";
1495 return true;
1496 }
Weidong Guo421ff332017-04-17 10:08:38 -07001497
Chris Sosa77f79e82014-06-02 18:16:24 -07001498 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001499 bool is_device_policy_set =
1500 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1501 // Treats tethered connection as if it is cellular connection.
1502 bool is_over_cellular = type == ConnectionType::kCellular ||
1503 tethering == ConnectionTethering::kConfirmed;
1504
1505 if (!is_over_cellular) {
1506 // There's no need to further check user preferences as we are not over
1507 // cellular connection.
1508 if (!is_allowed)
1509 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1510 } else if (is_device_policy_set) {
1511 // There's no need to further check user preferences as the device policy
1512 // is set regarding updates over cellular.
1513 if (!is_allowed)
1514 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1515 } else {
1516 // Deivce policy is not set, so user preferences overwrite whether to
1517 // allow updates over cellular.
1518 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1519 if (!is_allowed)
1520 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1521 }
1522
Chris Sosa77f79e82014-06-02 18:16:24 -07001523 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001524 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001525 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1526 return is_allowed;
1527}
1528
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001529bool OmahaRequestAction::IsRollbackEnabled() const {
1530 if (policy_provider_->IsConsumerDevice()) {
1531 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1532 return false;
1533 }
1534
1535 if (!policy_provider_->device_policy_is_loaded()) {
1536 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1537 return true;
1538 }
1539
1540 int allowed_milestones;
1541 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1542 &allowed_milestones)) {
1543 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1544 "Defaulting to rollback enabled.";
1545 return true;
1546 }
1547
1548 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1549 return allowed_milestones > 0;
1550}
1551
1552void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001553 int max_kernel_rollforward;
1554 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001555 if (IsRollbackEnabled()) {
1556 // If rollback is enabled, set the max kernel key version to the current
1557 // kernel key version. This has the effect of freezing kernel key roll
1558 // forwards.
1559 //
1560 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1561 // key roll forward happens until the server side components of rollback
1562 // are implemented. Future changes will allow the Omaha server to return
1563 // the kernel key version from max_rollback_versions in the past. At that
1564 // point the max kernel key version will be set to that value, creating a
1565 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001566 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001567 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001568 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001569 } else {
1570 // For devices that are not rollback enabled (ie. consumer devices), the
1571 // max kernel key version is set to 0xfffffffe, which is logically
1572 // infinity. This maintains the previous behavior that that kernel key
1573 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001574 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001575 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001576 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001577 }
1578
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001579 bool max_rollforward_set =
1580 system_state_->hardware()->SetMaxKernelKeyRollforward(
1581 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001582 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001583 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001584 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001585 // Report metrics
1586 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1587 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001588}
1589
May Lippert60aa3ca2018-08-15 16:55:29 -07001590base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1591 Time update_first_seen_at;
1592 int64_t update_first_seen_at_int;
1593 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1594 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1595 &update_first_seen_at_int)) {
1596 // Note: This timestamp could be that of ANY update we saw in the past
1597 // (not necessarily this particular update we're considering to apply)
1598 // but never got to apply because of some reason (e.g. stop AU policy,
1599 // updates being pulled out from Omaha, changes in target version prefix,
1600 // new update being rolled out, etc.). But for the purposes of scattering
1601 // it doesn't matter which update the timestamp corresponds to. i.e.
1602 // the clock starts ticking the first time we see an update and we're
1603 // ready to apply when the random wait period is satisfied relative to
1604 // that first seen timestamp.
1605 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1606 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1607 << utils::ToString(update_first_seen_at);
1608 } else {
1609 // This seems like an unexpected error where the persisted value exists
1610 // but it's not readable for some reason.
1611 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1612 return base::Time();
1613 }
1614 } else {
1615 update_first_seen_at = system_state_->clock()->GetWallclockTime();
1616 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
1617 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1618 update_first_seen_at_int)) {
1619 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1620 << utils::ToString(update_first_seen_at);
1621 } else {
1622 // This seems like an unexpected error where the value cannot be
1623 // persisted for some reason.
1624 LOG(INFO) << "UpdateFirstSeenAt value "
1625 << utils::ToString(update_first_seen_at)
1626 << " cannot be persisted";
1627 return base::Time();
1628 }
1629 }
1630 return update_first_seen_at;
1631}
1632
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001633} // namespace chromeos_update_engine