blob: d67623f4ed7c837a8ecb1cd530a0efd0be073aa3 [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
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/cros/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>
Andrewe045aef2020-01-08 16:29:22 -080029#include <base/files/file_util.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070030#include <base/logging.h>
Jae Hoon Kimebea3392020-04-27 13:27:35 -070031#include <base/optional.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070032#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070033#include <base/strings/string_number_conversions.h>
Sen Jiang0affc2c2017-02-10 15:55:05 -080034#include <base/strings/string_split.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070035#include <base/strings/string_util.h>
36#include <base/strings/stringprintf.h>
37#include <base/time/time.h>
Sen Jiang684c9cd2017-10-17 16:26:45 -070038#include <brillo/key_value_store.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040039#include <expat.h>
Alex Deymoa2591792015-11-17 00:39:40 -030040#include <metrics/metrics_library.h>
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080041#include <policy/libpolicy.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000042
Alex Deymo39910dc2015-11-09 17:04:30 -080043#include "update_engine/common/action_pipe.h"
44#include "update_engine/common/constants.h"
45#include "update_engine/common/hardware_interface.h"
46#include "update_engine/common/hash_calculator.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070047#include "update_engine/common/metrics_reporter_interface.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080048#include "update_engine/common/platform_constants.h"
Andrewe045aef2020-01-08 16:29:22 -080049#include "update_engine/common/prefs.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080050#include "update_engine/common/prefs_interface.h"
Amin Hassani538bd592020-11-04 20:46:08 -080051#include "update_engine/common/system_state.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080052#include "update_engine/common/utils.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070053#include "update_engine/cros/connection_manager_interface.h"
54#include "update_engine/cros/omaha_request_builder_xml.h"
55#include "update_engine/cros/omaha_request_params.h"
56#include "update_engine/cros/p2p_manager.h"
57#include "update_engine/cros/payload_state_interface.h"
58#include "update_engine/cros/update_attempter.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080059#include "update_engine/metrics_utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000060
Jae Hoon Kimebea3392020-04-27 13:27:35 -070061using base::Optional;
Darin Petkov1cbd78f2010-07-29 12:38:34 -070062using base::Time;
63using base::TimeDelta;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080064using chromeos_update_manager::kRollforwardInfinity;
David Zeuthene8ed8632014-07-24 13:38:10 -040065using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000066using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040067using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000068
69namespace chromeos_update_engine {
70
Amin Hassani6600a562018-09-24 15:17:19 -070071// List of custom attributes that we interpret in the Omaha response:
72constexpr char kAttrDeadline[] = "deadline";
73constexpr char kAttrDisableP2PForDownloading[] = "DisableP2PForDownloading";
74constexpr char kAttrDisableP2PForSharing[] = "DisableP2PForSharing";
75constexpr char kAttrDisablePayloadBackoff[] = "DisablePayloadBackoff";
76constexpr char kAttrVersion[] = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080077// Deprecated: "IsDelta"
Amin Hassani6600a562018-09-24 15:17:19 -070078constexpr char kAttrIsDeltaPayload[] = "IsDeltaPayload";
79constexpr char kAttrMaxFailureCountPerUrl[] = "MaxFailureCountPerUrl";
80constexpr char kAttrMaxDaysToScatter[] = "MaxDaysToScatter";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080081// Deprecated: "ManifestSignatureRsa"
82// Deprecated: "ManifestSize"
Amin Hassani6600a562018-09-24 15:17:19 -070083constexpr char kAttrMetadataSignatureRsa[] = "MetadataSignatureRsa";
84constexpr char kAttrMetadataSize[] = "MetadataSize";
85constexpr char kAttrMoreInfo[] = "MoreInfo";
86constexpr char kAttrNoUpdate[] = "noupdate";
Don Garrett42bd3aa2013-04-10 18:14:56 -070087// Deprecated: "NeedsAdmin"
Amin Hassani6600a562018-09-24 15:17:19 -070088constexpr char kAttrPollInterval[] = "PollInterval";
89constexpr char kAttrPowerwash[] = "Powerwash";
90constexpr char kAttrPrompt[] = "Prompt";
91constexpr char kAttrPublicKeyRsa[] = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080092
Amin Hassani6600a562018-09-24 15:17:19 -070093// List of attributes that we interpret in the Omaha response:
94constexpr char kAttrAppId[] = "appid";
95constexpr char kAttrCodeBase[] = "codebase";
96constexpr char kAttrCohort[] = "cohort";
97constexpr char kAttrCohortHint[] = "cohorthint";
98constexpr char kAttrCohortName[] = "cohortname";
99constexpr char kAttrElapsedDays[] = "elapsed_days";
100constexpr char kAttrElapsedSeconds[] = "elapsed_seconds";
101constexpr char kAttrEvent[] = "event";
Vyshu Khota4c5413d2020-11-04 16:17:25 -0800102constexpr char kAttrFp[] = "fp";
Amin Hassani6600a562018-09-24 15:17:19 -0700103constexpr char kAttrHashSha256[] = "hash_sha256";
104// Deprecated: "hash"; Although we still need to pass it from the server for
105// backward compatibility.
106constexpr char kAttrName[] = "name";
107// Deprecated: "sha256"; Although we still need to pass it from the server for
108// backward compatibility.
109constexpr char kAttrSize[] = "size";
110constexpr char kAttrStatus[] = "status";
111
112// List of values that we interpret in the Omaha response:
113constexpr char kValPostInstall[] = "postinstall";
114constexpr char kValNoUpdate[] = "noupdate";
115
Alex Deymob3fa53b2016-04-18 19:57:58 -0700116// updatecheck attributes (without the underscore prefix).
Amin Hassani2cbb0692019-10-30 13:36:17 -0700117// Deprecated: "eol"
Jae Hoon Kim051627a2019-09-03 12:56:32 -0700118constexpr char kAttrEolDate[] = "eol_date";
Amin Hassani6600a562018-09-24 15:17:19 -0700119constexpr char kAttrRollback[] = "rollback";
120constexpr char kAttrFirmwareVersion[] = "firmware_version";
121constexpr char kAttrKernelVersion[] = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -0700122
David Zeuthene8ed8632014-07-24 13:38:10 -0400123// Struct used for holding data obtained when parsing the XML.
124struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400125 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
126
127 // Pointer to the expat XML_Parser object.
128 XML_Parser xml_parser;
129
David Zeuthene8ed8632014-07-24 13:38:10 -0400130 // This is the state of the parser as it's processing the XML.
131 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400132 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400133 string current_path;
134
135 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400136 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700137 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400138 string daystart_elapsed_days;
139 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800140
Sen Jiang81259682017-03-30 15:11:30 -0700141 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700142 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700143 vector<string> url_codebase;
144 string manifest_version;
145 map<string, string> action_postinstall_attrs;
146 string updatecheck_status;
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700147 Optional<string> cohort;
148 Optional<string> cohorthint;
149 Optional<string> cohortname;
Sen Jiang81259682017-03-30 15:11:30 -0700150
151 struct Package {
152 string name;
153 string size;
154 string hash;
Vyshu Khota4c5413d2020-11-04 16:17:25 -0800155 string fp;
Sen Jiang81259682017-03-30 15:11:30 -0700156 };
157 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800158 };
Sen Jiang81259682017-03-30 15:11:30 -0700159 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400160};
161
162namespace {
163
164// Callback function invoked by expat.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800165void ParserHandlerStart(void* user_data,
166 const XML_Char* element,
David Zeuthene8ed8632014-07-24 13:38:10 -0400167 const XML_Char** attr) {
168 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
169
170 if (data->failed)
171 return;
172
173 data->current_path += string("/") + element;
174
175 map<string, string> attrs;
176 if (attr != nullptr) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800177 for (int n = 0; attr[n] != nullptr && attr[n + 1] != nullptr; n += 2) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400178 string key = attr[n];
179 string value = attr[n + 1];
180 attrs[key] = value;
181 }
182 }
183
Alex Deymo8e18f932015-03-27 16:16:59 -0700184 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700185 OmahaParserData::App app;
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700186 if (attrs.find(kAttrAppId) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700187 app.id = attrs[kAttrAppId];
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700188 if (attrs.find(kAttrCohort) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700189 app.cohort = attrs[kAttrCohort];
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700190 if (attrs.find(kAttrCohortHint) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700191 app.cohorthint = attrs[kAttrCohortHint];
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700192 if (attrs.find(kAttrCohortName) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700193 app.cohortname = attrs[kAttrCohortName];
Sen Jiangb1e063a2017-09-15 17:44:31 -0700194 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700195 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700196 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700197 data->apps.back().updatecheck_status = attrs[kAttrStatus];
Sen Jiang81259682017-03-30 15:11:30 -0700198 if (data->updatecheck_poll_interval.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700199 data->updatecheck_poll_interval = attrs[kAttrPollInterval];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700200 // Omaha sends arbitrary key-value pairs as extra attributes starting with
201 // an underscore.
202 for (const auto& attr : attrs) {
203 if (!attr.first.empty() && attr.first[0] == '_')
204 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
205 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400206 } else if (data->current_path == "/response/daystart") {
207 // Get the install-date.
Amin Hassani6600a562018-09-24 15:17:19 -0700208 data->daystart_elapsed_days = attrs[kAttrElapsedDays];
209 data->daystart_elapsed_seconds = attrs[kAttrElapsedSeconds];
David Zeuthene8ed8632014-07-24 13:38:10 -0400210 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
211 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700212 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700213 data->apps.back().url_codebase.push_back(attrs[kAttrCodeBase]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800214 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400215 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800216 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700217 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700218 data->apps.back().packages.push_back({.name = attrs[kAttrName],
219 .size = attrs[kAttrSize],
Vyshu Khota4c5413d2020-11-04 16:17:25 -0800220 .hash = attrs[kAttrHashSha256],
221 .fp = attrs[kAttrFp]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400222 } else if (data->current_path == "/response/app/updatecheck/manifest") {
223 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700224 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700225 data->apps.back().manifest_version = attrs[kAttrVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400226 } else if (data->current_path ==
227 "/response/app/updatecheck/manifest/actions/action") {
228 // We only care about the postinstall action.
Amin Hassani6600a562018-09-24 15:17:19 -0700229 if (attrs[kAttrEvent] == kValPostInstall && !data->apps.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700230 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400231 }
232 }
233}
234
235// Callback function invoked by expat.
236void ParserHandlerEnd(void* user_data, const XML_Char* element) {
237 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
238 if (data->failed)
239 return;
240
241 const string path_suffix = string("/") + element;
242
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800243 if (!base::EndsWith(
244 data->current_path, path_suffix, base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400245 LOG(ERROR) << "Unexpected end element '" << element
246 << "' with current_path='" << data->current_path << "'";
247 data->failed = true;
248 return;
249 }
250 data->current_path.resize(data->current_path.size() - path_suffix.size());
251}
252
David Zeuthenf3e28012014-08-26 18:23:52 -0400253// Callback function invoked by expat.
254//
255// This is called for entity declarations. Since Omaha is guaranteed
256// to never return any XML with entities our course of action is to
257// just stop parsing. This avoids potential resource exhaustion
258// problems AKA the "billion laughs". CVE-2013-0340.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800259void ParserHandlerEntityDecl(void* user_data,
260 const XML_Char* entity_name,
David Zeuthenf3e28012014-08-26 18:23:52 -0400261 int is_parameter_entity,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800262 const XML_Char* value,
David Zeuthenf3e28012014-08-26 18:23:52 -0400263 int value_length,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800264 const XML_Char* base,
265 const XML_Char* system_id,
266 const XML_Char* public_id,
267 const XML_Char* notation_name) {
David Zeuthenf3e28012014-08-26 18:23:52 -0400268 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
269
270 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
271 data->failed = true;
272 data->entity_decl = true;
273 XML_StopParser(data->xml_parser, false);
274}
275
David Zeuthene8ed8632014-07-24 13:38:10 -0400276} // namespace
277
Alex Deymoc1c17b42015-11-23 03:53:15 -0300278OmahaRequestAction::OmahaRequestAction(
Alex Deymoc1c17b42015-11-23 03:53:15 -0300279 OmahaEvent* event,
280 std::unique_ptr<HttpFetcher> http_fetcher,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700281 bool ping_only,
282 const string& session_id)
Amin Hassani61789032020-11-13 16:20:12 -0800283 : event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300284 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800285 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700286 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700287 ping_active_days_(0),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700288 ping_roll_call_days_(0),
289 session_id_(session_id) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800290 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700291}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000292
Darin Petkov6a5b3222010-07-13 14:55:28 -0700293OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000294
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700295// Calculates the value to use for the ping days parameter.
296int OmahaRequestAction::CalculatePingDays(const string& key) {
Andrewe045aef2020-01-08 16:29:22 -0800297 int days = kPingNeverPinged;
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700298 int64_t last_ping = 0;
Amin Hassani538bd592020-11-04 20:46:08 -0800299 if (SystemState::Get()->prefs()->GetInt64(key, &last_ping) &&
300 last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700301 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
302 if (days < 0) {
303 // If |days| is negative, then the system clock must have jumped
304 // back in time since the ping was sent. Mark the value so that
305 // it doesn't get sent to the server but we still update the
306 // last ping daystart preference. This way the next ping time
307 // will be correct, hopefully.
308 days = kPingTimeJump;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800309 LOG(WARNING)
310 << "System clock jumped back in time. Resetting ping daystarts.";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700311 }
312 }
313 return days;
314}
315
316void OmahaRequestAction::InitPingDays() {
317 // We send pings only along with update checks, not with events.
318 if (IsEvent()) {
319 return;
320 }
321 // TODO(petkov): Figure a way to distinguish active use pings
322 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700323 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700324 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
325 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
326}
327
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700328bool OmahaRequestAction::ShouldPing() const {
Andrewe045aef2020-01-08 16:29:22 -0800329 if (ping_active_days_ == kPingNeverPinged &&
330 ping_roll_call_days_ == kPingNeverPinged) {
Amin Hassani538bd592020-11-04 20:46:08 -0800331 int powerwash_count = SystemState::Get()->hardware()->GetPowerwashCount();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700332 if (powerwash_count > 0) {
333 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
334 << "powerwash_count is " << powerwash_count;
335 return false;
336 }
Amin Hassani538bd592020-11-04 20:46:08 -0800337 if (SystemState::Get()->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani1677e812017-06-21 13:36:36 -0700338 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
Amin Hassanida35b872020-11-04 17:54:44 -0800339 << "the first_active_omaha_ping_sent is true.";
Amin Hassani1677e812017-06-21 13:36:36 -0700340 return false;
341 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700342 return true;
343 }
344 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
345}
346
David Zeuthen639aa362014-02-03 16:23:44 -0800347// static
Amin Hassani538bd592020-11-04 20:46:08 -0800348int OmahaRequestAction::GetInstallDate() {
Amin Hassani90e9f192020-11-18 14:20:56 -0800349 auto* prefs = SystemState::Get()->prefs();
David Zeuthen639aa362014-02-03 16:23:44 -0800350 // If we have the value stored on disk, just return it.
351 int64_t stored_value;
352 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
Kelvin Zhangebd5e252020-07-22 18:27:06 -0400353 // Convert and validity-check.
David Zeuthen639aa362014-02-03 16:23:44 -0800354 int install_date_days = static_cast<int>(stored_value);
355 if (install_date_days >= 0)
356 return install_date_days;
357 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
358 << install_date_days << " looks suspicious.";
359 prefs->Delete(kPrefsInstallDateDays);
360 }
361
362 // Otherwise, if OOBE is not complete then do nothing and wait for
363 // ParseResponse() to call ParseInstallDate() and then
364 // PersistInstallDate() to set the kPrefsInstallDateDays state
365 // variable. Once that is done, we'll then report back in future
366 // Omaha requests. This works exactly because OOBE triggers an
367 // update check.
368 //
369 // However, if OOBE is complete and the kPrefsInstallDateDays state
370 // variable is not set, there are two possibilities
371 //
372 // 1. The update check in OOBE failed so we never got a response
373 // from Omaha (no network etc.); or
374 //
375 // 2. OOBE was done on an older version that didn't write to the
376 // kPrefsInstallDateDays state variable.
377 //
378 // In both cases, we approximate the install date by simply
379 // inspecting the timestamp of when OOBE happened.
380
381 Time time_of_oobe;
Amin Hassani538bd592020-11-04 20:46:08 -0800382 if (!SystemState::Get()->hardware()->IsOOBEEnabled() ||
383 !SystemState::Get()->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800384 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700385 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800386 return -1;
387 }
388
389 int num_days;
390 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
391 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
392 << "as its value '" << utils::ToString(time_of_oobe)
393 << "' looks suspicious.";
394 return -1;
395 }
396
397 // Persist this to disk, for future use.
Amin Hassani538bd592020-11-04 20:46:08 -0800398 if (!OmahaRequestAction::PersistInstallDate(num_days,
399 kProvisionedFromOOBEMarker))
David Zeuthen639aa362014-02-03 16:23:44 -0800400 return -1;
401
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800402 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to " << num_days
Amin Hassanida35b872020-11-04 17:54:44 -0800403 << " days.";
David Zeuthen639aa362014-02-03 16:23:44 -0800404
405 return num_days;
406}
407
Andrewe045aef2020-01-08 16:29:22 -0800408void OmahaRequestAction::StorePingReply(
409 const OmahaParserData& parser_data) const {
Amin Hassani61789032020-11-13 16:20:12 -0800410 const auto* params = SystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -0800411 for (const auto& app : parser_data.apps) {
Amin Hassani61789032020-11-13 16:20:12 -0800412 auto it = params->dlc_apps_params().find(app.id);
413 if (it == params->dlc_apps_params().end())
Andrewe045aef2020-01-08 16:29:22 -0800414 continue;
415
416 const OmahaRequestParams::AppParams& dlc_params = it->second;
Andrew065d78d2020-04-07 15:43:07 -0700417 const string& dlc_id = dlc_params.name;
Andrewe045aef2020-01-08 16:29:22 -0800418 // Skip if the ping for this DLC was not sent.
419 if (!dlc_params.send_ping)
420 continue;
421
Amin Hassani90e9f192020-11-18 14:20:56 -0800422 auto* prefs = SystemState::Get()->prefs();
Andrewe045aef2020-01-08 16:29:22 -0800423 // Reset the active metadata value to |kPingInactiveValue|.
Andrew065d78d2020-04-07 15:43:07 -0700424 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -0700425 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -0700426 if (!prefs->SetInt64(active_key, kPingInactiveValue))
427 LOG(ERROR) << "Failed to set the value of ping metadata '" << active_key
428 << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800429
Andrew065d78d2020-04-07 15:43:07 -0700430 auto last_rollcall_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -0700431 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -0700432 if (!prefs->SetString(last_rollcall_key, parser_data.daystart_elapsed_days))
Andrewe045aef2020-01-08 16:29:22 -0800433 LOG(ERROR) << "Failed to set the value of ping metadata '"
Andrew065d78d2020-04-07 15:43:07 -0700434 << last_rollcall_key << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800435
436 if (dlc_params.ping_active) {
437 // Write the value of elapsed_days into |kPrefsPingLastActive| only if
438 // the previous ping was an active one.
Andrew065d78d2020-04-07 15:43:07 -0700439 auto last_active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -0700440 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -0700441 if (!prefs->SetString(last_active_key, parser_data.daystart_elapsed_days))
Andrewe045aef2020-01-08 16:29:22 -0800442 LOG(ERROR) << "Failed to set the value of ping metadata '"
Andrew065d78d2020-04-07 15:43:07 -0700443 << last_active_key << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800444 }
445 }
446}
447
Darin Petkov6a5b3222010-07-13 14:55:28 -0700448void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000449 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700450 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700451 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700452 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700453 return;
454 }
David Zeuthen639aa362014-02-03 16:23:44 -0800455
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700456 OmahaRequestBuilderXml omaha_request(event_.get(),
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700457 ping_only_,
458 ShouldPing(), // include_ping
459 ping_active_days_,
460 ping_roll_call_days_,
Amin Hassani538bd592020-11-04 20:46:08 -0800461 GetInstallDate(),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700462 session_id_);
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700463 string request_post = omaha_request.GetRequest();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700464
Sen Jiang42fa45e2018-03-12 11:02:14 -0700465 // Set X-Goog-Update headers.
Amin Hassani9ed2cee2020-11-13 18:40:35 -0800466 const auto* params = SystemState::Get()->request_params();
Alex Deymo14ad88e2016-06-29 12:30:14 -0700467 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
Amin Hassani61789032020-11-13 16:20:12 -0800468 params->interactive() ? "fg" : "bg");
469 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params->GetAppId());
Alex Deymo14ad88e2016-06-29 12:30:14 -0700470 http_fetcher_->SetHeader(
471 kXGoogleUpdateUpdater,
472 base::StringPrintf(
473 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
474
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800475 http_fetcher_->SetPostData(
476 request_post.data(), request_post.size(), kHttpContentTypeTextXml);
Amin Hassani61789032020-11-13 16:20:12 -0800477 LOG(INFO) << "Posting an Omaha request to " << params->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700478 LOG(INFO) << "Request: " << request_post;
Amin Hassani61789032020-11-13 16:20:12 -0800479 http_fetcher_->BeginTransfer(params->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000480}
481
Darin Petkov6a5b3222010-07-13 14:55:28 -0700482void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000483 http_fetcher_->TerminateTransfer();
484}
485
486// We just store the response in the buffer. Once we've received all bytes,
487// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700488bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800489 const void* bytes,
490 size_t length) {
491 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
492 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700493 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000494}
495
496namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000497
498// Parses a 64 bit base-10 int from a string and returns it. Returns 0
499// on error. If the string contains "0", that's indistinguishable from
500// error.
501off_t ParseInt(const string& str) {
502 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700503 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000504 if (rc < 1) {
505 // failure
506 return 0;
507 }
508 return ret;
509}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700510
David Zeuthene8ed8632014-07-24 13:38:10 -0400511// Parses |str| and returns |true| if, and only if, its value is "true".
512bool ParseBool(const string& str) {
513 return str == "true";
514}
515
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700516// Update the last ping day preferences based on the server daystart
517// response. Returns true on success, false otherwise.
Amin Hassani90e9f192020-11-18 14:20:56 -0800518bool UpdateLastPingDays(OmahaParserData* parser_data) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700519 int64_t elapsed_seconds = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800520 TEST_AND_RETURN_FALSE(base::StringToInt64(
521 parser_data->daystart_elapsed_seconds, &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700522 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
523
524 // Remember the local time that matches the server's last midnight
525 // time.
Amin Hassani90e9f192020-11-18 14:20:56 -0800526 auto* prefs = SystemState::Get()->prefs();
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700527 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
528 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
529 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
530 return true;
531}
Sen Jiang81259682017-03-30 15:11:30 -0700532
533// Parses the package node in the given XML document and populates
534// |output_object| if valid. Returns true if we should continue the parsing.
535// False otherwise, in which case it sets any error code using |completer|.
536bool ParsePackage(OmahaParserData::App* app,
537 OmahaResponse* output_object,
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700538 bool can_exclude,
Sen Jiang81259682017-03-30 15:11:30 -0700539 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700540 if (app->updatecheck_status.empty() ||
541 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700542 if (!app->packages.empty()) {
543 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
544 completer->set_code(ErrorCode::kOmahaResponseInvalid);
545 return false;
546 }
547 return true;
548 }
549 if (app->packages.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800550 LOG(ERROR) << "Omaha Response has no packages.";
Sen Jiang81259682017-03-30 15:11:30 -0700551 completer->set_code(ErrorCode::kOmahaResponseInvalid);
552 return false;
553 }
554 if (app->url_codebase.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800555 LOG(ERROR) << "No Omaha Response URLs.";
Sen Jiang81259682017-03-30 15:11:30 -0700556 completer->set_code(ErrorCode::kOmahaResponseInvalid);
557 return false;
558 }
Sen Jiang81259682017-03-30 15:11:30 -0700559 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700560 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700561 ":",
562 base::TRIM_WHITESPACE,
563 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700564 vector<string> metadata_signatures = base::SplitString(
565 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
566 ":",
567 base::TRIM_WHITESPACE,
568 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700569 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700570 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700571 ":",
572 base::TRIM_WHITESPACE,
573 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700574 for (size_t i = 0; i < app->packages.size(); i++) {
575 const auto& package = app->packages[i];
576 if (package.name.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800577 LOG(ERROR) << "Omaha Response has empty package name.";
Sen Jiang81259682017-03-30 15:11:30 -0700578 completer->set_code(ErrorCode::kOmahaResponseInvalid);
579 return false;
580 }
Sen Jiang81259682017-03-30 15:11:30 -0700581
582 OmahaResponse::Package out_package;
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700583 out_package.app_id = app->id;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700584 out_package.can_exclude = can_exclude;
Sen Jiang81259682017-03-30 15:11:30 -0700585 for (const string& codebase : app->url_codebase) {
586 if (codebase.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800587 LOG(ERROR) << "Omaha Response URL has empty codebase.";
Sen Jiang81259682017-03-30 15:11:30 -0700588 completer->set_code(ErrorCode::kOmahaResponseInvalid);
589 return false;
590 }
591 out_package.payload_urls.push_back(codebase + package.name);
592 }
Amin Hassanida35b872020-11-04 17:54:44 -0800593
Sen Jiang81259682017-03-30 15:11:30 -0700594 // Parse the payload size.
595 base::StringToUint64(package.size, &out_package.size);
596 if (out_package.size <= 0) {
597 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
598 completer->set_code(ErrorCode::kOmahaResponseInvalid);
599 return false;
600 }
Sen Jiang81259682017-03-30 15:11:30 -0700601
602 if (i < metadata_sizes.size())
603 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
Sen Jiang81259682017-03-30 15:11:30 -0700604
605 if (i < metadata_signatures.size())
606 out_package.metadata_signature = metadata_signatures[i];
Sen Jiang81259682017-03-30 15:11:30 -0700607
608 out_package.hash = package.hash;
609 if (out_package.hash.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800610 LOG(ERROR) << "Omaha Response has empty hash_sha256 value.";
Sen Jiang81259682017-03-30 15:11:30 -0700611 completer->set_code(ErrorCode::kOmahaResponseInvalid);
612 return false;
613 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700614
Vyshu Khota4c5413d2020-11-04 16:17:25 -0800615 out_package.fp = package.fp;
616
Sen Jiangcdd52062017-05-18 15:33:10 -0700617 if (i < is_delta_payloads.size())
618 out_package.is_delta = ParseBool(is_delta_payloads[i]);
Sen Jiangcdd52062017-05-18 15:33:10 -0700619
Sen Jiang81259682017-03-30 15:11:30 -0700620 output_object->packages.push_back(std::move(out_package));
621 }
622
623 return true;
624}
625
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700626// Removes the candidate URLs which are excluded within packages, if all the
627// candidate URLs are excluded within a package, the package will be excluded.
628void ProcessExclusions(OmahaResponse* output_object,
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700629 OmahaRequestParams* params,
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700630 ExcluderInterface* excluder) {
631 for (auto package_it = output_object->packages.begin();
632 package_it != output_object->packages.end();
633 /* Increment logic in loop */) {
634 // If package cannot be excluded, quickly continue.
635 if (!package_it->can_exclude) {
636 ++package_it;
637 continue;
638 }
639 // Remove the excluded payload URLs.
640 for (auto payload_url_it = package_it->payload_urls.begin();
641 payload_url_it != package_it->payload_urls.end();
642 /* Increment logic in loop */) {
643 auto exclusion_name = utils::GetExclusionName(*payload_url_it);
644 // If payload URL is not excluded, quickly continue.
645 if (!excluder->IsExcluded(exclusion_name)) {
646 ++payload_url_it;
647 continue;
648 }
649 LOG(INFO) << "Excluding payload URL=" << *payload_url_it
650 << " for payload hash=" << package_it->hash;
651 payload_url_it = package_it->payload_urls.erase(payload_url_it);
652 }
653 // If there are no candidate payload URLs, remove the package.
654 if (package_it->payload_urls.empty()) {
655 LOG(INFO) << "Excluding payload hash=" << package_it->hash;
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700656 // Need to set DLC as not updated so correct metrics can be sent when an
657 // update is completed.
658 params->SetDlcNoUpdate(package_it->app_id);
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700659 package_it = output_object->packages.erase(package_it);
660 continue;
661 }
662 ++package_it;
663 }
664}
665
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700666// Parses the 2 key version strings kernel_version and firmware_version. If the
667// field is not present, or cannot be parsed the values default to 0xffff.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700668void ParseRollbackVersions(int allowed_milestones,
669 OmahaParserData* parser_data,
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700670 OmahaResponse* output_object) {
671 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700672 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700673 &output_object->rollback_key_version.firmware_key,
674 &output_object->rollback_key_version.firmware);
675 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700676 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700677 &output_object->rollback_key_version.kernel_key,
678 &output_object->rollback_key_version.kernel);
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700679
680 // Create the attribute name strings for milestone N - allowed_milestones.
681 const string firmware_max_rollforward_attr =
682 base::StringPrintf("%s_%i", kAttrFirmwareVersion, allowed_milestones);
683 const string kernel_max_rollforward_attr =
684 base::StringPrintf("%s_%i", kAttrKernelVersion, allowed_milestones);
685
686 const bool max_firmware_and_kernel_exist =
687 parser_data->updatecheck_attrs.count(firmware_max_rollforward_attr) > 0 &&
688 parser_data->updatecheck_attrs.count(kernel_max_rollforward_attr) > 0;
689
690 string firmware_version;
691 string kernel_version;
692 if (max_firmware_and_kernel_exist) {
693 firmware_version =
694 parser_data->updatecheck_attrs[firmware_max_rollforward_attr];
695 kernel_version =
696 parser_data->updatecheck_attrs[kernel_max_rollforward_attr];
697 }
698
699 LOG(INFO) << "For milestone N-" << allowed_milestones
700 << " firmware_key_version=" << firmware_version
701 << " kernel_key_version=" << kernel_version;
702
703 OmahaResponse::RollbackKeyVersion version;
704 utils::ParseRollbackKeyVersion(
705 firmware_version, &version.firmware_key, &version.firmware);
706 utils::ParseRollbackKeyVersion(
707 kernel_version, &version.kernel_key, &version.kernel);
708
709 output_object->past_rollback_key_version = std::move(version);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700710}
711
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700712} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000713
David Zeuthene8ed8632014-07-24 13:38:10 -0400714bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700715 OmahaResponse* output_object,
716 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700717 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700718 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700719 return false;
720 }
721
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800722 // chromium-os:37289: The PollInterval is not supported by Omaha server
723 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700724 // slow down the request rate from the server-side. Note that the PollInterval
725 // is not persisted, so it has to be sent by the server on every response to
726 // guarantee that the scheduler uses this value (otherwise, if the device got
727 // rebooted after the last server-indicated value, it'll revert to the default
728 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
729 // based on the assumption that we perform an update check every hour so that
730 // the max value of 8 will roughly be equivalent to one work day. If we decide
731 // to use PollInterval permanently, we should update the
732 // max_update_checks_allowed to take PollInterval into account. Note: The
733 // parsing for PollInterval happens even before parsing of the status because
734 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400735 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700736 &output_object->poll_interval);
737
David Zeuthen639aa362014-02-03 16:23:44 -0800738 // Check for the "elapsed_days" attribute in the "daystart"
739 // element. This is the number of days since Jan 1 2007, 0:00
740 // PST. If we don't have a persisted value of the Omaha InstallDate,
741 // we'll use it to calculate it and then persist it.
Amin Hassani538bd592020-11-04 20:46:08 -0800742 if (ParseInstallDate(parser_data, output_object) && !HasInstallDate()) {
David Zeuthen639aa362014-02-03 16:23:44 -0800743 // Since output_object->install_date_days is never negative, the
744 // elapsed_days -> install-date calculation is reduced to simply
745 // rounding down to the nearest number divisible by 7.
746 int remainder = output_object->install_date_days % 7;
747 int install_date_days_rounded =
748 output_object->install_date_days - remainder;
Amin Hassani538bd592020-11-04 20:46:08 -0800749 if (PersistInstallDate(install_date_days_rounded,
David Zeuthen639aa362014-02-03 16:23:44 -0800750 kProvisionedFromOmahaResponse)) {
751 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
Amin Hassanida35b872020-11-04 17:54:44 -0800752 << install_date_days_rounded << " days.";
David Zeuthen639aa362014-02-03 16:23:44 -0800753 }
754 }
755
Alex Deymo00d79ac2015-06-29 15:41:49 -0700756 // We persist the cohorts sent by omaha even if the status is "noupdate".
Jae Hoon Kime2cac612020-11-02 18:30:29 -0800757 PersistCohorts(*parser_data);
Alex Deymo00d79ac2015-06-29 15:41:49 -0700758
Amin Hassani2cbb0692019-10-30 13:36:17 -0700759 PersistEolInfo(parser_data->updatecheck_attrs);
760
Marton Hunyady199152d2018-05-07 19:08:48 +0200761 // Rollback-related updatecheck attributes.
762 // Defaults to false if attribute is not present.
763 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -0700764 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700765
Amin Hassani61789032020-11-13 16:20:12 -0800766 const auto* params = SystemState::Get()->request_params();
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700767 // Parses the rollback versions of the current image. If the fields do not
768 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700769 ParseRollbackVersions(
Amin Hassani61789032020-11-13 16:20:12 -0800770 params->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -0700771
David Zeuthene8ed8632014-07-24 13:38:10 -0400772 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700773 return false;
774
David Zeuthene8ed8632014-07-24 13:38:10 -0400775 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700776 return false;
777
Sen Jiang0affc2c2017-02-10 15:55:05 -0800778 // Package has to be parsed after Params now because ParseParams need to make
779 // sure that postinstall action exists.
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700780 for (auto& app : parser_data->apps) {
781 // Only allow exclusions for a non-critical package during an update. For
782 // non-critical package installations, let the errors propagate instead
783 // of being handled inside update_engine as installations are a dlcservice
784 // specific feature.
Amin Hassani61789032020-11-13 16:20:12 -0800785 bool can_exclude = !params->is_install() && params->IsDlcAppId(app.id);
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700786 if (!ParsePackage(&app, output_object, can_exclude, completer))
Sen Jiang81259682017-03-30 15:11:30 -0700787 return false;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700788 }
Sen Jiang0affc2c2017-02-10 15:55:05 -0800789
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700790 return true;
791}
792
David Zeuthene8ed8632014-07-24 13:38:10 -0400793bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700794 OmahaResponse* output_object,
795 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700796 output_object->update_exists = false;
Amin Hassani61789032020-11-13 16:20:12 -0800797 auto* params = SystemState::Get()->request_params();
Xiaochu Liu6310be62018-10-11 15:09:03 -0700798 for (const auto& app : parser_data->apps) {
799 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -0700800 if (status == kValNoUpdate) {
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800801 // If the app is a DLC, allow status "noupdate" to support DLC
802 // deprecations.
Amin Hassani61789032020-11-13 16:20:12 -0800803 if (params->IsDlcAppId(app.id)) {
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800804 LOG(INFO) << "No update for <app> " << app.id
805 << " but update continuing since a DLC.";
Amin Hassani61789032020-11-13 16:20:12 -0800806 params->SetDlcNoUpdate(app.id);
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800807 continue;
808 }
Sen Jiang00adf7b2017-06-26 15:57:29 -0700809 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -0700810 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700811 output_object->update_exists = false;
812 break;
Sen Jiang81259682017-03-30 15:11:30 -0700813 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700814 auto const& attr_no_update =
815 app.action_postinstall_attrs.find(kAttrNoUpdate);
816 if (attr_no_update != app.action_postinstall_attrs.end() &&
817 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700818 // noupdate="true" in postinstall attributes means it's an update to
819 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -0700820 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700821 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700822 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700823 output_object->update_exists = true;
824 }
Amin Hassani61789032020-11-13 16:20:12 -0800825 } else if (status.empty() && params->is_install() &&
826 params->GetAppId() == app.id) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700827 // Skips the platform app for install operation.
828 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -0700829 } else {
830 LOG(ERROR) << "Unknown Omaha response status: " << status;
831 completer->set_code(ErrorCode::kOmahaResponseInvalid);
832 return false;
833 }
834 }
835 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700836 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700837 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700838 }
839
Sen Jiang81259682017-03-30 15:11:30 -0700840 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700841}
842
David Zeuthene8ed8632014-07-24 13:38:10 -0400843bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700844 OmahaResponse* output_object,
845 ScopedActionCompleter* completer) {
Amin Hassani61789032020-11-13 16:20:12 -0800846 const auto* params = SystemState::Get()->request_params();
Sen Jiang81259682017-03-30 15:11:30 -0700847 map<string, string> attrs;
848 for (auto& app : parser_data->apps) {
Amin Hassani61789032020-11-13 16:20:12 -0800849 if (app.id == params->GetAppId()) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700850 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -0700851 output_object->version = app.manifest_version;
Amin Hassani61789032020-11-13 16:20:12 -0800852 } else if (params->is_install() &&
853 app.manifest_version != params->app_version()) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700854 LOG(WARNING) << "An app has a different version (" << app.manifest_version
855 << ") that is different than platform app version ("
Amin Hassani61789032020-11-13 16:20:12 -0800856 << params->app_version() << ").";
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700857 }
858 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700859 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700860 }
Sen Jiang81259682017-03-30 15:11:30 -0700861 }
Amin Hassani61789032020-11-13 16:20:12 -0800862 if (params->is_install()) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700863 LOG(INFO) << "Use request version for Install operation.";
Amin Hassani61789032020-11-13 16:20:12 -0800864 output_object->version = params->app_version();
Xiaochu Liu6310be62018-10-11 15:09:03 -0700865 }
Chris Sosa3b748432013-06-20 16:42:59 -0700866 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700867 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700868 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700869 return false;
870 }
871
David Zeuthene8ed8632014-07-24 13:38:10 -0400872 if (attrs.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800873 LOG(ERROR) << "Omaha Response has no postinstall event action.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700874 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700875 return false;
876 }
877
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800878 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -0700879 output_object->more_info_url = attrs[kAttrMoreInfo];
880 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
881 output_object->deadline = attrs[kAttrDeadline];
882 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700883 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -0700884 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700885 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -0700886 ParseBool(attrs[kAttrDisableP2PForSharing]);
887 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800888
Amin Hassani6600a562018-09-24 15:17:19 -0700889 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800890 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800891 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700892
Jay Srinivasan08262882012-12-28 19:29:43 -0800893 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -0700894 ParseBool(attrs[kAttrDisablePayloadBackoff]);
895 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800896
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700897 return true;
898}
899
David Zeuthene8ed8632014-07-24 13:38:10 -0400900// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000901// and fill in the appropriate fields of the output object. Also, notifies
902// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800903void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -0700904 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000905 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800906 string current_response(response_buffer_.begin(), response_buffer_.end());
907 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700908
Amin Hassani538bd592020-11-04 20:46:08 -0800909 PayloadStateInterface* const payload_state =
910 SystemState::Get()->payload_state();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700911
Zentaro Kavanagh76af2662018-05-15 10:54:53 -0700912 // Set the max kernel key version based on whether rollback is allowed.
913 SetMaxKernelKeyVersionForRollback();
914
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700915 // Events are best effort transactions -- assume they always succeed.
916 if (IsEvent()) {
917 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700918 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700919 return;
920 }
921
Amin Hassanid3d84212019-08-17 00:27:44 -0700922 ErrorCode aux_error_code = fetcher->GetAuxiliaryErrorCode();
923 if (aux_error_code != ErrorCode::kSuccess) {
924 metrics::DownloadErrorCode download_error_code =
925 metrics_utils::GetDownloadErrorCode(aux_error_code);
Amin Hassani538bd592020-11-04 20:46:08 -0800926 SystemState::Get()->metrics_reporter()->ReportUpdateCheckMetrics(
Amin Hassanid3d84212019-08-17 00:27:44 -0700927 metrics::CheckResult::kUnset,
928 metrics::CheckReaction::kUnset,
929 download_error_code);
930 }
931
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700932 if (!successful) {
Darin Petkovedc522e2010-11-05 09:35:17 -0700933 int code = GetHTTPResponseCode();
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700934 LOG(ERROR) << "Omaha request network transfer failed with HTTPResponseCode="
935 << code;
Saint Chou6431c332020-07-29 14:04:14 +0000936 // Makes sure we send proper error values.
Darin Petkovedc522e2010-11-05 09:35:17 -0700937 if (code < 0 || code >= 1000) {
938 code = 999;
Saint Chou6431c332020-07-29 14:04:14 +0000939 LOG(WARNING) << "Converting to proper HTTPResponseCode=" << code;
Darin Petkovedc522e2010-11-05 09:35:17 -0700940 }
David Zeuthena99981f2013-04-29 13:42:47 -0700941 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700942 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000943 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700944 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000945
David Zeuthene8ed8632014-07-24 13:38:10 -0400946 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400947 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400948 XML_SetUserData(parser, &parser_data);
949 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400950 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800951 XML_Status res =
952 XML_Parse(parser,
953 reinterpret_cast<const char*>(response_buffer_.data()),
954 response_buffer_.size(),
955 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400956
957 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700958 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800959 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
960 << XML_GetCurrentLineNumber(parser) << " col "
961 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -0700962 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400963 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
964 if (response_buffer_.empty()) {
965 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
966 } else if (parser_data.entity_decl) {
967 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
968 }
969 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000970 return;
971 }
Amin Hassani91f48b42018-08-06 17:47:14 -0700972 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000973
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700974 // Update the last ping day preferences based on the server daystart response
975 // even if we didn't send a ping. Omaha always includes the daystart in the
976 // response, but log the error if it didn't.
Amin Hassani90e9f192020-11-18 14:20:56 -0800977 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data))
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700978 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700979
Amin Hassani1677e812017-06-21 13:36:36 -0700980 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
981 // we have got a response from omaha and if its value has never been set to
982 // true before. Failure of this function should be ignored. There should be no
983 // need to check if a=-1 has been sent because older devices have already sent
984 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
985 // future checks.
Amin Hassani538bd592020-11-04 20:46:08 -0800986 if (!SystemState::Get()->hardware()->GetFirstActiveOmahaPingSent()) {
987 if (!SystemState::Get()->hardware()->SetFirstActiveOmahaPingSent()) {
988 SystemState::Get()->metrics_reporter()->ReportInternalErrorCode(
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700989 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
990 }
Amin Hassani1677e812017-06-21 13:36:36 -0700991 }
992
Andrewe045aef2020-01-08 16:29:22 -0800993 // Create/update the metadata files for each DLC app received.
994 StorePingReply(parser_data);
995
Thieu Le116fda32011-04-19 11:01:54 -0700996 if (!HasOutputPipe()) {
997 // Just set success to whether or not the http transfer succeeded,
998 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700999 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001000 return;
1001 }
1002
Darin Petkov6a5b3222010-07-13 14:55:28 -07001003 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001004 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001005 return;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001006 ProcessExclusions(&output_object,
Amin Hassani538bd592020-11-04 20:46:08 -08001007 SystemState::Get()->request_params(),
1008 SystemState::Get()->update_attempter()->GetExcluder());
David Zeuthen8f191b22013-08-06 12:27:50 -07001009 output_object.update_exists = true;
1010 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001011
Toni Barzic61544e62018-10-11 14:37:30 -07001012 LoadOrPersistUpdateFirstSeenAtPref();
1013
Weidong Guo421ff332017-04-17 10:08:38 -07001014 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -07001015 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -07001016 // No need to change output_object.update_exists here, since the value
1017 // has been output to the pipe.
1018 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001019 return;
1020 }
1021
David Zeuthen8f191b22013-08-06 12:27:50 -07001022 // If Omaha says to disable p2p, respect that
1023 if (output_object.disable_p2p_for_downloading) {
1024 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1025 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001026 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001027 }
1028 if (output_object.disable_p2p_for_sharing) {
1029 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1030 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001031 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001032 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001033
1034 // Update the payload state with the current response. The payload state
1035 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001036 // from what's stored already. We are updating the payload state as late
1037 // as possible in this method so that if a new release gets pushed and then
1038 // got pulled back due to some issues, we don't want to clear our internal
1039 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001040 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001041
David Zeuthen8f191b22013-08-06 12:27:50 -07001042 // It could be we've already exceeded the deadline for when p2p is
1043 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001044 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001045 payload_state->P2PNewAttempt();
1046 if (!payload_state->P2PAttemptAllowed()) {
1047 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1048 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001049 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001050 }
1051 }
1052
1053 // From here on, we'll complete stuff in CompleteProcessing() so
1054 // disable |completer| since we'll create a new one in that
1055 // function.
1056 completer.set_should_complete(false);
1057
1058 // If we're allowed to use p2p for downloading we do not pay
1059 // attention to wall-clock-based waiting if the URL is indeed
1060 // available via p2p. Therefore, check if the file is available via
1061 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001062 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001063 LookupPayloadViaP2P(output_object);
1064 } else {
1065 CompleteProcessing();
1066 }
1067}
1068
1069void OmahaRequestAction::CompleteProcessing() {
1070 ScopedActionCompleter completer(processor_, this);
1071 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
Amin Hassani538bd592020-11-04 20:46:08 -08001072 PayloadStateInterface* payload_state = SystemState::Get()->payload_state();
David Zeuthen8f191b22013-08-06 12:27:50 -07001073
1074 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001075 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001076 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001077 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001078 return;
1079 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001080
Chris Sosa20f005c2013-09-05 13:53:08 -07001081 if (payload_state->ShouldBackoffDownload()) {
1082 output_object.update_exists = false;
1083 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
Amin Hassanida35b872020-11-04 17:54:44 -08001084 << "attempts.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001085 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001086 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001087 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001088 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001089}
1090
1091void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1092 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1093 if (!url.empty()) {
Amin Hassani538bd592020-11-04 20:46:08 -08001094 SystemState::Get()->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001095 } else {
1096 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1097 << "because no suitable peer could be found.";
Amin Hassani538bd592020-11-04 20:46:08 -08001098 SystemState::Get()->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001099 }
1100 CompleteProcessing();
1101}
1102
1103void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001104 // If the device is in the middle of an update, the state variables
1105 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1106 // tracks the offset and length of the operation currently in
1107 // progress. The offset is based from the end of the manifest which
1108 // is kPrefsManifestMetadataSize bytes long.
1109 //
1110 // To make forward progress and avoid deadlocks, we need to find a
1111 // peer that has at least the entire operation we're currently
1112 // working on. Otherwise we may end up in a situation where two
1113 // devices bounce back and forth downloading from each other,
1114 // neither making any forward progress until one of them decides to
1115 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1116 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001117 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001118 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001119 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001120 int64_t next_data_offset = 0;
1121 int64_t next_data_length = 0;
Amin Hassani538bd592020-11-04 20:46:08 -08001122 if (SystemState::Get()->prefs()->GetInt64(kPrefsManifestMetadataSize,
1123 &manifest_metadata_size) &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001124 manifest_metadata_size != -1 &&
Amin Hassani538bd592020-11-04 20:46:08 -08001125 SystemState::Get()->prefs()->GetInt64(kPrefsManifestSignatureSize,
1126 &manifest_signature_size) &&
Alex Deymof25eb492016-02-26 00:20:08 -08001127 manifest_signature_size != -1 &&
Amin Hassani538bd592020-11-04 20:46:08 -08001128 SystemState::Get()->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
1129 &next_data_offset) &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001130 next_data_offset != -1 &&
Amin Hassani538bd592020-11-04 20:46:08 -08001131 SystemState::Get()->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1132 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001133 minimum_size = manifest_metadata_size + manifest_signature_size +
1134 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001135 }
1136
Sen Jiang0affc2c2017-02-10 15:55:05 -08001137 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001138 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001139 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001140 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001141 string file_id =
1142 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Amin Hassani538bd592020-11-04 20:46:08 -08001143 if (SystemState::Get()->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001144 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1145 << " minimum_size=" << minimum_size;
Amin Hassani538bd592020-11-04 20:46:08 -08001146 SystemState::Get()->p2p_manager()->LookupUrlForFile(
David Zeuthen8f191b22013-08-06 12:27:50 -07001147 file_id,
1148 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001149 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001150 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1151 base::Unretained(this)));
1152 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001153}
1154
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001155bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Amin Hassani61789032020-11-13 16:20:12 -08001156 const auto* params = SystemState::Get()->request_params();
1157 if (params->interactive()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001158 LOG(INFO) << "Not deferring download because update is interactive.";
1159 return false;
1160 }
1161
David Zeuthen8f191b22013-08-06 12:27:50 -07001162 // If we're using p2p to download _and_ we have a p2p URL, we never
1163 // defer the download. This is because the download will always
1164 // happen from a peer on the LAN and we've been waiting in line for
1165 // our turn.
Amin Hassani538bd592020-11-04 20:46:08 -08001166 const PayloadStateInterface* payload_state =
1167 SystemState::Get()->payload_state();
Gilad Arnold74b5f552014-10-07 08:17:16 -07001168 if (payload_state->GetUsingP2PForDownloading() &&
1169 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001170 LOG(INFO) << "Download not deferred because download "
1171 << "will happen from a local peer (via p2p).";
1172 return false;
1173 }
1174
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001175 // We should defer the downloads only if we've first satisfied the
1176 // wall-clock-based-waiting period and then the update-check-based waiting
1177 // period, if required.
Amin Hassani61789032020-11-13 16:20:12 -08001178 if (!params->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001179 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1180 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001181 return false;
1182 }
1183
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001184 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001185 case kWallClockWaitNotSatisfied:
1186 // We haven't even satisfied the first condition, passing the
1187 // wall-clock-based waiting period, so we should defer the downloads
1188 // until that happens.
1189 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1190 return true;
1191
1192 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1193 LOG(INFO) << "wall-clock-based-wait satisfied and "
1194 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001195 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001196
1197 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1198 // Wall-clock-based waiting period is satisfied, and it's determined
1199 // that we do not need the update-check-based wait. so no need to
1200 // defer downloads.
1201 LOG(INFO) << "wall-clock-based-wait satisfied and "
1202 << "update-check-based-wait is not required.";
1203 return false;
1204
1205 default:
1206 // Returning false for this default case so we err on the
1207 // side of downloading updates than deferring in case of any bugs.
1208 NOTREACHED();
1209 return false;
1210 }
1211}
1212
1213OmahaRequestAction::WallClockWaitResult
1214OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001215 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001216 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1217 if (update_first_seen_at == base::Time()) {
1218 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
Amin Hassanida35b872020-11-04 17:54:44 -08001219 "persisted.";
May Lippert60aa3ca2018-08-15 16:55:29 -07001220 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001221 }
1222
Sen Jiang7c1171e2016-06-23 11:35:40 -07001223 TimeDelta elapsed_time =
Amin Hassani538bd592020-11-04 20:46:08 -08001224 SystemState::Get()->clock()->GetWallclockTime() - update_first_seen_at;
Sen Jiang7c1171e2016-06-23 11:35:40 -07001225 TimeDelta max_scatter_period =
1226 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001227 int64_t staging_wait_time_in_days = 0;
1228 // Use staging and its default max value if staging is on.
Amin Hassani538bd592020-11-04 20:46:08 -08001229 if (SystemState::Get()->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1230 &staging_wait_time_in_days) &&
Adolfo Victoria497044c2018-07-18 07:51:42 -07001231 staging_wait_time_in_days > 0)
1232 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001233
Amin Hassani61789032020-11-13 16:20:12 -08001234 const auto* params = SystemState::Get()->request_params();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001235 LOG(INFO) << "Waiting Period = "
Amin Hassani61789032020-11-13 16:20:12 -08001236 << utils::FormatSecs(params->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001237 << ", Time Elapsed = "
1238 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001239 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001240
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001241 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001242 // The deadline is set for all rules which serve a delta update from a
1243 // previous FSI, which means this update will be applied mostly in OOBE
1244 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1245 // quickly.
Amin Hassanida35b872020-11-04 17:54:44 -08001246 LOG(INFO) << "Not scattering as deadline flag is set.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001247 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1248 }
1249
1250 if (max_scatter_period.InDays() == 0) {
1251 // This means the Omaha rule creator decides that this rule
1252 // should not be scattered irrespective of the policy.
1253 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1254 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1255 }
1256
1257 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001258 // This means we've waited more than the upperbound wait in the rule
1259 // from the time we first saw a valid update available to us.
1260 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001261 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1262 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1263 }
1264
1265 // This means we are required to participate in scattering.
1266 // See if our turn has arrived now.
Amin Hassani61789032020-11-13 16:20:12 -08001267 TimeDelta remaining_wait_time = params->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001268 if (remaining_wait_time.InSeconds() <= 0) {
1269 // Yes, it's our turn now.
1270 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1271
1272 // But we can't download until the update-check-count-based wait is also
1273 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani61789032020-11-13 16:20:12 -08001274 return params->update_check_count_wait_enabled()
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001275 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1276 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001277 }
1278
1279 // Not our turn yet, so we have to wait until our turn to
1280 // help scatter the downloads across all clients of the enterprise.
1281 LOG(INFO) << "Update deferred for another "
1282 << utils::FormatSecs(remaining_wait_time.InSeconds())
1283 << " per policy.";
1284 return kWallClockWaitNotSatisfied;
1285}
1286
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001287bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001288 int64_t update_check_count_value;
Amin Hassani61789032020-11-13 16:20:12 -08001289 const auto* params = SystemState::Get()->request_params();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001290
Amin Hassani538bd592020-11-04 20:46:08 -08001291 if (SystemState::Get()->prefs()->Exists(kPrefsUpdateCheckCount)) {
1292 if (!SystemState::Get()->prefs()->GetInt64(kPrefsUpdateCheckCount,
1293 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001294 // We are unable to read the update check count from file for some reason.
1295 // So let's proceed anyway so as to not stall the update.
1296 LOG(ERROR) << "Unable to read update check count. "
1297 << "Skipping update-check-count-based-wait.";
1298 return true;
1299 }
1300 } else {
1301 // This file does not exist. This means we haven't started our update
1302 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001303 update_check_count_value =
Amin Hassani61789032020-11-13 16:20:12 -08001304 base::RandInt(params->min_update_checks_needed(),
1305 params->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001306
1307 LOG(INFO) << "Randomly picked update check count value = "
1308 << update_check_count_value;
1309
1310 // Write out the initial value of update_check_count_value.
Amin Hassani538bd592020-11-04 20:46:08 -08001311 if (!SystemState::Get()->prefs()->SetInt64(kPrefsUpdateCheckCount,
1312 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001313 // We weren't able to write the update check count file for some reason.
1314 // So let's proceed anyway so as to not stall the update.
1315 LOG(ERROR) << "Unable to write update check count. "
1316 << "Skipping update-check-count-based-wait.";
1317 return true;
1318 }
1319 }
1320
1321 if (update_check_count_value == 0) {
1322 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1323 return true;
1324 }
1325
1326 if (update_check_count_value < 0 ||
Amin Hassani61789032020-11-13 16:20:12 -08001327 update_check_count_value > params->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001328 // We err on the side of skipping scattering logic instead of stalling
1329 // a machine from receiving any updates in case of any unexpected state.
1330 LOG(ERROR) << "Invalid value for update check count detected. "
1331 << "Skipping update-check-count-based-wait.";
1332 return true;
1333 }
1334
1335 // Legal value, we need to wait for more update checks to happen
1336 // until this becomes 0.
1337 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001338 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001339 return false;
1340}
1341
David Zeuthen639aa362014-02-03 16:23:44 -08001342// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001343bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001344 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001345 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001346 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001347 return false;
1348
1349 if (elapsed_days < 0)
1350 return false;
1351
1352 output_object->install_date_days = elapsed_days;
1353 return true;
1354}
1355
1356// static
Amin Hassani538bd592020-11-04 20:46:08 -08001357bool OmahaRequestAction::HasInstallDate() {
Amin Hassani90e9f192020-11-18 14:20:56 -08001358 return SystemState::Get()->prefs()->Exists(kPrefsInstallDateDays);
David Zeuthen639aa362014-02-03 16:23:44 -08001359}
1360
1361// static
1362bool OmahaRequestAction::PersistInstallDate(
David Zeuthen639aa362014-02-03 16:23:44 -08001363 int install_date_days,
1364 InstallDateProvisioningSource source) {
1365 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1366
Amin Hassani90e9f192020-11-18 14:20:56 -08001367 auto* prefs = SystemState::Get()->prefs();
David Zeuthen639aa362014-02-03 16:23:44 -08001368 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1369 return false;
1370
Amin Hassani538bd592020-11-04 20:46:08 -08001371 SystemState::Get()->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001372 static_cast<int>(source), // Sample.
1373 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001374 return true;
1375}
1376
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001377void OmahaRequestAction::PersistCohortData(const string& prefs_key,
1378 const Optional<string>& new_value) {
1379 if (!new_value)
1380 return;
1381 const string& value = new_value.value();
Amin Hassani538bd592020-11-04 20:46:08 -08001382 if (value.empty() && SystemState::Get()->prefs()->Exists(prefs_key)) {
1383 if (!SystemState::Get()->prefs()->Delete(prefs_key))
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001384 LOG(ERROR) << "Failed to remove stored " << prefs_key << "value.";
1385 else
1386 LOG(INFO) << "Removed stored " << prefs_key << " value.";
1387 } else if (!value.empty()) {
Amin Hassani538bd592020-11-04 20:46:08 -08001388 if (!SystemState::Get()->prefs()->SetString(prefs_key, value))
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001389 LOG(INFO) << "Failed to store new setting " << prefs_key << " as "
1390 << value;
1391 else
1392 LOG(INFO) << "Stored cohort setting " << prefs_key << " as " << value;
Alex Deymo8e18f932015-03-27 16:16:59 -07001393 }
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001394}
1395
1396void OmahaRequestAction::PersistCohorts(const OmahaParserData& parser_data) {
Amin Hassani61789032020-11-13 16:20:12 -08001397 const auto* params = SystemState::Get()->request_params();
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001398 for (const auto& app : parser_data.apps) {
1399 // For platform App ID.
Amin Hassani61789032020-11-13 16:20:12 -08001400 if (app.id == params->GetAppId()) {
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001401 PersistCohortData(kPrefsOmahaCohort, app.cohort);
1402 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
1403 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
Amin Hassani61789032020-11-13 16:20:12 -08001404 } else if (params->IsDlcAppId(app.id)) {
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001405 string dlc_id;
Amin Hassani61789032020-11-13 16:20:12 -08001406 if (!params->GetDlcId(app.id, &dlc_id)) {
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001407 LOG(WARNING) << "Skip persisting cohorts for DLC App ID=" << app.id
1408 << " as it is not in the request params.";
1409 continue;
1410 }
Amin Hassani90e9f192020-11-18 14:20:56 -08001411 auto* prefs = SystemState::Get()->prefs();
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001412 PersistCohortData(
1413 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohort}),
1414 app.cohort);
1415 PersistCohortData(
1416 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohortName}),
1417 app.cohortname);
1418 PersistCohortData(
1419 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohortHint}),
1420 app.cohorthint);
1421 } else {
1422 LOG(WARNING) << "Skip persisting cohorts for unknown App ID=" << app.id;
1423 }
1424 }
Alex Deymo8e18f932015-03-27 16:16:59 -07001425}
1426
Amin Hassani2cbb0692019-10-30 13:36:17 -07001427bool OmahaRequestAction::PersistEolInfo(const map<string, string>& attrs) {
Jae Hoon Kimb3146742019-11-07 13:24:24 -08001428 // If EOL date attribute is not sent, don't delete the old persisted EOL
1429 // date information.
Jae Hoon Kim051627a2019-09-03 12:56:32 -07001430 auto eol_date_attr = attrs.find(kAttrEolDate);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07001431 if (eol_date_attr != attrs.end()) {
1432 const auto& eol_date = eol_date_attr->second;
Amin Hassani538bd592020-11-04 20:46:08 -08001433 if (!SystemState::Get()->prefs()->SetString(kPrefsOmahaEolDate, eol_date)) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07001434 LOG(ERROR) << "Setting EOL date failed.";
1435 return false;
1436 }
1437 LOG(INFO) << "Set EOL date to " << eol_date;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001438 }
Amin Hassani2cbb0692019-10-30 13:36:17 -07001439 return true;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001440}
1441
David Zeuthen33bae492014-02-25 16:16:18 -08001442void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1443 // We only want to report this on "update check".
1444 if (ping_only_ || event_ != nullptr)
1445 return;
1446
1447 metrics::CheckResult result = metrics::CheckResult::kUnset;
1448 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1449 metrics::DownloadErrorCode download_error_code =
1450 metrics::DownloadErrorCode::kUnset;
1451
1452 // Regular update attempt.
1453 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001454 case ErrorCode::kSuccess:
1455 // OK, we parsed the response successfully but that does
1456 // necessarily mean that an update is available.
1457 if (HasOutputPipe()) {
1458 const OmahaResponse& response = GetOutputObject();
1459 if (response.update_exists) {
1460 result = metrics::CheckResult::kUpdateAvailable;
1461 reaction = metrics::CheckReaction::kUpdating;
1462 } else {
1463 result = metrics::CheckResult::kNoUpdateAvailable;
1464 }
David Zeuthen33bae492014-02-25 16:16:18 -08001465 } else {
1466 result = metrics::CheckResult::kNoUpdateAvailable;
1467 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001468 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001469
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001470 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1471 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1472 result = metrics::CheckResult::kUpdateAvailable;
1473 reaction = metrics::CheckReaction::kIgnored;
1474 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001475
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001476 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1477 result = metrics::CheckResult::kUpdateAvailable;
1478 reaction = metrics::CheckReaction::kDeferring;
1479 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001480
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001481 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1482 result = metrics::CheckResult::kUpdateAvailable;
1483 reaction = metrics::CheckReaction::kBackingOff;
1484 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001485
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001486 default:
1487 // We report two flavors of errors, "Download errors" and "Parsing
1488 // error". Try to convert to the former and if that doesn't work
1489 // we know it's the latter.
1490 metrics::DownloadErrorCode tmp_error =
1491 metrics_utils::GetDownloadErrorCode(code);
1492 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1493 result = metrics::CheckResult::kDownloadError;
1494 download_error_code = tmp_error;
1495 } else {
1496 result = metrics::CheckResult::kParsingError;
1497 }
1498 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001499 }
1500
Amin Hassani538bd592020-11-04 20:46:08 -08001501 SystemState::Get()->metrics_reporter()->ReportUpdateCheckMetrics(
1502 result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001503}
1504
Toni Barzic61544e62018-10-11 14:37:30 -07001505bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1506 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001507 // Note: policy decision to not update to a version we rolled back from.
1508 string rollback_version =
Amin Hassani538bd592020-11-04 20:46:08 -08001509 SystemState::Get()->payload_state()->GetRollbackVersion();
Amin Hassani61789032020-11-13 16:20:12 -08001510 const auto* params = SystemState::Get()->request_params();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001511 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001512 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001513 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001514 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001515 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001516 return true;
1517 }
1518 }
1519
Amin Hassani538bd592020-11-04 20:46:08 -08001520 if (SystemState::Get()->hardware()->IsOOBEEnabled() &&
1521 !SystemState::Get()->hardware()->IsOOBEComplete(nullptr) &&
Toni Barzic61544e62018-10-11 14:37:30 -07001522 (response.deadline.empty() ||
Amin Hassani538bd592020-11-04 20:46:08 -08001523 SystemState::Get()->payload_state()->GetRollbackHappened()) &&
Amin Hassani61789032020-11-13 16:20:12 -08001524 params->app_version() != "ForcedUpdate") {
Toni Barzic61544e62018-10-11 14:37:30 -07001525 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1526 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1527 return true;
1528 }
1529
Weidong Guo421ff332017-04-17 10:08:38 -07001530 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001531 LOG(INFO) << "Update is not allowed over current connection.";
1532 return true;
1533 }
1534
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001535 // Currently non-critical updates always update alongside the platform update
1536 // (a critical update) so this case should never actually be hit if the
1537 // request to Omaha for updates are correct. In other words, stop the update
1538 // from happening as there are no packages in the response to process.
1539 if (response.packages.empty()) {
1540 LOG(ERROR) << "All packages were excluded.";
1541 }
1542
Chris Sosa77f79e82014-06-02 18:16:24 -07001543 // Note: We could technically delete the UpdateFirstSeenAt state when we
1544 // return true. If we do, it'll mean a device has to restart the
1545 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1546 // turned on again. On the other hand, it also increases the chance of update
1547 // starvation if an admin turns AU on/off more frequently. We choose to err on
1548 // the side of preventing starvation at the cost of not applying scattering in
1549 // those cases.
1550 return false;
1551}
1552
Weidong Guo421ff332017-04-17 10:08:38 -07001553bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1554 const OmahaResponse& response) const {
Amin Hassani90e9f192020-11-18 14:20:56 -08001555 auto* prefs = SystemState::Get()->prefs();
Weidong Guo421ff332017-04-17 10:08:38 -07001556 bool is_allowed;
Weidong Guo421ff332017-04-17 10:08:38 -07001557 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1558 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1559 is_allowed) {
1560 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1561 "set to true.";
1562 return true;
1563 }
1564
1565 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1566 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1567 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1568 "set to false or does not exist while target does not exist.";
1569 return false;
1570 }
1571
1572 std::string target_version;
1573 int64_t target_size;
1574
1575 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1576 &target_version) ||
1577 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1578 LOG(INFO) << "Disabling updates over cellular as the target version or "
1579 "size is not accessible.";
1580 return false;
1581 }
1582
1583 uint64_t total_packages_size = 0;
1584 for (const auto& package : response.packages) {
1585 total_packages_size += package.size;
1586 }
1587 if (target_version == response.version &&
1588 static_cast<uint64_t>(target_size) == total_packages_size) {
1589 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1590 "omaha response.";
1591 return true;
1592 } else {
1593 LOG(INFO) << "Disabling updates over cellular as the target does not"
1594 "match the omaha response.";
1595 return false;
1596 }
1597}
1598
1599bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1600 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001601 ConnectionType type;
1602 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001603 ConnectionManagerInterface* connection_manager =
Amin Hassani538bd592020-11-04 20:46:08 -08001604 SystemState::Get()->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001605 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001606 LOG(INFO) << "We could not determine our connection type. "
1607 << "Defaulting to allow updates.";
1608 return true;
1609 }
Weidong Guo421ff332017-04-17 10:08:38 -07001610
Chris Sosa77f79e82014-06-02 18:16:24 -07001611 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001612 bool is_device_policy_set =
1613 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1614 // Treats tethered connection as if it is cellular connection.
1615 bool is_over_cellular = type == ConnectionType::kCellular ||
1616 tethering == ConnectionTethering::kConfirmed;
1617
1618 if (!is_over_cellular) {
1619 // There's no need to further check user preferences as we are not over
1620 // cellular connection.
1621 if (!is_allowed)
1622 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1623 } else if (is_device_policy_set) {
1624 // There's no need to further check user preferences as the device policy
1625 // is set regarding updates over cellular.
1626 if (!is_allowed)
1627 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1628 } else {
1629 // Deivce policy is not set, so user preferences overwrite whether to
1630 // allow updates over cellular.
1631 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1632 if (!is_allowed)
1633 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1634 }
1635
Chris Sosa77f79e82014-06-02 18:16:24 -07001636 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001637 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001638 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1639 return is_allowed;
1640}
1641
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001642bool OmahaRequestAction::IsRollbackEnabled() const {
1643 if (policy_provider_->IsConsumerDevice()) {
1644 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1645 return false;
1646 }
1647
1648 if (!policy_provider_->device_policy_is_loaded()) {
1649 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1650 return true;
1651 }
1652
1653 int allowed_milestones;
1654 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1655 &allowed_milestones)) {
1656 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1657 "Defaulting to rollback enabled.";
1658 return true;
1659 }
1660
1661 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1662 return allowed_milestones > 0;
1663}
1664
1665void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001666 int max_kernel_rollforward;
Amin Hassani538bd592020-11-04 20:46:08 -08001667 int min_kernel_version =
1668 SystemState::Get()->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001669 if (IsRollbackEnabled()) {
1670 // If rollback is enabled, set the max kernel key version to the current
1671 // kernel key version. This has the effect of freezing kernel key roll
1672 // forwards.
1673 //
1674 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1675 // key roll forward happens until the server side components of rollback
1676 // are implemented. Future changes will allow the Omaha server to return
1677 // the kernel key version from max_rollback_versions in the past. At that
1678 // point the max kernel key version will be set to that value, creating a
1679 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001680 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001681 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001682 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001683 } else {
1684 // For devices that are not rollback enabled (ie. consumer devices), the
1685 // max kernel key version is set to 0xfffffffe, which is logically
1686 // infinity. This maintains the previous behavior that that kernel key
1687 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001688 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001689 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001690 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001691 }
1692
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001693 bool max_rollforward_set =
Amin Hassani538bd592020-11-04 20:46:08 -08001694 SystemState::Get()->hardware()->SetMaxKernelKeyRollforward(
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001695 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001696 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001697 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001698 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001699 // Report metrics
Amin Hassani538bd592020-11-04 20:46:08 -08001700 SystemState::Get()->metrics_reporter()->ReportKeyVersionMetrics(
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001701 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001702}
1703
May Lippert60aa3ca2018-08-15 16:55:29 -07001704base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1705 Time update_first_seen_at;
1706 int64_t update_first_seen_at_int;
Amin Hassani538bd592020-11-04 20:46:08 -08001707 if (SystemState::Get()->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1708 if (SystemState::Get()->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1709 &update_first_seen_at_int)) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001710 // Note: This timestamp could be that of ANY update we saw in the past
1711 // (not necessarily this particular update we're considering to apply)
1712 // but never got to apply because of some reason (e.g. stop AU policy,
1713 // updates being pulled out from Omaha, changes in target version prefix,
1714 // new update being rolled out, etc.). But for the purposes of scattering
1715 // it doesn't matter which update the timestamp corresponds to. i.e.
1716 // the clock starts ticking the first time we see an update and we're
1717 // ready to apply when the random wait period is satisfied relative to
1718 // that first seen timestamp.
1719 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1720 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1721 << utils::ToString(update_first_seen_at);
1722 } else {
1723 // This seems like an unexpected error where the persisted value exists
1724 // but it's not readable for some reason.
1725 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1726 return base::Time();
1727 }
1728 } else {
Amin Hassani538bd592020-11-04 20:46:08 -08001729 update_first_seen_at = SystemState::Get()->clock()->GetWallclockTime();
May Lippert60aa3ca2018-08-15 16:55:29 -07001730 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Amin Hassani538bd592020-11-04 20:46:08 -08001731 if (SystemState::Get()->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1732 update_first_seen_at_int)) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001733 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1734 << utils::ToString(update_first_seen_at);
1735 } else {
1736 // This seems like an unexpected error where the value cannot be
1737 // persisted for some reason.
1738 LOG(INFO) << "UpdateFirstSeenAt value "
1739 << utils::ToString(update_first_seen_at)
1740 << " cannot be persisted";
1741 return base::Time();
1742 }
1743 }
1744 return update_first_seen_at;
1745}
1746
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001747} // namespace chromeos_update_engine