blob: f84719451eee50b901413033870109cfe033067e [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() {
349 PrefsInterface* prefs = SystemState::Get()->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700350 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800351 return -1;
352
353 // If we have the value stored on disk, just return it.
354 int64_t stored_value;
355 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
Kelvin Zhangebd5e252020-07-22 18:27:06 -0400356 // Convert and validity-check.
David Zeuthen639aa362014-02-03 16:23:44 -0800357 int install_date_days = static_cast<int>(stored_value);
358 if (install_date_days >= 0)
359 return install_date_days;
360 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
361 << install_date_days << " looks suspicious.";
362 prefs->Delete(kPrefsInstallDateDays);
363 }
364
365 // Otherwise, if OOBE is not complete then do nothing and wait for
366 // ParseResponse() to call ParseInstallDate() and then
367 // PersistInstallDate() to set the kPrefsInstallDateDays state
368 // variable. Once that is done, we'll then report back in future
369 // Omaha requests. This works exactly because OOBE triggers an
370 // update check.
371 //
372 // However, if OOBE is complete and the kPrefsInstallDateDays state
373 // variable is not set, there are two possibilities
374 //
375 // 1. The update check in OOBE failed so we never got a response
376 // from Omaha (no network etc.); or
377 //
378 // 2. OOBE was done on an older version that didn't write to the
379 // kPrefsInstallDateDays state variable.
380 //
381 // In both cases, we approximate the install date by simply
382 // inspecting the timestamp of when OOBE happened.
383
384 Time time_of_oobe;
Amin Hassani538bd592020-11-04 20:46:08 -0800385 if (!SystemState::Get()->hardware()->IsOOBEEnabled() ||
386 !SystemState::Get()->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800387 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700388 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800389 return -1;
390 }
391
392 int num_days;
393 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
394 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
395 << "as its value '" << utils::ToString(time_of_oobe)
396 << "' looks suspicious.";
397 return -1;
398 }
399
400 // Persist this to disk, for future use.
Amin Hassani538bd592020-11-04 20:46:08 -0800401 if (!OmahaRequestAction::PersistInstallDate(num_days,
402 kProvisionedFromOOBEMarker))
David Zeuthen639aa362014-02-03 16:23:44 -0800403 return -1;
404
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800405 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to " << num_days
Amin Hassanida35b872020-11-04 17:54:44 -0800406 << " days.";
David Zeuthen639aa362014-02-03 16:23:44 -0800407
408 return num_days;
409}
410
Andrewe045aef2020-01-08 16:29:22 -0800411void OmahaRequestAction::StorePingReply(
412 const OmahaParserData& parser_data) const {
Amin Hassani61789032020-11-13 16:20:12 -0800413 const auto* params = SystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -0800414 for (const auto& app : parser_data.apps) {
Amin Hassani61789032020-11-13 16:20:12 -0800415 auto it = params->dlc_apps_params().find(app.id);
416 if (it == params->dlc_apps_params().end())
Andrewe045aef2020-01-08 16:29:22 -0800417 continue;
418
419 const OmahaRequestParams::AppParams& dlc_params = it->second;
Andrew065d78d2020-04-07 15:43:07 -0700420 const string& dlc_id = dlc_params.name;
Andrewe045aef2020-01-08 16:29:22 -0800421 // Skip if the ping for this DLC was not sent.
422 if (!dlc_params.send_ping)
423 continue;
424
Amin Hassani538bd592020-11-04 20:46:08 -0800425 PrefsInterface* prefs = SystemState::Get()->prefs();
Andrewe045aef2020-01-08 16:29:22 -0800426 // Reset the active metadata value to |kPingInactiveValue|.
Andrew065d78d2020-04-07 15:43:07 -0700427 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -0700428 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -0700429 if (!prefs->SetInt64(active_key, kPingInactiveValue))
430 LOG(ERROR) << "Failed to set the value of ping metadata '" << active_key
431 << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800432
Andrew065d78d2020-04-07 15:43:07 -0700433 auto last_rollcall_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -0700434 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -0700435 if (!prefs->SetString(last_rollcall_key, parser_data.daystart_elapsed_days))
Andrewe045aef2020-01-08 16:29:22 -0800436 LOG(ERROR) << "Failed to set the value of ping metadata '"
Andrew065d78d2020-04-07 15:43:07 -0700437 << last_rollcall_key << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800438
439 if (dlc_params.ping_active) {
440 // Write the value of elapsed_days into |kPrefsPingLastActive| only if
441 // the previous ping was an active one.
Andrew065d78d2020-04-07 15:43:07 -0700442 auto last_active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -0700443 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -0700444 if (!prefs->SetString(last_active_key, parser_data.daystart_elapsed_days))
Andrewe045aef2020-01-08 16:29:22 -0800445 LOG(ERROR) << "Failed to set the value of ping metadata '"
Andrew065d78d2020-04-07 15:43:07 -0700446 << last_active_key << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800447 }
448 }
449}
450
Darin Petkov6a5b3222010-07-13 14:55:28 -0700451void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000452 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700453 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700454 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700455 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700456 return;
457 }
David Zeuthen639aa362014-02-03 16:23:44 -0800458
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700459 OmahaRequestBuilderXml omaha_request(event_.get(),
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700460 ping_only_,
461 ShouldPing(), // include_ping
462 ping_active_days_,
463 ping_roll_call_days_,
Amin Hassani538bd592020-11-04 20:46:08 -0800464 GetInstallDate(),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700465 session_id_);
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700466 string request_post = omaha_request.GetRequest();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700467
Sen Jiang42fa45e2018-03-12 11:02:14 -0700468 // Set X-Goog-Update headers.
Amin Hassani9ed2cee2020-11-13 18:40:35 -0800469 const auto* params = SystemState::Get()->request_params();
Alex Deymo14ad88e2016-06-29 12:30:14 -0700470 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
Amin Hassani61789032020-11-13 16:20:12 -0800471 params->interactive() ? "fg" : "bg");
472 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params->GetAppId());
Alex Deymo14ad88e2016-06-29 12:30:14 -0700473 http_fetcher_->SetHeader(
474 kXGoogleUpdateUpdater,
475 base::StringPrintf(
476 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
477
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800478 http_fetcher_->SetPostData(
479 request_post.data(), request_post.size(), kHttpContentTypeTextXml);
Amin Hassani61789032020-11-13 16:20:12 -0800480 LOG(INFO) << "Posting an Omaha request to " << params->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700481 LOG(INFO) << "Request: " << request_post;
Amin Hassani61789032020-11-13 16:20:12 -0800482 http_fetcher_->BeginTransfer(params->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000483}
484
Darin Petkov6a5b3222010-07-13 14:55:28 -0700485void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000486 http_fetcher_->TerminateTransfer();
487}
488
489// We just store the response in the buffer. Once we've received all bytes,
490// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700491bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800492 const void* bytes,
493 size_t length) {
494 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
495 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700496 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000497}
498
499namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000500
501// Parses a 64 bit base-10 int from a string and returns it. Returns 0
502// on error. If the string contains "0", that's indistinguishable from
503// error.
504off_t ParseInt(const string& str) {
505 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700506 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000507 if (rc < 1) {
508 // failure
509 return 0;
510 }
511 return ret;
512}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700513
David Zeuthene8ed8632014-07-24 13:38:10 -0400514// Parses |str| and returns |true| if, and only if, its value is "true".
515bool ParseBool(const string& str) {
516 return str == "true";
517}
518
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700519// Update the last ping day preferences based on the server daystart
520// response. Returns true on success, false otherwise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800521bool UpdateLastPingDays(OmahaParserData* parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700522 int64_t elapsed_seconds = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800523 TEST_AND_RETURN_FALSE(base::StringToInt64(
524 parser_data->daystart_elapsed_seconds, &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700525 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
526
527 // Remember the local time that matches the server's last midnight
528 // time.
529 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
530 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
531 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
532 return true;
533}
Sen Jiang81259682017-03-30 15:11:30 -0700534
535// Parses the package node in the given XML document and populates
536// |output_object| if valid. Returns true if we should continue the parsing.
537// False otherwise, in which case it sets any error code using |completer|.
538bool ParsePackage(OmahaParserData::App* app,
539 OmahaResponse* output_object,
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700540 bool can_exclude,
Sen Jiang81259682017-03-30 15:11:30 -0700541 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700542 if (app->updatecheck_status.empty() ||
543 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700544 if (!app->packages.empty()) {
545 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
546 completer->set_code(ErrorCode::kOmahaResponseInvalid);
547 return false;
548 }
549 return true;
550 }
551 if (app->packages.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800552 LOG(ERROR) << "Omaha Response has no packages.";
Sen Jiang81259682017-03-30 15:11:30 -0700553 completer->set_code(ErrorCode::kOmahaResponseInvalid);
554 return false;
555 }
556 if (app->url_codebase.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800557 LOG(ERROR) << "No Omaha Response URLs.";
Sen Jiang81259682017-03-30 15:11:30 -0700558 completer->set_code(ErrorCode::kOmahaResponseInvalid);
559 return false;
560 }
Sen Jiang81259682017-03-30 15:11:30 -0700561 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700562 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700563 ":",
564 base::TRIM_WHITESPACE,
565 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700566 vector<string> metadata_signatures = base::SplitString(
567 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
568 ":",
569 base::TRIM_WHITESPACE,
570 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700571 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700572 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700573 ":",
574 base::TRIM_WHITESPACE,
575 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700576 for (size_t i = 0; i < app->packages.size(); i++) {
577 const auto& package = app->packages[i];
578 if (package.name.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800579 LOG(ERROR) << "Omaha Response has empty package name.";
Sen Jiang81259682017-03-30 15:11:30 -0700580 completer->set_code(ErrorCode::kOmahaResponseInvalid);
581 return false;
582 }
Sen Jiang81259682017-03-30 15:11:30 -0700583
584 OmahaResponse::Package out_package;
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700585 out_package.app_id = app->id;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700586 out_package.can_exclude = can_exclude;
Sen Jiang81259682017-03-30 15:11:30 -0700587 for (const string& codebase : app->url_codebase) {
588 if (codebase.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800589 LOG(ERROR) << "Omaha Response URL has empty codebase.";
Sen Jiang81259682017-03-30 15:11:30 -0700590 completer->set_code(ErrorCode::kOmahaResponseInvalid);
591 return false;
592 }
593 out_package.payload_urls.push_back(codebase + package.name);
594 }
Amin Hassanida35b872020-11-04 17:54:44 -0800595
Sen Jiang81259682017-03-30 15:11:30 -0700596 // Parse the payload size.
597 base::StringToUint64(package.size, &out_package.size);
598 if (out_package.size <= 0) {
599 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
600 completer->set_code(ErrorCode::kOmahaResponseInvalid);
601 return false;
602 }
Sen Jiang81259682017-03-30 15:11:30 -0700603
604 if (i < metadata_sizes.size())
605 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
Sen Jiang81259682017-03-30 15:11:30 -0700606
607 if (i < metadata_signatures.size())
608 out_package.metadata_signature = metadata_signatures[i];
Sen Jiang81259682017-03-30 15:11:30 -0700609
610 out_package.hash = package.hash;
611 if (out_package.hash.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800612 LOG(ERROR) << "Omaha Response has empty hash_sha256 value.";
Sen Jiang81259682017-03-30 15:11:30 -0700613 completer->set_code(ErrorCode::kOmahaResponseInvalid);
614 return false;
615 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700616
Vyshu Khota4c5413d2020-11-04 16:17:25 -0800617 out_package.fp = package.fp;
618
Sen Jiangcdd52062017-05-18 15:33:10 -0700619 if (i < is_delta_payloads.size())
620 out_package.is_delta = ParseBool(is_delta_payloads[i]);
Sen Jiangcdd52062017-05-18 15:33:10 -0700621
Sen Jiang81259682017-03-30 15:11:30 -0700622 output_object->packages.push_back(std::move(out_package));
623 }
624
625 return true;
626}
627
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700628// Removes the candidate URLs which are excluded within packages, if all the
629// candidate URLs are excluded within a package, the package will be excluded.
630void ProcessExclusions(OmahaResponse* output_object,
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700631 OmahaRequestParams* params,
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700632 ExcluderInterface* excluder) {
633 for (auto package_it = output_object->packages.begin();
634 package_it != output_object->packages.end();
635 /* Increment logic in loop */) {
636 // If package cannot be excluded, quickly continue.
637 if (!package_it->can_exclude) {
638 ++package_it;
639 continue;
640 }
641 // Remove the excluded payload URLs.
642 for (auto payload_url_it = package_it->payload_urls.begin();
643 payload_url_it != package_it->payload_urls.end();
644 /* Increment logic in loop */) {
645 auto exclusion_name = utils::GetExclusionName(*payload_url_it);
646 // If payload URL is not excluded, quickly continue.
647 if (!excluder->IsExcluded(exclusion_name)) {
648 ++payload_url_it;
649 continue;
650 }
651 LOG(INFO) << "Excluding payload URL=" << *payload_url_it
652 << " for payload hash=" << package_it->hash;
653 payload_url_it = package_it->payload_urls.erase(payload_url_it);
654 }
655 // If there are no candidate payload URLs, remove the package.
656 if (package_it->payload_urls.empty()) {
657 LOG(INFO) << "Excluding payload hash=" << package_it->hash;
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700658 // Need to set DLC as not updated so correct metrics can be sent when an
659 // update is completed.
660 params->SetDlcNoUpdate(package_it->app_id);
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700661 package_it = output_object->packages.erase(package_it);
662 continue;
663 }
664 ++package_it;
665 }
666}
667
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700668// Parses the 2 key version strings kernel_version and firmware_version. If the
669// field is not present, or cannot be parsed the values default to 0xffff.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700670void ParseRollbackVersions(int allowed_milestones,
671 OmahaParserData* parser_data,
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700672 OmahaResponse* output_object) {
673 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700674 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700675 &output_object->rollback_key_version.firmware_key,
676 &output_object->rollback_key_version.firmware);
677 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700678 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700679 &output_object->rollback_key_version.kernel_key,
680 &output_object->rollback_key_version.kernel);
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700681
682 // Create the attribute name strings for milestone N - allowed_milestones.
683 const string firmware_max_rollforward_attr =
684 base::StringPrintf("%s_%i", kAttrFirmwareVersion, allowed_milestones);
685 const string kernel_max_rollforward_attr =
686 base::StringPrintf("%s_%i", kAttrKernelVersion, allowed_milestones);
687
688 const bool max_firmware_and_kernel_exist =
689 parser_data->updatecheck_attrs.count(firmware_max_rollforward_attr) > 0 &&
690 parser_data->updatecheck_attrs.count(kernel_max_rollforward_attr) > 0;
691
692 string firmware_version;
693 string kernel_version;
694 if (max_firmware_and_kernel_exist) {
695 firmware_version =
696 parser_data->updatecheck_attrs[firmware_max_rollforward_attr];
697 kernel_version =
698 parser_data->updatecheck_attrs[kernel_max_rollforward_attr];
699 }
700
701 LOG(INFO) << "For milestone N-" << allowed_milestones
702 << " firmware_key_version=" << firmware_version
703 << " kernel_key_version=" << kernel_version;
704
705 OmahaResponse::RollbackKeyVersion version;
706 utils::ParseRollbackKeyVersion(
707 firmware_version, &version.firmware_key, &version.firmware);
708 utils::ParseRollbackKeyVersion(
709 kernel_version, &version.kernel_key, &version.kernel);
710
711 output_object->past_rollback_key_version = std::move(version);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700712}
713
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700714} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000715
David Zeuthene8ed8632014-07-24 13:38:10 -0400716bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700717 OmahaResponse* output_object,
718 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700719 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700720 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700721 return false;
722 }
723
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800724 // chromium-os:37289: The PollInterval is not supported by Omaha server
725 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700726 // slow down the request rate from the server-side. Note that the PollInterval
727 // is not persisted, so it has to be sent by the server on every response to
728 // guarantee that the scheduler uses this value (otherwise, if the device got
729 // rebooted after the last server-indicated value, it'll revert to the default
730 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
731 // based on the assumption that we perform an update check every hour so that
732 // the max value of 8 will roughly be equivalent to one work day. If we decide
733 // to use PollInterval permanently, we should update the
734 // max_update_checks_allowed to take PollInterval into account. Note: The
735 // parsing for PollInterval happens even before parsing of the status because
736 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400737 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700738 &output_object->poll_interval);
739
David Zeuthen639aa362014-02-03 16:23:44 -0800740 // Check for the "elapsed_days" attribute in the "daystart"
741 // element. This is the number of days since Jan 1 2007, 0:00
742 // PST. If we don't have a persisted value of the Omaha InstallDate,
743 // we'll use it to calculate it and then persist it.
Amin Hassani538bd592020-11-04 20:46:08 -0800744 if (ParseInstallDate(parser_data, output_object) && !HasInstallDate()) {
David Zeuthen639aa362014-02-03 16:23:44 -0800745 // Since output_object->install_date_days is never negative, the
746 // elapsed_days -> install-date calculation is reduced to simply
747 // rounding down to the nearest number divisible by 7.
748 int remainder = output_object->install_date_days % 7;
749 int install_date_days_rounded =
750 output_object->install_date_days - remainder;
Amin Hassani538bd592020-11-04 20:46:08 -0800751 if (PersistInstallDate(install_date_days_rounded,
David Zeuthen639aa362014-02-03 16:23:44 -0800752 kProvisionedFromOmahaResponse)) {
753 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
Amin Hassanida35b872020-11-04 17:54:44 -0800754 << install_date_days_rounded << " days.";
David Zeuthen639aa362014-02-03 16:23:44 -0800755 }
756 }
757
Alex Deymo00d79ac2015-06-29 15:41:49 -0700758 // We persist the cohorts sent by omaha even if the status is "noupdate".
Jae Hoon Kime2cac612020-11-02 18:30:29 -0800759 PersistCohorts(*parser_data);
Alex Deymo00d79ac2015-06-29 15:41:49 -0700760
Amin Hassani2cbb0692019-10-30 13:36:17 -0700761 PersistEolInfo(parser_data->updatecheck_attrs);
762
Marton Hunyady199152d2018-05-07 19:08:48 +0200763 // Rollback-related updatecheck attributes.
764 // Defaults to false if attribute is not present.
765 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -0700766 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700767
Amin Hassani61789032020-11-13 16:20:12 -0800768 const auto* params = SystemState::Get()->request_params();
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700769 // Parses the rollback versions of the current image. If the fields do not
770 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700771 ParseRollbackVersions(
Amin Hassani61789032020-11-13 16:20:12 -0800772 params->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -0700773
David Zeuthene8ed8632014-07-24 13:38:10 -0400774 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700775 return false;
776
David Zeuthene8ed8632014-07-24 13:38:10 -0400777 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700778 return false;
779
Sen Jiang0affc2c2017-02-10 15:55:05 -0800780 // Package has to be parsed after Params now because ParseParams need to make
781 // sure that postinstall action exists.
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700782 for (auto& app : parser_data->apps) {
783 // Only allow exclusions for a non-critical package during an update. For
784 // non-critical package installations, let the errors propagate instead
785 // of being handled inside update_engine as installations are a dlcservice
786 // specific feature.
Amin Hassani61789032020-11-13 16:20:12 -0800787 bool can_exclude = !params->is_install() && params->IsDlcAppId(app.id);
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700788 if (!ParsePackage(&app, output_object, can_exclude, completer))
Sen Jiang81259682017-03-30 15:11:30 -0700789 return false;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700790 }
Sen Jiang0affc2c2017-02-10 15:55:05 -0800791
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700792 return true;
793}
794
David Zeuthene8ed8632014-07-24 13:38:10 -0400795bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700796 OmahaResponse* output_object,
797 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700798 output_object->update_exists = false;
Amin Hassani61789032020-11-13 16:20:12 -0800799 auto* params = SystemState::Get()->request_params();
Xiaochu Liu6310be62018-10-11 15:09:03 -0700800 for (const auto& app : parser_data->apps) {
801 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -0700802 if (status == kValNoUpdate) {
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800803 // If the app is a DLC, allow status "noupdate" to support DLC
804 // deprecations.
Amin Hassani61789032020-11-13 16:20:12 -0800805 if (params->IsDlcAppId(app.id)) {
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800806 LOG(INFO) << "No update for <app> " << app.id
807 << " but update continuing since a DLC.";
Amin Hassani61789032020-11-13 16:20:12 -0800808 params->SetDlcNoUpdate(app.id);
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800809 continue;
810 }
Sen Jiang00adf7b2017-06-26 15:57:29 -0700811 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -0700812 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700813 output_object->update_exists = false;
814 break;
Sen Jiang81259682017-03-30 15:11:30 -0700815 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700816 auto const& attr_no_update =
817 app.action_postinstall_attrs.find(kAttrNoUpdate);
818 if (attr_no_update != app.action_postinstall_attrs.end() &&
819 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700820 // noupdate="true" in postinstall attributes means it's an update to
821 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -0700822 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700823 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700824 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700825 output_object->update_exists = true;
826 }
Amin Hassani61789032020-11-13 16:20:12 -0800827 } else if (status.empty() && params->is_install() &&
828 params->GetAppId() == app.id) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700829 // Skips the platform app for install operation.
830 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -0700831 } else {
832 LOG(ERROR) << "Unknown Omaha response status: " << status;
833 completer->set_code(ErrorCode::kOmahaResponseInvalid);
834 return false;
835 }
836 }
837 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700838 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700839 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700840 }
841
Sen Jiang81259682017-03-30 15:11:30 -0700842 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700843}
844
David Zeuthene8ed8632014-07-24 13:38:10 -0400845bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700846 OmahaResponse* output_object,
847 ScopedActionCompleter* completer) {
Amin Hassani61789032020-11-13 16:20:12 -0800848 const auto* params = SystemState::Get()->request_params();
Sen Jiang81259682017-03-30 15:11:30 -0700849 map<string, string> attrs;
850 for (auto& app : parser_data->apps) {
Amin Hassani61789032020-11-13 16:20:12 -0800851 if (app.id == params->GetAppId()) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700852 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -0700853 output_object->version = app.manifest_version;
Amin Hassani61789032020-11-13 16:20:12 -0800854 } else if (params->is_install() &&
855 app.manifest_version != params->app_version()) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700856 LOG(WARNING) << "An app has a different version (" << app.manifest_version
857 << ") that is different than platform app version ("
Amin Hassani61789032020-11-13 16:20:12 -0800858 << params->app_version() << ").";
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700859 }
860 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700861 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700862 }
Sen Jiang81259682017-03-30 15:11:30 -0700863 }
Amin Hassani61789032020-11-13 16:20:12 -0800864 if (params->is_install()) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700865 LOG(INFO) << "Use request version for Install operation.";
Amin Hassani61789032020-11-13 16:20:12 -0800866 output_object->version = params->app_version();
Xiaochu Liu6310be62018-10-11 15:09:03 -0700867 }
Chris Sosa3b748432013-06-20 16:42:59 -0700868 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700869 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700870 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700871 return false;
872 }
873
David Zeuthene8ed8632014-07-24 13:38:10 -0400874 if (attrs.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800875 LOG(ERROR) << "Omaha Response has no postinstall event action.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700876 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700877 return false;
878 }
879
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800880 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -0700881 output_object->more_info_url = attrs[kAttrMoreInfo];
882 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
883 output_object->deadline = attrs[kAttrDeadline];
884 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700885 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -0700886 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700887 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -0700888 ParseBool(attrs[kAttrDisableP2PForSharing]);
889 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800890
Amin Hassani6600a562018-09-24 15:17:19 -0700891 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800892 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800893 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700894
Jay Srinivasan08262882012-12-28 19:29:43 -0800895 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -0700896 ParseBool(attrs[kAttrDisablePayloadBackoff]);
897 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800898
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700899 return true;
900}
901
David Zeuthene8ed8632014-07-24 13:38:10 -0400902// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000903// and fill in the appropriate fields of the output object. Also, notifies
904// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800905void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -0700906 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000907 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800908 string current_response(response_buffer_.begin(), response_buffer_.end());
909 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700910
Amin Hassani538bd592020-11-04 20:46:08 -0800911 PayloadStateInterface* const payload_state =
912 SystemState::Get()->payload_state();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700913
Zentaro Kavanagh76af2662018-05-15 10:54:53 -0700914 // Set the max kernel key version based on whether rollback is allowed.
915 SetMaxKernelKeyVersionForRollback();
916
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700917 // Events are best effort transactions -- assume they always succeed.
918 if (IsEvent()) {
919 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700920 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700921 return;
922 }
923
Amin Hassanid3d84212019-08-17 00:27:44 -0700924 ErrorCode aux_error_code = fetcher->GetAuxiliaryErrorCode();
925 if (aux_error_code != ErrorCode::kSuccess) {
926 metrics::DownloadErrorCode download_error_code =
927 metrics_utils::GetDownloadErrorCode(aux_error_code);
Amin Hassani538bd592020-11-04 20:46:08 -0800928 SystemState::Get()->metrics_reporter()->ReportUpdateCheckMetrics(
Amin Hassanid3d84212019-08-17 00:27:44 -0700929 metrics::CheckResult::kUnset,
930 metrics::CheckReaction::kUnset,
931 download_error_code);
932 }
933
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700934 if (!successful) {
Darin Petkovedc522e2010-11-05 09:35:17 -0700935 int code = GetHTTPResponseCode();
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700936 LOG(ERROR) << "Omaha request network transfer failed with HTTPResponseCode="
937 << code;
Saint Chou6431c332020-07-29 14:04:14 +0000938 // Makes sure we send proper error values.
Darin Petkovedc522e2010-11-05 09:35:17 -0700939 if (code < 0 || code >= 1000) {
940 code = 999;
Saint Chou6431c332020-07-29 14:04:14 +0000941 LOG(WARNING) << "Converting to proper HTTPResponseCode=" << code;
Darin Petkovedc522e2010-11-05 09:35:17 -0700942 }
David Zeuthena99981f2013-04-29 13:42:47 -0700943 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700944 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000945 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700946 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000947
David Zeuthene8ed8632014-07-24 13:38:10 -0400948 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400949 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400950 XML_SetUserData(parser, &parser_data);
951 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400952 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800953 XML_Status res =
954 XML_Parse(parser,
955 reinterpret_cast<const char*>(response_buffer_.data()),
956 response_buffer_.size(),
957 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400958
959 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700960 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800961 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
962 << XML_GetCurrentLineNumber(parser) << " col "
963 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -0700964 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400965 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
966 if (response_buffer_.empty()) {
967 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
968 } else if (parser_data.entity_decl) {
969 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
970 }
971 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000972 return;
973 }
Amin Hassani91f48b42018-08-06 17:47:14 -0700974 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000975
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700976 // Update the last ping day preferences based on the server daystart response
977 // even if we didn't send a ping. Omaha always includes the daystart in the
978 // response, but log the error if it didn't.
Amin Hassani538bd592020-11-04 20:46:08 -0800979 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, SystemState::Get()->prefs()))
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700980 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700981
Amin Hassani1677e812017-06-21 13:36:36 -0700982 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
983 // we have got a response from omaha and if its value has never been set to
984 // true before. Failure of this function should be ignored. There should be no
985 // need to check if a=-1 has been sent because older devices have already sent
986 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
987 // future checks.
Amin Hassani538bd592020-11-04 20:46:08 -0800988 if (!SystemState::Get()->hardware()->GetFirstActiveOmahaPingSent()) {
989 if (!SystemState::Get()->hardware()->SetFirstActiveOmahaPingSent()) {
990 SystemState::Get()->metrics_reporter()->ReportInternalErrorCode(
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700991 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
992 }
Amin Hassani1677e812017-06-21 13:36:36 -0700993 }
994
Andrewe045aef2020-01-08 16:29:22 -0800995 // Create/update the metadata files for each DLC app received.
996 StorePingReply(parser_data);
997
Thieu Le116fda32011-04-19 11:01:54 -0700998 if (!HasOutputPipe()) {
999 // Just set success to whether or not the http transfer succeeded,
1000 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001001 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001002 return;
1003 }
1004
Darin Petkov6a5b3222010-07-13 14:55:28 -07001005 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001006 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001007 return;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001008 ProcessExclusions(&output_object,
Amin Hassani538bd592020-11-04 20:46:08 -08001009 SystemState::Get()->request_params(),
1010 SystemState::Get()->update_attempter()->GetExcluder());
David Zeuthen8f191b22013-08-06 12:27:50 -07001011 output_object.update_exists = true;
1012 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001013
Toni Barzic61544e62018-10-11 14:37:30 -07001014 LoadOrPersistUpdateFirstSeenAtPref();
1015
Weidong Guo421ff332017-04-17 10:08:38 -07001016 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -07001017 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -07001018 // No need to change output_object.update_exists here, since the value
1019 // has been output to the pipe.
1020 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001021 return;
1022 }
1023
David Zeuthen8f191b22013-08-06 12:27:50 -07001024 // If Omaha says to disable p2p, respect that
1025 if (output_object.disable_p2p_for_downloading) {
1026 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1027 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001028 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001029 }
1030 if (output_object.disable_p2p_for_sharing) {
1031 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1032 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001033 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001034 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001035
1036 // Update the payload state with the current response. The payload state
1037 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001038 // from what's stored already. We are updating the payload state as late
1039 // as possible in this method so that if a new release gets pushed and then
1040 // got pulled back due to some issues, we don't want to clear our internal
1041 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001042 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001043
David Zeuthen8f191b22013-08-06 12:27:50 -07001044 // It could be we've already exceeded the deadline for when p2p is
1045 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001046 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001047 payload_state->P2PNewAttempt();
1048 if (!payload_state->P2PAttemptAllowed()) {
1049 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1050 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001051 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001052 }
1053 }
1054
1055 // From here on, we'll complete stuff in CompleteProcessing() so
1056 // disable |completer| since we'll create a new one in that
1057 // function.
1058 completer.set_should_complete(false);
1059
1060 // If we're allowed to use p2p for downloading we do not pay
1061 // attention to wall-clock-based waiting if the URL is indeed
1062 // available via p2p. Therefore, check if the file is available via
1063 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001064 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001065 LookupPayloadViaP2P(output_object);
1066 } else {
1067 CompleteProcessing();
1068 }
1069}
1070
1071void OmahaRequestAction::CompleteProcessing() {
1072 ScopedActionCompleter completer(processor_, this);
1073 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
Amin Hassani538bd592020-11-04 20:46:08 -08001074 PayloadStateInterface* payload_state = SystemState::Get()->payload_state();
David Zeuthen8f191b22013-08-06 12:27:50 -07001075
1076 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001077 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001078 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001079 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001080 return;
1081 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001082
Chris Sosa20f005c2013-09-05 13:53:08 -07001083 if (payload_state->ShouldBackoffDownload()) {
1084 output_object.update_exists = false;
1085 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
Amin Hassanida35b872020-11-04 17:54:44 -08001086 << "attempts.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001087 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001088 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001089 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001090 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001091}
1092
1093void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1094 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1095 if (!url.empty()) {
Amin Hassani538bd592020-11-04 20:46:08 -08001096 SystemState::Get()->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001097 } else {
1098 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1099 << "because no suitable peer could be found.";
Amin Hassani538bd592020-11-04 20:46:08 -08001100 SystemState::Get()->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001101 }
1102 CompleteProcessing();
1103}
1104
1105void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001106 // If the device is in the middle of an update, the state variables
1107 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1108 // tracks the offset and length of the operation currently in
1109 // progress. The offset is based from the end of the manifest which
1110 // is kPrefsManifestMetadataSize bytes long.
1111 //
1112 // To make forward progress and avoid deadlocks, we need to find a
1113 // peer that has at least the entire operation we're currently
1114 // working on. Otherwise we may end up in a situation where two
1115 // devices bounce back and forth downloading from each other,
1116 // neither making any forward progress until one of them decides to
1117 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1118 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001119 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001120 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001121 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001122 int64_t next_data_offset = 0;
1123 int64_t next_data_length = 0;
Amin Hassani538bd592020-11-04 20:46:08 -08001124 if (SystemState::Get()->prefs()->GetInt64(kPrefsManifestMetadataSize,
1125 &manifest_metadata_size) &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001126 manifest_metadata_size != -1 &&
Amin Hassani538bd592020-11-04 20:46:08 -08001127 SystemState::Get()->prefs()->GetInt64(kPrefsManifestSignatureSize,
1128 &manifest_signature_size) &&
Alex Deymof25eb492016-02-26 00:20:08 -08001129 manifest_signature_size != -1 &&
Amin Hassani538bd592020-11-04 20:46:08 -08001130 SystemState::Get()->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
1131 &next_data_offset) &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001132 next_data_offset != -1 &&
Amin Hassani538bd592020-11-04 20:46:08 -08001133 SystemState::Get()->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1134 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001135 minimum_size = manifest_metadata_size + manifest_signature_size +
1136 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001137 }
1138
Sen Jiang0affc2c2017-02-10 15:55:05 -08001139 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001140 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001141 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001142 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001143 string file_id =
1144 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Amin Hassani538bd592020-11-04 20:46:08 -08001145 if (SystemState::Get()->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001146 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1147 << " minimum_size=" << minimum_size;
Amin Hassani538bd592020-11-04 20:46:08 -08001148 SystemState::Get()->p2p_manager()->LookupUrlForFile(
David Zeuthen8f191b22013-08-06 12:27:50 -07001149 file_id,
1150 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001151 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001152 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1153 base::Unretained(this)));
1154 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001155}
1156
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001157bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Amin Hassani61789032020-11-13 16:20:12 -08001158 const auto* params = SystemState::Get()->request_params();
1159 if (params->interactive()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001160 LOG(INFO) << "Not deferring download because update is interactive.";
1161 return false;
1162 }
1163
David Zeuthen8f191b22013-08-06 12:27:50 -07001164 // If we're using p2p to download _and_ we have a p2p URL, we never
1165 // defer the download. This is because the download will always
1166 // happen from a peer on the LAN and we've been waiting in line for
1167 // our turn.
Amin Hassani538bd592020-11-04 20:46:08 -08001168 const PayloadStateInterface* payload_state =
1169 SystemState::Get()->payload_state();
Gilad Arnold74b5f552014-10-07 08:17:16 -07001170 if (payload_state->GetUsingP2PForDownloading() &&
1171 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001172 LOG(INFO) << "Download not deferred because download "
1173 << "will happen from a local peer (via p2p).";
1174 return false;
1175 }
1176
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001177 // We should defer the downloads only if we've first satisfied the
1178 // wall-clock-based-waiting period and then the update-check-based waiting
1179 // period, if required.
Amin Hassani61789032020-11-13 16:20:12 -08001180 if (!params->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001181 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1182 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001183 return false;
1184 }
1185
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001186 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001187 case kWallClockWaitNotSatisfied:
1188 // We haven't even satisfied the first condition, passing the
1189 // wall-clock-based waiting period, so we should defer the downloads
1190 // until that happens.
1191 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1192 return true;
1193
1194 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1195 LOG(INFO) << "wall-clock-based-wait satisfied and "
1196 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001197 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001198
1199 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1200 // Wall-clock-based waiting period is satisfied, and it's determined
1201 // that we do not need the update-check-based wait. so no need to
1202 // defer downloads.
1203 LOG(INFO) << "wall-clock-based-wait satisfied and "
1204 << "update-check-based-wait is not required.";
1205 return false;
1206
1207 default:
1208 // Returning false for this default case so we err on the
1209 // side of downloading updates than deferring in case of any bugs.
1210 NOTREACHED();
1211 return false;
1212 }
1213}
1214
1215OmahaRequestAction::WallClockWaitResult
1216OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001217 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001218 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1219 if (update_first_seen_at == base::Time()) {
1220 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
Amin Hassanida35b872020-11-04 17:54:44 -08001221 "persisted.";
May Lippert60aa3ca2018-08-15 16:55:29 -07001222 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001223 }
1224
Sen Jiang7c1171e2016-06-23 11:35:40 -07001225 TimeDelta elapsed_time =
Amin Hassani538bd592020-11-04 20:46:08 -08001226 SystemState::Get()->clock()->GetWallclockTime() - update_first_seen_at;
Sen Jiang7c1171e2016-06-23 11:35:40 -07001227 TimeDelta max_scatter_period =
1228 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001229 int64_t staging_wait_time_in_days = 0;
1230 // Use staging and its default max value if staging is on.
Amin Hassani538bd592020-11-04 20:46:08 -08001231 if (SystemState::Get()->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1232 &staging_wait_time_in_days) &&
Adolfo Victoria497044c2018-07-18 07:51:42 -07001233 staging_wait_time_in_days > 0)
1234 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001235
Amin Hassani61789032020-11-13 16:20:12 -08001236 const auto* params = SystemState::Get()->request_params();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001237 LOG(INFO) << "Waiting Period = "
Amin Hassani61789032020-11-13 16:20:12 -08001238 << utils::FormatSecs(params->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001239 << ", Time Elapsed = "
1240 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001241 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001242
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001243 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001244 // The deadline is set for all rules which serve a delta update from a
1245 // previous FSI, which means this update will be applied mostly in OOBE
1246 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1247 // quickly.
Amin Hassanida35b872020-11-04 17:54:44 -08001248 LOG(INFO) << "Not scattering as deadline flag is set.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001249 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1250 }
1251
1252 if (max_scatter_period.InDays() == 0) {
1253 // This means the Omaha rule creator decides that this rule
1254 // should not be scattered irrespective of the policy.
1255 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1256 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1257 }
1258
1259 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001260 // This means we've waited more than the upperbound wait in the rule
1261 // from the time we first saw a valid update available to us.
1262 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001263 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1264 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1265 }
1266
1267 // This means we are required to participate in scattering.
1268 // See if our turn has arrived now.
Amin Hassani61789032020-11-13 16:20:12 -08001269 TimeDelta remaining_wait_time = params->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001270 if (remaining_wait_time.InSeconds() <= 0) {
1271 // Yes, it's our turn now.
1272 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1273
1274 // But we can't download until the update-check-count-based wait is also
1275 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani61789032020-11-13 16:20:12 -08001276 return params->update_check_count_wait_enabled()
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001277 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1278 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001279 }
1280
1281 // Not our turn yet, so we have to wait until our turn to
1282 // help scatter the downloads across all clients of the enterprise.
1283 LOG(INFO) << "Update deferred for another "
1284 << utils::FormatSecs(remaining_wait_time.InSeconds())
1285 << " per policy.";
1286 return kWallClockWaitNotSatisfied;
1287}
1288
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001289bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001290 int64_t update_check_count_value;
Amin Hassani61789032020-11-13 16:20:12 -08001291 const auto* params = SystemState::Get()->request_params();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001292
Amin Hassani538bd592020-11-04 20:46:08 -08001293 if (SystemState::Get()->prefs()->Exists(kPrefsUpdateCheckCount)) {
1294 if (!SystemState::Get()->prefs()->GetInt64(kPrefsUpdateCheckCount,
1295 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001296 // We are unable to read the update check count from file for some reason.
1297 // So let's proceed anyway so as to not stall the update.
1298 LOG(ERROR) << "Unable to read update check count. "
1299 << "Skipping update-check-count-based-wait.";
1300 return true;
1301 }
1302 } else {
1303 // This file does not exist. This means we haven't started our update
1304 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001305 update_check_count_value =
Amin Hassani61789032020-11-13 16:20:12 -08001306 base::RandInt(params->min_update_checks_needed(),
1307 params->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001308
1309 LOG(INFO) << "Randomly picked update check count value = "
1310 << update_check_count_value;
1311
1312 // Write out the initial value of update_check_count_value.
Amin Hassani538bd592020-11-04 20:46:08 -08001313 if (!SystemState::Get()->prefs()->SetInt64(kPrefsUpdateCheckCount,
1314 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001315 // We weren't able to write the update check count file for some reason.
1316 // So let's proceed anyway so as to not stall the update.
1317 LOG(ERROR) << "Unable to write update check count. "
1318 << "Skipping update-check-count-based-wait.";
1319 return true;
1320 }
1321 }
1322
1323 if (update_check_count_value == 0) {
1324 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1325 return true;
1326 }
1327
1328 if (update_check_count_value < 0 ||
Amin Hassani61789032020-11-13 16:20:12 -08001329 update_check_count_value > params->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001330 // We err on the side of skipping scattering logic instead of stalling
1331 // a machine from receiving any updates in case of any unexpected state.
1332 LOG(ERROR) << "Invalid value for update check count detected. "
1333 << "Skipping update-check-count-based-wait.";
1334 return true;
1335 }
1336
1337 // Legal value, we need to wait for more update checks to happen
1338 // until this becomes 0.
1339 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001340 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001341 return false;
1342}
1343
David Zeuthen639aa362014-02-03 16:23:44 -08001344// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001345bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001346 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001347 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001348 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001349 return false;
1350
1351 if (elapsed_days < 0)
1352 return false;
1353
1354 output_object->install_date_days = elapsed_days;
1355 return true;
1356}
1357
1358// static
Amin Hassani538bd592020-11-04 20:46:08 -08001359bool OmahaRequestAction::HasInstallDate() {
1360 PrefsInterface* prefs = SystemState::Get()->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001361 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001362 return false;
1363
1364 return prefs->Exists(kPrefsInstallDateDays);
1365}
1366
1367// static
1368bool OmahaRequestAction::PersistInstallDate(
David Zeuthen639aa362014-02-03 16:23:44 -08001369 int install_date_days,
1370 InstallDateProvisioningSource source) {
1371 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1372
Amin Hassani538bd592020-11-04 20:46:08 -08001373 PrefsInterface* prefs = SystemState::Get()->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001374 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001375 return false;
1376
1377 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1378 return false;
1379
Amin Hassani538bd592020-11-04 20:46:08 -08001380 SystemState::Get()->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001381 static_cast<int>(source), // Sample.
1382 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001383 return true;
1384}
1385
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001386void OmahaRequestAction::PersistCohortData(const string& prefs_key,
1387 const Optional<string>& new_value) {
1388 if (!new_value)
1389 return;
1390 const string& value = new_value.value();
Amin Hassani538bd592020-11-04 20:46:08 -08001391 if (value.empty() && SystemState::Get()->prefs()->Exists(prefs_key)) {
1392 if (!SystemState::Get()->prefs()->Delete(prefs_key))
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001393 LOG(ERROR) << "Failed to remove stored " << prefs_key << "value.";
1394 else
1395 LOG(INFO) << "Removed stored " << prefs_key << " value.";
1396 } else if (!value.empty()) {
Amin Hassani538bd592020-11-04 20:46:08 -08001397 if (!SystemState::Get()->prefs()->SetString(prefs_key, value))
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001398 LOG(INFO) << "Failed to store new setting " << prefs_key << " as "
1399 << value;
1400 else
1401 LOG(INFO) << "Stored cohort setting " << prefs_key << " as " << value;
Alex Deymo8e18f932015-03-27 16:16:59 -07001402 }
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001403}
1404
1405void OmahaRequestAction::PersistCohorts(const OmahaParserData& parser_data) {
Amin Hassani61789032020-11-13 16:20:12 -08001406 const auto* params = SystemState::Get()->request_params();
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001407 for (const auto& app : parser_data.apps) {
1408 // For platform App ID.
Amin Hassani61789032020-11-13 16:20:12 -08001409 if (app.id == params->GetAppId()) {
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001410 PersistCohortData(kPrefsOmahaCohort, app.cohort);
1411 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
1412 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
Amin Hassani61789032020-11-13 16:20:12 -08001413 } else if (params->IsDlcAppId(app.id)) {
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001414 string dlc_id;
Amin Hassani61789032020-11-13 16:20:12 -08001415 if (!params->GetDlcId(app.id, &dlc_id)) {
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001416 LOG(WARNING) << "Skip persisting cohorts for DLC App ID=" << app.id
1417 << " as it is not in the request params.";
1418 continue;
1419 }
Amin Hassani538bd592020-11-04 20:46:08 -08001420 PrefsInterface* prefs = SystemState::Get()->prefs();
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001421 PersistCohortData(
1422 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohort}),
1423 app.cohort);
1424 PersistCohortData(
1425 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohortName}),
1426 app.cohortname);
1427 PersistCohortData(
1428 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohortHint}),
1429 app.cohorthint);
1430 } else {
1431 LOG(WARNING) << "Skip persisting cohorts for unknown App ID=" << app.id;
1432 }
1433 }
Alex Deymo8e18f932015-03-27 16:16:59 -07001434}
1435
Amin Hassani2cbb0692019-10-30 13:36:17 -07001436bool OmahaRequestAction::PersistEolInfo(const map<string, string>& attrs) {
Jae Hoon Kimb3146742019-11-07 13:24:24 -08001437 // If EOL date attribute is not sent, don't delete the old persisted EOL
1438 // date information.
Jae Hoon Kim051627a2019-09-03 12:56:32 -07001439 auto eol_date_attr = attrs.find(kAttrEolDate);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07001440 if (eol_date_attr != attrs.end()) {
1441 const auto& eol_date = eol_date_attr->second;
Amin Hassani538bd592020-11-04 20:46:08 -08001442 if (!SystemState::Get()->prefs()->SetString(kPrefsOmahaEolDate, eol_date)) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07001443 LOG(ERROR) << "Setting EOL date failed.";
1444 return false;
1445 }
1446 LOG(INFO) << "Set EOL date to " << eol_date;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001447 }
Amin Hassani2cbb0692019-10-30 13:36:17 -07001448 return true;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001449}
1450
David Zeuthen33bae492014-02-25 16:16:18 -08001451void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1452 // We only want to report this on "update check".
1453 if (ping_only_ || event_ != nullptr)
1454 return;
1455
1456 metrics::CheckResult result = metrics::CheckResult::kUnset;
1457 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1458 metrics::DownloadErrorCode download_error_code =
1459 metrics::DownloadErrorCode::kUnset;
1460
1461 // Regular update attempt.
1462 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001463 case ErrorCode::kSuccess:
1464 // OK, we parsed the response successfully but that does
1465 // necessarily mean that an update is available.
1466 if (HasOutputPipe()) {
1467 const OmahaResponse& response = GetOutputObject();
1468 if (response.update_exists) {
1469 result = metrics::CheckResult::kUpdateAvailable;
1470 reaction = metrics::CheckReaction::kUpdating;
1471 } else {
1472 result = metrics::CheckResult::kNoUpdateAvailable;
1473 }
David Zeuthen33bae492014-02-25 16:16:18 -08001474 } else {
1475 result = metrics::CheckResult::kNoUpdateAvailable;
1476 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001477 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001478
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001479 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1480 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1481 result = metrics::CheckResult::kUpdateAvailable;
1482 reaction = metrics::CheckReaction::kIgnored;
1483 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001484
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001485 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1486 result = metrics::CheckResult::kUpdateAvailable;
1487 reaction = metrics::CheckReaction::kDeferring;
1488 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001489
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001490 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1491 result = metrics::CheckResult::kUpdateAvailable;
1492 reaction = metrics::CheckReaction::kBackingOff;
1493 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001494
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001495 default:
1496 // We report two flavors of errors, "Download errors" and "Parsing
1497 // error". Try to convert to the former and if that doesn't work
1498 // we know it's the latter.
1499 metrics::DownloadErrorCode tmp_error =
1500 metrics_utils::GetDownloadErrorCode(code);
1501 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1502 result = metrics::CheckResult::kDownloadError;
1503 download_error_code = tmp_error;
1504 } else {
1505 result = metrics::CheckResult::kParsingError;
1506 }
1507 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001508 }
1509
Amin Hassani538bd592020-11-04 20:46:08 -08001510 SystemState::Get()->metrics_reporter()->ReportUpdateCheckMetrics(
1511 result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001512}
1513
Toni Barzic61544e62018-10-11 14:37:30 -07001514bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1515 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001516 // Note: policy decision to not update to a version we rolled back from.
1517 string rollback_version =
Amin Hassani538bd592020-11-04 20:46:08 -08001518 SystemState::Get()->payload_state()->GetRollbackVersion();
Amin Hassani61789032020-11-13 16:20:12 -08001519 const auto* params = SystemState::Get()->request_params();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001520 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001521 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001522 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001523 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001524 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001525 return true;
1526 }
1527 }
1528
Amin Hassani538bd592020-11-04 20:46:08 -08001529 if (SystemState::Get()->hardware()->IsOOBEEnabled() &&
1530 !SystemState::Get()->hardware()->IsOOBEComplete(nullptr) &&
Toni Barzic61544e62018-10-11 14:37:30 -07001531 (response.deadline.empty() ||
Amin Hassani538bd592020-11-04 20:46:08 -08001532 SystemState::Get()->payload_state()->GetRollbackHappened()) &&
Amin Hassani61789032020-11-13 16:20:12 -08001533 params->app_version() != "ForcedUpdate") {
Toni Barzic61544e62018-10-11 14:37:30 -07001534 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1535 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1536 return true;
1537 }
1538
Weidong Guo421ff332017-04-17 10:08:38 -07001539 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001540 LOG(INFO) << "Update is not allowed over current connection.";
1541 return true;
1542 }
1543
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001544 // Currently non-critical updates always update alongside the platform update
1545 // (a critical update) so this case should never actually be hit if the
1546 // request to Omaha for updates are correct. In other words, stop the update
1547 // from happening as there are no packages in the response to process.
1548 if (response.packages.empty()) {
1549 LOG(ERROR) << "All packages were excluded.";
1550 }
1551
Chris Sosa77f79e82014-06-02 18:16:24 -07001552 // Note: We could technically delete the UpdateFirstSeenAt state when we
1553 // return true. If we do, it'll mean a device has to restart the
1554 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1555 // turned on again. On the other hand, it also increases the chance of update
1556 // starvation if an admin turns AU on/off more frequently. We choose to err on
1557 // the side of preventing starvation at the cost of not applying scattering in
1558 // those cases.
1559 return false;
1560}
1561
Weidong Guo421ff332017-04-17 10:08:38 -07001562bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1563 const OmahaResponse& response) const {
Amin Hassani538bd592020-11-04 20:46:08 -08001564 PrefsInterface* prefs = SystemState::Get()->prefs();
Weidong Guo421ff332017-04-17 10:08:38 -07001565
1566 if (!prefs) {
1567 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1568 "not available.";
1569 return false;
1570 }
1571
1572 bool is_allowed;
1573
1574 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1575 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1576 is_allowed) {
1577 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1578 "set to true.";
1579 return true;
1580 }
1581
1582 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1583 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1584 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1585 "set to false or does not exist while target does not exist.";
1586 return false;
1587 }
1588
1589 std::string target_version;
1590 int64_t target_size;
1591
1592 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1593 &target_version) ||
1594 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1595 LOG(INFO) << "Disabling updates over cellular as the target version or "
1596 "size is not accessible.";
1597 return false;
1598 }
1599
1600 uint64_t total_packages_size = 0;
1601 for (const auto& package : response.packages) {
1602 total_packages_size += package.size;
1603 }
1604 if (target_version == response.version &&
1605 static_cast<uint64_t>(target_size) == total_packages_size) {
1606 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1607 "omaha response.";
1608 return true;
1609 } else {
1610 LOG(INFO) << "Disabling updates over cellular as the target does not"
1611 "match the omaha response.";
1612 return false;
1613 }
1614}
1615
1616bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1617 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001618 ConnectionType type;
1619 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001620 ConnectionManagerInterface* connection_manager =
Amin Hassani538bd592020-11-04 20:46:08 -08001621 SystemState::Get()->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001622 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001623 LOG(INFO) << "We could not determine our connection type. "
1624 << "Defaulting to allow updates.";
1625 return true;
1626 }
Weidong Guo421ff332017-04-17 10:08:38 -07001627
Chris Sosa77f79e82014-06-02 18:16:24 -07001628 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001629 bool is_device_policy_set =
1630 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1631 // Treats tethered connection as if it is cellular connection.
1632 bool is_over_cellular = type == ConnectionType::kCellular ||
1633 tethering == ConnectionTethering::kConfirmed;
1634
1635 if (!is_over_cellular) {
1636 // There's no need to further check user preferences as we are not over
1637 // cellular connection.
1638 if (!is_allowed)
1639 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1640 } else if (is_device_policy_set) {
1641 // There's no need to further check user preferences as the device policy
1642 // is set regarding updates over cellular.
1643 if (!is_allowed)
1644 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1645 } else {
1646 // Deivce policy is not set, so user preferences overwrite whether to
1647 // allow updates over cellular.
1648 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1649 if (!is_allowed)
1650 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1651 }
1652
Chris Sosa77f79e82014-06-02 18:16:24 -07001653 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001654 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001655 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1656 return is_allowed;
1657}
1658
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001659bool OmahaRequestAction::IsRollbackEnabled() const {
1660 if (policy_provider_->IsConsumerDevice()) {
1661 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1662 return false;
1663 }
1664
1665 if (!policy_provider_->device_policy_is_loaded()) {
1666 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1667 return true;
1668 }
1669
1670 int allowed_milestones;
1671 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1672 &allowed_milestones)) {
1673 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1674 "Defaulting to rollback enabled.";
1675 return true;
1676 }
1677
1678 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1679 return allowed_milestones > 0;
1680}
1681
1682void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001683 int max_kernel_rollforward;
Amin Hassani538bd592020-11-04 20:46:08 -08001684 int min_kernel_version =
1685 SystemState::Get()->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001686 if (IsRollbackEnabled()) {
1687 // If rollback is enabled, set the max kernel key version to the current
1688 // kernel key version. This has the effect of freezing kernel key roll
1689 // forwards.
1690 //
1691 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1692 // key roll forward happens until the server side components of rollback
1693 // are implemented. Future changes will allow the Omaha server to return
1694 // the kernel key version from max_rollback_versions in the past. At that
1695 // point the max kernel key version will be set to that value, creating a
1696 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001697 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001698 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001699 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001700 } else {
1701 // For devices that are not rollback enabled (ie. consumer devices), the
1702 // max kernel key version is set to 0xfffffffe, which is logically
1703 // infinity. This maintains the previous behavior that that kernel key
1704 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001705 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001706 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001707 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001708 }
1709
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001710 bool max_rollforward_set =
Amin Hassani538bd592020-11-04 20:46:08 -08001711 SystemState::Get()->hardware()->SetMaxKernelKeyRollforward(
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001712 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001713 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001714 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001715 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001716 // Report metrics
Amin Hassani538bd592020-11-04 20:46:08 -08001717 SystemState::Get()->metrics_reporter()->ReportKeyVersionMetrics(
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001718 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001719}
1720
May Lippert60aa3ca2018-08-15 16:55:29 -07001721base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1722 Time update_first_seen_at;
1723 int64_t update_first_seen_at_int;
Amin Hassani538bd592020-11-04 20:46:08 -08001724 if (SystemState::Get()->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1725 if (SystemState::Get()->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1726 &update_first_seen_at_int)) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001727 // Note: This timestamp could be that of ANY update we saw in the past
1728 // (not necessarily this particular update we're considering to apply)
1729 // but never got to apply because of some reason (e.g. stop AU policy,
1730 // updates being pulled out from Omaha, changes in target version prefix,
1731 // new update being rolled out, etc.). But for the purposes of scattering
1732 // it doesn't matter which update the timestamp corresponds to. i.e.
1733 // the clock starts ticking the first time we see an update and we're
1734 // ready to apply when the random wait period is satisfied relative to
1735 // that first seen timestamp.
1736 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1737 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1738 << utils::ToString(update_first_seen_at);
1739 } else {
1740 // This seems like an unexpected error where the persisted value exists
1741 // but it's not readable for some reason.
1742 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1743 return base::Time();
1744 }
1745 } else {
Amin Hassani538bd592020-11-04 20:46:08 -08001746 update_first_seen_at = SystemState::Get()->clock()->GetWallclockTime();
May Lippert60aa3ca2018-08-15 16:55:29 -07001747 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Amin Hassani538bd592020-11-04 20:46:08 -08001748 if (SystemState::Get()->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1749 update_first_seen_at_int)) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001750 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1751 << utils::ToString(update_first_seen_at);
1752 } else {
1753 // This seems like an unexpected error where the value cannot be
1754 // persisted for some reason.
1755 LOG(INFO) << "UpdateFirstSeenAt value "
1756 << utils::ToString(update_first_seen_at)
1757 << " cannot be persisted";
1758 return base::Time();
1759 }
1760 }
1761 return update_first_seen_at;
1762}
1763
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001764} // namespace chromeos_update_engine