blob: 40e52f08bbda97f9ce6ce2fac8a53b674bf9ce8b [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
Sen Jiang42fa45e2018-03-12 11:02:14 -0700110// X-Goog-Update headers.
Amin Hassani6600a562018-09-24 15:17:19 -0700111constexpr char kXGoogleUpdateInteractivity[] = "X-Goog-Update-Interactivity";
112constexpr char kXGoogleUpdateAppId[] = "X-Goog-Update-AppId";
113constexpr char kXGoogleUpdateUpdater[] = "X-Goog-Update-Updater";
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700114constexpr char kXGoogleUpdateSessionId[] = "X-Goog-Update-SessionId";
Alex Deymo14ad88e2016-06-29 12:30:14 -0700115
Alex Deymob3fa53b2016-04-18 19:57:58 -0700116// updatecheck attributes (without the underscore prefix).
Amin Hassani6600a562018-09-24 15:17:19 -0700117constexpr char kAttrEol[] = "eol";
118constexpr char kAttrRollback[] = "rollback";
119constexpr char kAttrFirmwareVersion[] = "firmware_version";
120constexpr char kAttrKernelVersion[] = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -0700121
David Zeuthene8ed8632014-07-24 13:38:10 -0400122// Struct used for holding data obtained when parsing the XML.
123struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400124 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
125
126 // Pointer to the expat XML_Parser object.
127 XML_Parser xml_parser;
128
David Zeuthene8ed8632014-07-24 13:38:10 -0400129 // This is the state of the parser as it's processing the XML.
130 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400131 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400132 string current_path;
133
134 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400135 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700136 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400137 string daystart_elapsed_days;
138 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800139
Sen Jiang81259682017-03-30 15:11:30 -0700140 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700141 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700142 vector<string> url_codebase;
143 string manifest_version;
144 map<string, string> action_postinstall_attrs;
145 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700146 string cohort;
147 string cohorthint;
148 string cohortname;
149 bool cohort_set = false;
150 bool cohorthint_set = false;
151 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700152
153 struct Package {
154 string name;
155 string size;
156 string hash;
157 };
158 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800159 };
Sen Jiang81259682017-03-30 15:11:30 -0700160 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400161};
162
163namespace {
164
165// Callback function invoked by expat.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800166void ParserHandlerStart(void* user_data,
167 const XML_Char* element,
David Zeuthene8ed8632014-07-24 13:38:10 -0400168 const XML_Char** attr) {
169 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
170
171 if (data->failed)
172 return;
173
174 data->current_path += string("/") + element;
175
176 map<string, string> attrs;
177 if (attr != nullptr) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800178 for (int n = 0; attr[n] != nullptr && attr[n + 1] != nullptr; n += 2) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400179 string key = attr[n];
180 string value = attr[n + 1];
181 attrs[key] = value;
182 }
183 }
184
Alex Deymo8e18f932015-03-27 16:16:59 -0700185 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700186 OmahaParserData::App app;
Amin Hassani6600a562018-09-24 15:17:19 -0700187 if (attrs.find(kAttrAppId) != attrs.end()) {
188 app.id = attrs[kAttrAppId];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700189 }
Amin Hassani6600a562018-09-24 15:17:19 -0700190 if (attrs.find(kAttrCohort) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700191 app.cohort_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700192 app.cohort = attrs[kAttrCohort];
Alex Deymo8e18f932015-03-27 16:16:59 -0700193 }
Amin Hassani6600a562018-09-24 15:17:19 -0700194 if (attrs.find(kAttrCohortHint) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700195 app.cohorthint_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700196 app.cohorthint = attrs[kAttrCohortHint];
Alex Deymo8e18f932015-03-27 16:16:59 -0700197 }
Amin Hassani6600a562018-09-24 15:17:19 -0700198 if (attrs.find(kAttrCohortName) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700199 app.cohortname_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700200 app.cohortname = attrs[kAttrCohortName];
Alex Deymo8e18f932015-03-27 16:16:59 -0700201 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700202 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700203 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700204 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700205 data->apps.back().updatecheck_status = attrs[kAttrStatus];
Sen Jiang81259682017-03-30 15:11:30 -0700206 if (data->updatecheck_poll_interval.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700207 data->updatecheck_poll_interval = attrs[kAttrPollInterval];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700208 // Omaha sends arbitrary key-value pairs as extra attributes starting with
209 // an underscore.
210 for (const auto& attr : attrs) {
211 if (!attr.first.empty() && attr.first[0] == '_')
212 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
213 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400214 } else if (data->current_path == "/response/daystart") {
215 // Get the install-date.
Amin Hassani6600a562018-09-24 15:17:19 -0700216 data->daystart_elapsed_days = attrs[kAttrElapsedDays];
217 data->daystart_elapsed_seconds = attrs[kAttrElapsedSeconds];
David Zeuthene8ed8632014-07-24 13:38:10 -0400218 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
219 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700220 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700221 data->apps.back().url_codebase.push_back(attrs[kAttrCodeBase]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800222 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400223 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800224 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700225 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700226 data->apps.back().packages.push_back({.name = attrs[kAttrName],
227 .size = attrs[kAttrSize],
228 .hash = attrs[kAttrHashSha256]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400229 } else if (data->current_path == "/response/app/updatecheck/manifest") {
230 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700231 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700232 data->apps.back().manifest_version = attrs[kAttrVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400233 } else if (data->current_path ==
234 "/response/app/updatecheck/manifest/actions/action") {
235 // We only care about the postinstall action.
Amin Hassani6600a562018-09-24 15:17:19 -0700236 if (attrs[kAttrEvent] == kValPostInstall && !data->apps.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700237 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400238 }
239 }
240}
241
242// Callback function invoked by expat.
243void ParserHandlerEnd(void* user_data, const XML_Char* element) {
244 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
245 if (data->failed)
246 return;
247
248 const string path_suffix = string("/") + element;
249
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800250 if (!base::EndsWith(
251 data->current_path, path_suffix, base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400252 LOG(ERROR) << "Unexpected end element '" << element
253 << "' with current_path='" << data->current_path << "'";
254 data->failed = true;
255 return;
256 }
257 data->current_path.resize(data->current_path.size() - path_suffix.size());
258}
259
David Zeuthenf3e28012014-08-26 18:23:52 -0400260// Callback function invoked by expat.
261//
262// This is called for entity declarations. Since Omaha is guaranteed
263// to never return any XML with entities our course of action is to
264// just stop parsing. This avoids potential resource exhaustion
265// problems AKA the "billion laughs". CVE-2013-0340.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800266void ParserHandlerEntityDecl(void* user_data,
267 const XML_Char* entity_name,
David Zeuthenf3e28012014-08-26 18:23:52 -0400268 int is_parameter_entity,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800269 const XML_Char* value,
David Zeuthenf3e28012014-08-26 18:23:52 -0400270 int value_length,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800271 const XML_Char* base,
272 const XML_Char* system_id,
273 const XML_Char* public_id,
274 const XML_Char* notation_name) {
David Zeuthenf3e28012014-08-26 18:23:52 -0400275 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
276
277 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
278 data->failed = true;
279 data->entity_decl = true;
280 XML_StopParser(data->xml_parser, false);
281}
282
David Zeuthene8ed8632014-07-24 13:38:10 -0400283} // namespace
284
Alex Deymoc1c17b42015-11-23 03:53:15 -0300285OmahaRequestAction::OmahaRequestAction(
286 SystemState* system_state,
287 OmahaEvent* event,
288 std::unique_ptr<HttpFetcher> http_fetcher,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700289 bool ping_only,
290 const string& session_id)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800291 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800292 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700293 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300294 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800295 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700296 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700297 ping_active_days_(0),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700298 ping_roll_call_days_(0),
299 session_id_(session_id) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800300 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700301}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000302
Darin Petkov6a5b3222010-07-13 14:55:28 -0700303OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000304
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700305// Calculates the value to use for the ping days parameter.
306int OmahaRequestAction::CalculatePingDays(const string& key) {
307 int days = kNeverPinged;
308 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800309 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700310 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
311 if (days < 0) {
312 // If |days| is negative, then the system clock must have jumped
313 // back in time since the ping was sent. Mark the value so that
314 // it doesn't get sent to the server but we still update the
315 // last ping daystart preference. This way the next ping time
316 // will be correct, hopefully.
317 days = kPingTimeJump;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800318 LOG(WARNING)
319 << "System clock jumped back in time. Resetting ping daystarts.";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700320 }
321 }
322 return days;
323}
324
325void OmahaRequestAction::InitPingDays() {
326 // We send pings only along with update checks, not with events.
327 if (IsEvent()) {
328 return;
329 }
330 // TODO(petkov): Figure a way to distinguish active use pings
331 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700332 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700333 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
334 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
335}
336
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700337bool OmahaRequestAction::ShouldPing() const {
Amin Hassani7fca2862019-03-28 16:09:22 -0700338 if (ping_active_days_ == kNeverPinged &&
339 ping_roll_call_days_ == kNeverPinged) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700340 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
341 if (powerwash_count > 0) {
342 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
343 << "powerwash_count is " << powerwash_count;
344 return false;
345 }
Amin Hassani1677e812017-06-21 13:36:36 -0700346 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
347 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
348 << "the first_active_omaha_ping_sent is true";
349 return false;
350 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700351 return true;
352 }
353 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
354}
355
David Zeuthen639aa362014-02-03 16:23:44 -0800356// static
357int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
358 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700359 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800360 return -1;
361
362 // If we have the value stored on disk, just return it.
363 int64_t stored_value;
364 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
365 // Convert and sanity-check.
366 int install_date_days = static_cast<int>(stored_value);
367 if (install_date_days >= 0)
368 return install_date_days;
369 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
370 << install_date_days << " looks suspicious.";
371 prefs->Delete(kPrefsInstallDateDays);
372 }
373
374 // Otherwise, if OOBE is not complete then do nothing and wait for
375 // ParseResponse() to call ParseInstallDate() and then
376 // PersistInstallDate() to set the kPrefsInstallDateDays state
377 // variable. Once that is done, we'll then report back in future
378 // Omaha requests. This works exactly because OOBE triggers an
379 // update check.
380 //
381 // However, if OOBE is complete and the kPrefsInstallDateDays state
382 // variable is not set, there are two possibilities
383 //
384 // 1. The update check in OOBE failed so we never got a response
385 // from Omaha (no network etc.); or
386 //
387 // 2. OOBE was done on an older version that didn't write to the
388 // kPrefsInstallDateDays state variable.
389 //
390 // In both cases, we approximate the install date by simply
391 // inspecting the timestamp of when OOBE happened.
392
393 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700394 if (!system_state->hardware()->IsOOBEEnabled() ||
395 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800396 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700397 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800398 return -1;
399 }
400
401 int num_days;
402 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
403 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
404 << "as its value '" << utils::ToString(time_of_oobe)
405 << "' looks suspicious.";
406 return -1;
407 }
408
409 // Persist this to disk, for future use.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800410 if (!OmahaRequestAction::PersistInstallDate(
411 system_state, num_days, kProvisionedFromOOBEMarker))
David Zeuthen639aa362014-02-03 16:23:44 -0800412 return -1;
413
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800414 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to " << num_days
415 << " days";
David Zeuthen639aa362014-02-03 16:23:44 -0800416
417 return num_days;
418}
419
Darin Petkov6a5b3222010-07-13 14:55:28 -0700420void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000421 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700422 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700423 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700424 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700425 return;
426 }
David Zeuthen639aa362014-02-03 16:23:44 -0800427
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700428 OmahaRequestBuilderXml omaha_request(event_.get(),
429 params_,
430 ping_only_,
431 ShouldPing(), // include_ping
432 ping_active_days_,
433 ping_roll_call_days_,
434 GetInstallDate(system_state_),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700435 system_state_->prefs(),
436 session_id_);
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700437 string request_post = omaha_request.GetRequest();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700438
Sen Jiang42fa45e2018-03-12 11:02:14 -0700439 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700440 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
441 params_->interactive() ? "fg" : "bg");
442 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
443 http_fetcher_->SetHeader(
444 kXGoogleUpdateUpdater,
445 base::StringPrintf(
446 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700447 http_fetcher_->SetHeader(kXGoogleUpdateSessionId, session_id_);
Alex Deymo14ad88e2016-06-29 12:30:14 -0700448
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800449 http_fetcher_->SetPostData(
450 request_post.data(), request_post.size(), kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700451 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700452 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700453 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000454}
455
Darin Petkov6a5b3222010-07-13 14:55:28 -0700456void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000457 http_fetcher_->TerminateTransfer();
458}
459
460// We just store the response in the buffer. Once we've received all bytes,
461// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700462bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800463 const void* bytes,
464 size_t length) {
465 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
466 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700467 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000468}
469
470namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000471
472// Parses a 64 bit base-10 int from a string and returns it. Returns 0
473// on error. If the string contains "0", that's indistinguishable from
474// error.
475off_t ParseInt(const string& str) {
476 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700477 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000478 if (rc < 1) {
479 // failure
480 return 0;
481 }
482 return ret;
483}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700484
David Zeuthene8ed8632014-07-24 13:38:10 -0400485// Parses |str| and returns |true| if, and only if, its value is "true".
486bool ParseBool(const string& str) {
487 return str == "true";
488}
489
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700490// Update the last ping day preferences based on the server daystart
491// response. Returns true on success, false otherwise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800492bool UpdateLastPingDays(OmahaParserData* parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700493 int64_t elapsed_seconds = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800494 TEST_AND_RETURN_FALSE(base::StringToInt64(
495 parser_data->daystart_elapsed_seconds, &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700496 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
497
498 // Remember the local time that matches the server's last midnight
499 // time.
500 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
501 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
502 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
503 return true;
504}
Sen Jiang81259682017-03-30 15:11:30 -0700505
506// Parses the package node in the given XML document and populates
507// |output_object| if valid. Returns true if we should continue the parsing.
508// False otherwise, in which case it sets any error code using |completer|.
509bool ParsePackage(OmahaParserData::App* app,
510 OmahaResponse* output_object,
511 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700512 if (app->updatecheck_status.empty() ||
513 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700514 if (!app->packages.empty()) {
515 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
516 completer->set_code(ErrorCode::kOmahaResponseInvalid);
517 return false;
518 }
519 return true;
520 }
521 if (app->packages.empty()) {
522 LOG(ERROR) << "Omaha Response has no packages";
523 completer->set_code(ErrorCode::kOmahaResponseInvalid);
524 return false;
525 }
526 if (app->url_codebase.empty()) {
527 LOG(ERROR) << "No Omaha Response URLs";
528 completer->set_code(ErrorCode::kOmahaResponseInvalid);
529 return false;
530 }
531 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
532 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700533 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700534 ":",
535 base::TRIM_WHITESPACE,
536 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700537 vector<string> metadata_signatures = base::SplitString(
538 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
539 ":",
540 base::TRIM_WHITESPACE,
541 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700542 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700543 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700544 ":",
545 base::TRIM_WHITESPACE,
546 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700547 for (size_t i = 0; i < app->packages.size(); i++) {
548 const auto& package = app->packages[i];
549 if (package.name.empty()) {
550 LOG(ERROR) << "Omaha Response has empty package name";
551 completer->set_code(ErrorCode::kOmahaResponseInvalid);
552 return false;
553 }
554 LOG(INFO) << "Found package " << package.name;
555
556 OmahaResponse::Package out_package;
557 for (const string& codebase : app->url_codebase) {
558 if (codebase.empty()) {
559 LOG(ERROR) << "Omaha Response URL has empty codebase";
560 completer->set_code(ErrorCode::kOmahaResponseInvalid);
561 return false;
562 }
563 out_package.payload_urls.push_back(codebase + package.name);
564 }
565 // Parse the payload size.
566 base::StringToUint64(package.size, &out_package.size);
567 if (out_package.size <= 0) {
568 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
569 completer->set_code(ErrorCode::kOmahaResponseInvalid);
570 return false;
571 }
572 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
573
574 if (i < metadata_sizes.size())
575 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
576 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
577 << " bytes";
578
579 if (i < metadata_signatures.size())
580 out_package.metadata_signature = metadata_signatures[i];
581 LOG(INFO) << "Payload metadata signature = "
582 << out_package.metadata_signature;
583
584 out_package.hash = package.hash;
585 if (out_package.hash.empty()) {
586 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
587 completer->set_code(ErrorCode::kOmahaResponseInvalid);
588 return false;
589 }
590 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700591
592 if (i < is_delta_payloads.size())
593 out_package.is_delta = ParseBool(is_delta_payloads[i]);
594 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
595
Sen Jiang81259682017-03-30 15:11:30 -0700596 output_object->packages.push_back(std::move(out_package));
597 }
598
599 return true;
600}
601
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700602// Parses the 2 key version strings kernel_version and firmware_version. If the
603// field is not present, or cannot be parsed the values default to 0xffff.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700604void ParseRollbackVersions(int allowed_milestones,
605 OmahaParserData* parser_data,
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700606 OmahaResponse* output_object) {
607 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700608 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700609 &output_object->rollback_key_version.firmware_key,
610 &output_object->rollback_key_version.firmware);
611 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700612 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700613 &output_object->rollback_key_version.kernel_key,
614 &output_object->rollback_key_version.kernel);
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700615
616 // Create the attribute name strings for milestone N - allowed_milestones.
617 const string firmware_max_rollforward_attr =
618 base::StringPrintf("%s_%i", kAttrFirmwareVersion, allowed_milestones);
619 const string kernel_max_rollforward_attr =
620 base::StringPrintf("%s_%i", kAttrKernelVersion, allowed_milestones);
621
622 const bool max_firmware_and_kernel_exist =
623 parser_data->updatecheck_attrs.count(firmware_max_rollforward_attr) > 0 &&
624 parser_data->updatecheck_attrs.count(kernel_max_rollforward_attr) > 0;
625
626 string firmware_version;
627 string kernel_version;
628 if (max_firmware_and_kernel_exist) {
629 firmware_version =
630 parser_data->updatecheck_attrs[firmware_max_rollforward_attr];
631 kernel_version =
632 parser_data->updatecheck_attrs[kernel_max_rollforward_attr];
633 }
634
635 LOG(INFO) << "For milestone N-" << allowed_milestones
636 << " firmware_key_version=" << firmware_version
637 << " kernel_key_version=" << kernel_version;
638
639 OmahaResponse::RollbackKeyVersion version;
640 utils::ParseRollbackKeyVersion(
641 firmware_version, &version.firmware_key, &version.firmware);
642 utils::ParseRollbackKeyVersion(
643 kernel_version, &version.kernel_key, &version.kernel);
644
645 output_object->past_rollback_key_version = std::move(version);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700646}
647
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700648} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000649
David Zeuthene8ed8632014-07-24 13:38:10 -0400650bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700651 OmahaResponse* output_object,
652 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700653 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700654 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700655 return false;
656 }
Sen Jiang81259682017-03-30 15:11:30 -0700657 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700658
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800659 // chromium-os:37289: The PollInterval is not supported by Omaha server
660 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700661 // slow down the request rate from the server-side. Note that the PollInterval
662 // is not persisted, so it has to be sent by the server on every response to
663 // guarantee that the scheduler uses this value (otherwise, if the device got
664 // rebooted after the last server-indicated value, it'll revert to the default
665 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
666 // based on the assumption that we perform an update check every hour so that
667 // the max value of 8 will roughly be equivalent to one work day. If we decide
668 // to use PollInterval permanently, we should update the
669 // max_update_checks_allowed to take PollInterval into account. Note: The
670 // parsing for PollInterval happens even before parsing of the status because
671 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400672 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700673 &output_object->poll_interval);
674
David Zeuthen639aa362014-02-03 16:23:44 -0800675 // Check for the "elapsed_days" attribute in the "daystart"
676 // element. This is the number of days since Jan 1 2007, 0:00
677 // PST. If we don't have a persisted value of the Omaha InstallDate,
678 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400679 if (ParseInstallDate(parser_data, output_object) &&
680 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800681 // Since output_object->install_date_days is never negative, the
682 // elapsed_days -> install-date calculation is reduced to simply
683 // rounding down to the nearest number divisible by 7.
684 int remainder = output_object->install_date_days % 7;
685 int install_date_days_rounded =
686 output_object->install_date_days - remainder;
687 if (PersistInstallDate(system_state_,
688 install_date_days_rounded,
689 kProvisionedFromOmahaResponse)) {
690 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
691 << install_date_days_rounded << " days";
692 }
693 }
694
Alex Deymo00d79ac2015-06-29 15:41:49 -0700695 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700696 for (const auto& app : parser_data->apps) {
697 if (app.id == params_->GetAppId()) {
698 if (app.cohort_set)
699 PersistCohortData(kPrefsOmahaCohort, app.cohort);
700 if (app.cohorthint_set)
701 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
702 if (app.cohortname_set)
703 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
704 break;
705 }
706 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700707
Alex Deymob3fa53b2016-04-18 19:57:58 -0700708 // Parse the updatecheck attributes.
709 PersistEolStatus(parser_data->updatecheck_attrs);
Marton Hunyady199152d2018-05-07 19:08:48 +0200710 // Rollback-related updatecheck attributes.
711 // Defaults to false if attribute is not present.
712 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -0700713 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700714
715 // Parses the rollback versions of the current image. If the fields do not
716 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700717 ParseRollbackVersions(
718 params_->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -0700719
David Zeuthene8ed8632014-07-24 13:38:10 -0400720 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700721 return false;
722
David Zeuthene8ed8632014-07-24 13:38:10 -0400723 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700724 return false;
725
Sen Jiang0affc2c2017-02-10 15:55:05 -0800726 // Package has to be parsed after Params now because ParseParams need to make
727 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -0700728 for (auto& app : parser_data->apps)
729 if (!ParsePackage(&app, output_object, completer))
730 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800731
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700732 return true;
733}
734
David Zeuthene8ed8632014-07-24 13:38:10 -0400735bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700736 OmahaResponse* output_object,
737 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700738 output_object->update_exists = false;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700739 for (const auto& app : parser_data->apps) {
740 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -0700741 if (status == kValNoUpdate) {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700742 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -0700743 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700744 output_object->update_exists = false;
745 break;
Sen Jiang81259682017-03-30 15:11:30 -0700746 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700747 auto const& attr_no_update =
748 app.action_postinstall_attrs.find(kAttrNoUpdate);
749 if (attr_no_update != app.action_postinstall_attrs.end() &&
750 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700751 // noupdate="true" in postinstall attributes means it's an update to
752 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -0700753 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700754 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700755 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700756 output_object->update_exists = true;
757 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700758 } else if (status.empty() && params_->is_install() &&
759 params_->GetAppId() == app.id) {
760 // Skips the platform app for install operation.
761 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -0700762 } else {
763 LOG(ERROR) << "Unknown Omaha response status: " << status;
764 completer->set_code(ErrorCode::kOmahaResponseInvalid);
765 return false;
766 }
767 }
768 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700769 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700770 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700771 }
772
Sen Jiang81259682017-03-30 15:11:30 -0700773 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700774}
775
David Zeuthene8ed8632014-07-24 13:38:10 -0400776bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700777 OmahaResponse* output_object,
778 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700779 map<string, string> attrs;
780 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700781 if (app.id == params_->GetAppId()) {
782 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -0700783 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700784 } else if (!params_->system_app_id().empty() &&
785 app.id == params_->system_app_id()) {
786 // this is the system app (this check is intentionally skipped if there is
787 // no system_app_id set)
788 output_object->system_version = app.manifest_version;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700789 } else if (params_->is_install() &&
790 app.manifest_version != params_->app_version()) {
791 LOG(WARNING) << "An app has a different version (" << app.manifest_version
792 << ") that is different than platform app version ("
793 << params_->app_version() << ")";
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700794 }
795 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700796 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700797 }
Sen Jiang81259682017-03-30 15:11:30 -0700798 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700799 if (params_->is_install()) {
800 LOG(INFO) << "Use request version for Install operation.";
801 output_object->version = params_->app_version();
802 }
Chris Sosa3b748432013-06-20 16:42:59 -0700803 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700804 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700805 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700806 return false;
807 }
808
809 LOG(INFO) << "Received omaha response to update to version "
810 << output_object->version;
811
David Zeuthene8ed8632014-07-24 13:38:10 -0400812 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700813 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700814 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700815 return false;
816 }
817
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800818 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -0700819 output_object->more_info_url = attrs[kAttrMoreInfo];
820 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
821 output_object->deadline = attrs[kAttrDeadline];
822 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700823 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -0700824 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700825 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -0700826 ParseBool(attrs[kAttrDisableP2PForSharing]);
827 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800828
Amin Hassani6600a562018-09-24 15:17:19 -0700829 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800830 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800831 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700832
Jay Srinivasan08262882012-12-28 19:29:43 -0800833 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -0700834 ParseBool(attrs[kAttrDisablePayloadBackoff]);
835 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800836
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700837 return true;
838}
839
David Zeuthene8ed8632014-07-24 13:38:10 -0400840// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000841// and fill in the appropriate fields of the output object. Also, notifies
842// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800843void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -0700844 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000845 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800846 string current_response(response_buffer_.begin(), response_buffer_.end());
847 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700848
Gilad Arnold74b5f552014-10-07 08:17:16 -0700849 PayloadStateInterface* const payload_state = system_state_->payload_state();
850
Zentaro Kavanagh76af2662018-05-15 10:54:53 -0700851 // Set the max kernel key version based on whether rollback is allowed.
852 SetMaxKernelKeyVersionForRollback();
853
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700854 // Events are best effort transactions -- assume they always succeed.
855 if (IsEvent()) {
856 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700857 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700858 return;
859 }
860
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700861 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700862 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700863 int code = GetHTTPResponseCode();
864 // Makes sure we send sane error values.
865 if (code < 0 || code >= 1000) {
866 code = 999;
867 }
David Zeuthena99981f2013-04-29 13:42:47 -0700868 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700869 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000870 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700871 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000872
David Zeuthene8ed8632014-07-24 13:38:10 -0400873 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400874 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400875 XML_SetUserData(parser, &parser_data);
876 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400877 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800878 XML_Status res =
879 XML_Parse(parser,
880 reinterpret_cast<const char*>(response_buffer_.data()),
881 response_buffer_.size(),
882 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400883
884 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700885 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800886 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
887 << XML_GetCurrentLineNumber(parser) << " col "
888 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -0700889 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400890 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
891 if (response_buffer_.empty()) {
892 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
893 } else if (parser_data.entity_decl) {
894 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
895 }
896 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000897 return;
898 }
Amin Hassani91f48b42018-08-06 17:47:14 -0700899 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000900
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700901 // Update the last ping day preferences based on the server daystart response
902 // even if we didn't send a ping. Omaha always includes the daystart in the
903 // response, but log the error if it didn't.
904 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
905 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700906
Amin Hassani1677e812017-06-21 13:36:36 -0700907 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
908 // we have got a response from omaha and if its value has never been set to
909 // true before. Failure of this function should be ignored. There should be no
910 // need to check if a=-1 has been sent because older devices have already sent
911 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
912 // future checks.
913 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700914 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
915 system_state_->metrics_reporter()->ReportInternalErrorCode(
916 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
917 }
Amin Hassani1677e812017-06-21 13:36:36 -0700918 }
919
Thieu Le116fda32011-04-19 11:01:54 -0700920 if (!HasOutputPipe()) {
921 // Just set success to whether or not the http transfer succeeded,
922 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700923 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700924 return;
925 }
926
Darin Petkov6a5b3222010-07-13 14:55:28 -0700927 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400928 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000929 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700930 output_object.update_exists = true;
931 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000932
Toni Barzic61544e62018-10-11 14:37:30 -0700933 LoadOrPersistUpdateFirstSeenAtPref();
934
Weidong Guo421ff332017-04-17 10:08:38 -0700935 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -0700936 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -0700937 // No need to change output_object.update_exists here, since the value
938 // has been output to the pipe.
939 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700940 return;
941 }
942
David Zeuthen8f191b22013-08-06 12:27:50 -0700943 // If Omaha says to disable p2p, respect that
944 if (output_object.disable_p2p_for_downloading) {
945 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
946 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700947 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700948 }
949 if (output_object.disable_p2p_for_sharing) {
950 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
951 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700952 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700953 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800954
955 // Update the payload state with the current response. The payload state
956 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800957 // from what's stored already. We are updating the payload state as late
958 // as possible in this method so that if a new release gets pushed and then
959 // got pulled back due to some issues, we don't want to clear our internal
960 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800961 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800962
David Zeuthen8f191b22013-08-06 12:27:50 -0700963 // It could be we've already exceeded the deadline for when p2p is
964 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700965 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700966 payload_state->P2PNewAttempt();
967 if (!payload_state->P2PAttemptAllowed()) {
968 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
969 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700970 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700971 }
972 }
973
974 // From here on, we'll complete stuff in CompleteProcessing() so
975 // disable |completer| since we'll create a new one in that
976 // function.
977 completer.set_should_complete(false);
978
979 // If we're allowed to use p2p for downloading we do not pay
980 // attention to wall-clock-based waiting if the URL is indeed
981 // available via p2p. Therefore, check if the file is available via
982 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -0700983 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700984 LookupPayloadViaP2P(output_object);
985 } else {
986 CompleteProcessing();
987 }
988}
989
Xiaochu Liu4a1173a2019-04-10 10:49:08 -0700990void OmahaRequestAction::ReportUpdateCheckMetrics(
991 metrics::CheckResult result,
992 metrics::CheckReaction reaction,
993 metrics::DownloadErrorCode download_error_code) {
994 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
995 system_state_, result, reaction, download_error_code);
996}
997
David Zeuthen8f191b22013-08-06 12:27:50 -0700998void OmahaRequestAction::CompleteProcessing() {
999 ScopedActionCompleter completer(processor_, this);
1000 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1001 PayloadStateInterface* payload_state = system_state_->payload_state();
1002
1003 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001004 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001005 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001006 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001007 return;
1008 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001009
Chris Sosa20f005c2013-09-05 13:53:08 -07001010 if (payload_state->ShouldBackoffDownload()) {
1011 output_object.update_exists = false;
1012 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1013 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001014 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001015 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001016 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001017 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001018}
1019
1020void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1021 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1022 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001023 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001024 } else {
1025 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1026 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001027 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001028 }
1029 CompleteProcessing();
1030}
1031
1032void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001033 // If the device is in the middle of an update, the state variables
1034 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1035 // tracks the offset and length of the operation currently in
1036 // progress. The offset is based from the end of the manifest which
1037 // is kPrefsManifestMetadataSize bytes long.
1038 //
1039 // To make forward progress and avoid deadlocks, we need to find a
1040 // peer that has at least the entire operation we're currently
1041 // working on. Otherwise we may end up in a situation where two
1042 // devices bounce back and forth downloading from each other,
1043 // neither making any forward progress until one of them decides to
1044 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1045 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001046 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001047 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001048 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001049 int64_t next_data_offset = 0;
1050 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001051 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001052 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1053 &manifest_metadata_size) &&
1054 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001055 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1056 &manifest_signature_size) &&
1057 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001058 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001059 &next_data_offset) &&
1060 next_data_offset != -1 &&
1061 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1062 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001063 minimum_size = manifest_metadata_size + manifest_signature_size +
1064 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001065 }
1066
Sen Jiang0affc2c2017-02-10 15:55:05 -08001067 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001068 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001069 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001070 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001071 string file_id =
1072 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001073 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001074 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1075 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001076 system_state_->p2p_manager()->LookupUrlForFile(
1077 file_id,
1078 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001079 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001080 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1081 base::Unretained(this)));
1082 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001083}
1084
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001085bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001086 if (params_->interactive()) {
1087 LOG(INFO) << "Not deferring download because update is interactive.";
1088 return false;
1089 }
1090
David Zeuthen8f191b22013-08-06 12:27:50 -07001091 // If we're using p2p to download _and_ we have a p2p URL, we never
1092 // defer the download. This is because the download will always
1093 // happen from a peer on the LAN and we've been waiting in line for
1094 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001095 const PayloadStateInterface* payload_state = system_state_->payload_state();
1096 if (payload_state->GetUsingP2PForDownloading() &&
1097 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001098 LOG(INFO) << "Download not deferred because download "
1099 << "will happen from a local peer (via p2p).";
1100 return false;
1101 }
1102
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001103 // We should defer the downloads only if we've first satisfied the
1104 // wall-clock-based-waiting period and then the update-check-based waiting
1105 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001106 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001107 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1108 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001109 return false;
1110 }
1111
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001112 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001113 case kWallClockWaitNotSatisfied:
1114 // We haven't even satisfied the first condition, passing the
1115 // wall-clock-based waiting period, so we should defer the downloads
1116 // until that happens.
1117 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1118 return true;
1119
1120 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1121 LOG(INFO) << "wall-clock-based-wait satisfied and "
1122 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001123 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001124
1125 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1126 // Wall-clock-based waiting period is satisfied, and it's determined
1127 // that we do not need the update-check-based wait. so no need to
1128 // defer downloads.
1129 LOG(INFO) << "wall-clock-based-wait satisfied and "
1130 << "update-check-based-wait is not required.";
1131 return false;
1132
1133 default:
1134 // Returning false for this default case so we err on the
1135 // side of downloading updates than deferring in case of any bugs.
1136 NOTREACHED();
1137 return false;
1138 }
1139}
1140
1141OmahaRequestAction::WallClockWaitResult
1142OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001143 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001144 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1145 if (update_first_seen_at == base::Time()) {
1146 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
1147 "persisted";
1148 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001149 }
1150
Sen Jiang7c1171e2016-06-23 11:35:40 -07001151 TimeDelta elapsed_time =
1152 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1153 TimeDelta max_scatter_period =
1154 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001155 int64_t staging_wait_time_in_days = 0;
1156 // Use staging and its default max value if staging is on.
1157 if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1158 &staging_wait_time_in_days) &&
1159 staging_wait_time_in_days > 0)
1160 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001161
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001162 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001163 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001164 << ", Time Elapsed = "
1165 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001166 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001167
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001168 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001169 // The deadline is set for all rules which serve a delta update from a
1170 // previous FSI, which means this update will be applied mostly in OOBE
1171 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1172 // quickly.
1173 LOG(INFO) << "Not scattering as deadline flag is set";
1174 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1175 }
1176
1177 if (max_scatter_period.InDays() == 0) {
1178 // This means the Omaha rule creator decides that this rule
1179 // should not be scattered irrespective of the policy.
1180 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1181 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1182 }
1183
1184 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001185 // This means we've waited more than the upperbound wait in the rule
1186 // from the time we first saw a valid update available to us.
1187 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001188 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1189 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1190 }
1191
1192 // This means we are required to participate in scattering.
1193 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001194 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001195 if (remaining_wait_time.InSeconds() <= 0) {
1196 // Yes, it's our turn now.
1197 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1198
1199 // But we can't download until the update-check-count-based wait is also
1200 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001201 return params_->update_check_count_wait_enabled()
1202 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1203 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001204 }
1205
1206 // Not our turn yet, so we have to wait until our turn to
1207 // help scatter the downloads across all clients of the enterprise.
1208 LOG(INFO) << "Update deferred for another "
1209 << utils::FormatSecs(remaining_wait_time.InSeconds())
1210 << " per policy.";
1211 return kWallClockWaitNotSatisfied;
1212}
1213
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001214bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001215 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001216
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001217 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1218 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1219 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001220 // We are unable to read the update check count from file for some reason.
1221 // So let's proceed anyway so as to not stall the update.
1222 LOG(ERROR) << "Unable to read update check count. "
1223 << "Skipping update-check-count-based-wait.";
1224 return true;
1225 }
1226 } else {
1227 // This file does not exist. This means we haven't started our update
1228 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001229 update_check_count_value =
1230 base::RandInt(params_->min_update_checks_needed(),
1231 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001232
1233 LOG(INFO) << "Randomly picked update check count value = "
1234 << update_check_count_value;
1235
1236 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001237 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1238 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001239 // We weren't able to write the update check count file for some reason.
1240 // So let's proceed anyway so as to not stall the update.
1241 LOG(ERROR) << "Unable to write update check count. "
1242 << "Skipping update-check-count-based-wait.";
1243 return true;
1244 }
1245 }
1246
1247 if (update_check_count_value == 0) {
1248 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1249 return true;
1250 }
1251
1252 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001253 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001254 // We err on the side of skipping scattering logic instead of stalling
1255 // a machine from receiving any updates in case of any unexpected state.
1256 LOG(ERROR) << "Invalid value for update check count detected. "
1257 << "Skipping update-check-count-based-wait.";
1258 return true;
1259 }
1260
1261 // Legal value, we need to wait for more update checks to happen
1262 // until this becomes 0.
1263 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001264 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001265 return false;
1266}
1267
David Zeuthen639aa362014-02-03 16:23:44 -08001268// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001269bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001270 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001271 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001272 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001273 return false;
1274
1275 if (elapsed_days < 0)
1276 return false;
1277
1278 output_object->install_date_days = elapsed_days;
1279 return true;
1280}
1281
1282// static
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001283bool OmahaRequestAction::HasInstallDate(SystemState* system_state) {
David Zeuthen639aa362014-02-03 16:23:44 -08001284 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001285 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001286 return false;
1287
1288 return prefs->Exists(kPrefsInstallDateDays);
1289}
1290
1291// static
1292bool OmahaRequestAction::PersistInstallDate(
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001293 SystemState* system_state,
David Zeuthen639aa362014-02-03 16:23:44 -08001294 int install_date_days,
1295 InstallDateProvisioningSource source) {
1296 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1297
1298 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001299 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001300 return false;
1301
1302 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1303 return false;
1304
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001305 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001306 static_cast<int>(source), // Sample.
1307 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001308 return true;
1309}
1310
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001311bool OmahaRequestAction::PersistCohortData(const string& prefs_key,
1312 const string& new_value) {
Alex Deymo8e18f932015-03-27 16:16:59 -07001313 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1314 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1315 return system_state_->prefs()->Delete(prefs_key);
1316 } else if (!new_value.empty()) {
1317 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1318 return system_state_->prefs()->SetString(prefs_key, new_value);
1319 }
1320 return true;
1321}
1322
Alex Deymob3fa53b2016-04-18 19:57:58 -07001323bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
Amin Hassani6600a562018-09-24 15:17:19 -07001324 auto eol_attr = attrs.find(kAttrEol);
Alex Deymob3fa53b2016-04-18 19:57:58 -07001325 if (eol_attr != attrs.end()) {
1326 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1327 eol_attr->second);
1328 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1329 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1330 }
1331 return true;
1332}
1333
David Zeuthen33bae492014-02-25 16:16:18 -08001334void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1335 // We only want to report this on "update check".
1336 if (ping_only_ || event_ != nullptr)
1337 return;
1338
1339 metrics::CheckResult result = metrics::CheckResult::kUnset;
1340 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1341 metrics::DownloadErrorCode download_error_code =
1342 metrics::DownloadErrorCode::kUnset;
1343
1344 // Regular update attempt.
1345 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001346 case ErrorCode::kSuccess:
1347 // OK, we parsed the response successfully but that does
1348 // necessarily mean that an update is available.
1349 if (HasOutputPipe()) {
1350 const OmahaResponse& response = GetOutputObject();
1351 if (response.update_exists) {
1352 result = metrics::CheckResult::kUpdateAvailable;
1353 reaction = metrics::CheckReaction::kUpdating;
1354 } else {
1355 result = metrics::CheckResult::kNoUpdateAvailable;
1356 }
David Zeuthen33bae492014-02-25 16:16:18 -08001357 } else {
1358 result = metrics::CheckResult::kNoUpdateAvailable;
1359 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001360 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001361
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001362 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1363 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1364 result = metrics::CheckResult::kUpdateAvailable;
1365 reaction = metrics::CheckReaction::kIgnored;
1366 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001367
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001368 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1369 result = metrics::CheckResult::kUpdateAvailable;
1370 reaction = metrics::CheckReaction::kDeferring;
1371 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001372
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001373 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1374 result = metrics::CheckResult::kUpdateAvailable;
1375 reaction = metrics::CheckReaction::kBackingOff;
1376 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001377
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001378 default:
1379 // We report two flavors of errors, "Download errors" and "Parsing
1380 // error". Try to convert to the former and if that doesn't work
1381 // we know it's the latter.
1382 metrics::DownloadErrorCode tmp_error =
1383 metrics_utils::GetDownloadErrorCode(code);
1384 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1385 result = metrics::CheckResult::kDownloadError;
1386 download_error_code = tmp_error;
1387 } else {
1388 result = metrics::CheckResult::kParsingError;
1389 }
1390 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001391 }
1392
Xiaochu Liu4a1173a2019-04-10 10:49:08 -07001393 ReportUpdateCheckMetrics(result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001394}
1395
Toni Barzic61544e62018-10-11 14:37:30 -07001396bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1397 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001398 // Note: policy decision to not update to a version we rolled back from.
1399 string rollback_version =
1400 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001401 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001402 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001403 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001404 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001405 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001406 return true;
1407 }
1408 }
1409
Toni Barzic61544e62018-10-11 14:37:30 -07001410 if (system_state_->hardware()->IsOOBEEnabled() &&
1411 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
1412 (response.deadline.empty() ||
1413 system_state_->payload_state()->GetRollbackHappened()) &&
1414 params_->app_version() != "ForcedUpdate") {
1415 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1416 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1417 return true;
1418 }
1419
Weidong Guo421ff332017-04-17 10:08:38 -07001420 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001421 LOG(INFO) << "Update is not allowed over current connection.";
1422 return true;
1423 }
1424
1425 // Note: We could technically delete the UpdateFirstSeenAt state when we
1426 // return true. If we do, it'll mean a device has to restart the
1427 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1428 // turned on again. On the other hand, it also increases the chance of update
1429 // starvation if an admin turns AU on/off more frequently. We choose to err on
1430 // the side of preventing starvation at the cost of not applying scattering in
1431 // those cases.
1432 return false;
1433}
1434
Weidong Guo421ff332017-04-17 10:08:38 -07001435bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1436 const OmahaResponse& response) const {
1437 PrefsInterface* prefs = system_state_->prefs();
1438
1439 if (!prefs) {
1440 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1441 "not available.";
1442 return false;
1443 }
1444
1445 bool is_allowed;
1446
1447 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1448 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1449 is_allowed) {
1450 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1451 "set to true.";
1452 return true;
1453 }
1454
1455 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1456 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1457 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1458 "set to false or does not exist while target does not exist.";
1459 return false;
1460 }
1461
1462 std::string target_version;
1463 int64_t target_size;
1464
1465 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1466 &target_version) ||
1467 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1468 LOG(INFO) << "Disabling updates over cellular as the target version or "
1469 "size is not accessible.";
1470 return false;
1471 }
1472
1473 uint64_t total_packages_size = 0;
1474 for (const auto& package : response.packages) {
1475 total_packages_size += package.size;
1476 }
1477 if (target_version == response.version &&
1478 static_cast<uint64_t>(target_size) == total_packages_size) {
1479 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1480 "omaha response.";
1481 return true;
1482 } else {
1483 LOG(INFO) << "Disabling updates over cellular as the target does not"
1484 "match the omaha response.";
1485 return false;
1486 }
1487}
1488
1489bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1490 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001491 ConnectionType type;
1492 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001493 ConnectionManagerInterface* connection_manager =
1494 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001495 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001496 LOG(INFO) << "We could not determine our connection type. "
1497 << "Defaulting to allow updates.";
1498 return true;
1499 }
Weidong Guo421ff332017-04-17 10:08:38 -07001500
Chris Sosa77f79e82014-06-02 18:16:24 -07001501 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001502 bool is_device_policy_set =
1503 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1504 // Treats tethered connection as if it is cellular connection.
1505 bool is_over_cellular = type == ConnectionType::kCellular ||
1506 tethering == ConnectionTethering::kConfirmed;
1507
1508 if (!is_over_cellular) {
1509 // There's no need to further check user preferences as we are not over
1510 // cellular connection.
1511 if (!is_allowed)
1512 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1513 } else if (is_device_policy_set) {
1514 // There's no need to further check user preferences as the device policy
1515 // is set regarding updates over cellular.
1516 if (!is_allowed)
1517 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1518 } else {
1519 // Deivce policy is not set, so user preferences overwrite whether to
1520 // allow updates over cellular.
1521 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1522 if (!is_allowed)
1523 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1524 }
1525
Chris Sosa77f79e82014-06-02 18:16:24 -07001526 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001527 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001528 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1529 return is_allowed;
1530}
1531
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001532bool OmahaRequestAction::IsRollbackEnabled() const {
1533 if (policy_provider_->IsConsumerDevice()) {
1534 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1535 return false;
1536 }
1537
1538 if (!policy_provider_->device_policy_is_loaded()) {
1539 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1540 return true;
1541 }
1542
1543 int allowed_milestones;
1544 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1545 &allowed_milestones)) {
1546 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1547 "Defaulting to rollback enabled.";
1548 return true;
1549 }
1550
1551 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1552 return allowed_milestones > 0;
1553}
1554
1555void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001556 int max_kernel_rollforward;
1557 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001558 if (IsRollbackEnabled()) {
1559 // If rollback is enabled, set the max kernel key version to the current
1560 // kernel key version. This has the effect of freezing kernel key roll
1561 // forwards.
1562 //
1563 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1564 // key roll forward happens until the server side components of rollback
1565 // are implemented. Future changes will allow the Omaha server to return
1566 // the kernel key version from max_rollback_versions in the past. At that
1567 // point the max kernel key version will be set to that value, creating a
1568 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001569 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001570 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001571 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001572 } else {
1573 // For devices that are not rollback enabled (ie. consumer devices), the
1574 // max kernel key version is set to 0xfffffffe, which is logically
1575 // infinity. This maintains the previous behavior that that kernel key
1576 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001577 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001578 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001579 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001580 }
1581
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001582 bool max_rollforward_set =
1583 system_state_->hardware()->SetMaxKernelKeyRollforward(
1584 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001585 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001586 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001587 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001588 // Report metrics
1589 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1590 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001591}
1592
May Lippert60aa3ca2018-08-15 16:55:29 -07001593base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1594 Time update_first_seen_at;
1595 int64_t update_first_seen_at_int;
1596 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1597 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1598 &update_first_seen_at_int)) {
1599 // Note: This timestamp could be that of ANY update we saw in the past
1600 // (not necessarily this particular update we're considering to apply)
1601 // but never got to apply because of some reason (e.g. stop AU policy,
1602 // updates being pulled out from Omaha, changes in target version prefix,
1603 // new update being rolled out, etc.). But for the purposes of scattering
1604 // it doesn't matter which update the timestamp corresponds to. i.e.
1605 // the clock starts ticking the first time we see an update and we're
1606 // ready to apply when the random wait period is satisfied relative to
1607 // that first seen timestamp.
1608 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1609 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1610 << utils::ToString(update_first_seen_at);
1611 } else {
1612 // This seems like an unexpected error where the persisted value exists
1613 // but it's not readable for some reason.
1614 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1615 return base::Time();
1616 }
1617 } else {
1618 update_first_seen_at = system_state_->clock()->GetWallclockTime();
1619 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
1620 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1621 update_first_seen_at_int)) {
1622 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1623 << utils::ToString(update_first_seen_at);
1624 } else {
1625 // This seems like an unexpected error where the value cannot be
1626 // persisted for some reason.
1627 LOG(INFO) << "UpdateFirstSeenAt value "
1628 << utils::ToString(update_first_seen_at)
1629 << " cannot be persisted";
1630 return base::Time();
1631 }
1632 }
1633 return update_first_seen_at;
1634}
1635
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001636} // namespace chromeos_update_engine