blob: 6f270c0a729c6e733d658f92064d630a1b1fe31b [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
Amin Hassani61789032020-11-13 16:20:12 -0800459 auto* params = SystemState::Get()->request_params();
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700460 OmahaRequestBuilderXml omaha_request(event_.get(),
Amin Hassani61789032020-11-13 16:20:12 -0800461 params,
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700462 ping_only_,
463 ShouldPing(), // include_ping
464 ping_active_days_,
465 ping_roll_call_days_,
Amin Hassani538bd592020-11-04 20:46:08 -0800466 GetInstallDate(),
467 SystemState::Get()->prefs(),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700468 session_id_);
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700469 string request_post = omaha_request.GetRequest();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700470
Sen Jiang42fa45e2018-03-12 11:02:14 -0700471 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700472 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
Amin Hassani61789032020-11-13 16:20:12 -0800473 params->interactive() ? "fg" : "bg");
474 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params->GetAppId());
Alex Deymo14ad88e2016-06-29 12:30:14 -0700475 http_fetcher_->SetHeader(
476 kXGoogleUpdateUpdater,
477 base::StringPrintf(
478 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
479
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800480 http_fetcher_->SetPostData(
481 request_post.data(), request_post.size(), kHttpContentTypeTextXml);
Amin Hassani61789032020-11-13 16:20:12 -0800482 LOG(INFO) << "Posting an Omaha request to " << params->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700483 LOG(INFO) << "Request: " << request_post;
Amin Hassani61789032020-11-13 16:20:12 -0800484 http_fetcher_->BeginTransfer(params->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000485}
486
Darin Petkov6a5b3222010-07-13 14:55:28 -0700487void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000488 http_fetcher_->TerminateTransfer();
489}
490
491// We just store the response in the buffer. Once we've received all bytes,
492// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700493bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800494 const void* bytes,
495 size_t length) {
496 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
497 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700498 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000499}
500
501namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000502
503// Parses a 64 bit base-10 int from a string and returns it. Returns 0
504// on error. If the string contains "0", that's indistinguishable from
505// error.
506off_t ParseInt(const string& str) {
507 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700508 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000509 if (rc < 1) {
510 // failure
511 return 0;
512 }
513 return ret;
514}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700515
David Zeuthene8ed8632014-07-24 13:38:10 -0400516// Parses |str| and returns |true| if, and only if, its value is "true".
517bool ParseBool(const string& str) {
518 return str == "true";
519}
520
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700521// Update the last ping day preferences based on the server daystart
522// response. Returns true on success, false otherwise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800523bool UpdateLastPingDays(OmahaParserData* parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700524 int64_t elapsed_seconds = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800525 TEST_AND_RETURN_FALSE(base::StringToInt64(
526 parser_data->daystart_elapsed_seconds, &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700527 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
528
529 // Remember the local time that matches the server's last midnight
530 // time.
531 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
532 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
533 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
534 return true;
535}
Sen Jiang81259682017-03-30 15:11:30 -0700536
537// Parses the package node in the given XML document and populates
538// |output_object| if valid. Returns true if we should continue the parsing.
539// False otherwise, in which case it sets any error code using |completer|.
540bool ParsePackage(OmahaParserData::App* app,
541 OmahaResponse* output_object,
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700542 bool can_exclude,
Sen Jiang81259682017-03-30 15:11:30 -0700543 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700544 if (app->updatecheck_status.empty() ||
545 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700546 if (!app->packages.empty()) {
547 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
548 completer->set_code(ErrorCode::kOmahaResponseInvalid);
549 return false;
550 }
551 return true;
552 }
553 if (app->packages.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800554 LOG(ERROR) << "Omaha Response has no packages.";
Sen Jiang81259682017-03-30 15:11:30 -0700555 completer->set_code(ErrorCode::kOmahaResponseInvalid);
556 return false;
557 }
558 if (app->url_codebase.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800559 LOG(ERROR) << "No Omaha Response URLs.";
Sen Jiang81259682017-03-30 15:11:30 -0700560 completer->set_code(ErrorCode::kOmahaResponseInvalid);
561 return false;
562 }
Sen Jiang81259682017-03-30 15:11:30 -0700563 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700564 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700565 ":",
566 base::TRIM_WHITESPACE,
567 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700568 vector<string> metadata_signatures = base::SplitString(
569 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
570 ":",
571 base::TRIM_WHITESPACE,
572 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700573 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700574 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700575 ":",
576 base::TRIM_WHITESPACE,
577 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700578 for (size_t i = 0; i < app->packages.size(); i++) {
579 const auto& package = app->packages[i];
580 if (package.name.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800581 LOG(ERROR) << "Omaha Response has empty package name.";
Sen Jiang81259682017-03-30 15:11:30 -0700582 completer->set_code(ErrorCode::kOmahaResponseInvalid);
583 return false;
584 }
Sen Jiang81259682017-03-30 15:11:30 -0700585
586 OmahaResponse::Package out_package;
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700587 out_package.app_id = app->id;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700588 out_package.can_exclude = can_exclude;
Sen Jiang81259682017-03-30 15:11:30 -0700589 for (const string& codebase : app->url_codebase) {
590 if (codebase.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800591 LOG(ERROR) << "Omaha Response URL has empty codebase.";
Sen Jiang81259682017-03-30 15:11:30 -0700592 completer->set_code(ErrorCode::kOmahaResponseInvalid);
593 return false;
594 }
595 out_package.payload_urls.push_back(codebase + package.name);
596 }
Amin Hassanida35b872020-11-04 17:54:44 -0800597
Sen Jiang81259682017-03-30 15:11:30 -0700598 // Parse the payload size.
599 base::StringToUint64(package.size, &out_package.size);
600 if (out_package.size <= 0) {
601 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
602 completer->set_code(ErrorCode::kOmahaResponseInvalid);
603 return false;
604 }
Sen Jiang81259682017-03-30 15:11:30 -0700605
606 if (i < metadata_sizes.size())
607 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
Sen Jiang81259682017-03-30 15:11:30 -0700608
609 if (i < metadata_signatures.size())
610 out_package.metadata_signature = metadata_signatures[i];
Sen Jiang81259682017-03-30 15:11:30 -0700611
612 out_package.hash = package.hash;
613 if (out_package.hash.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800614 LOG(ERROR) << "Omaha Response has empty hash_sha256 value.";
Sen Jiang81259682017-03-30 15:11:30 -0700615 completer->set_code(ErrorCode::kOmahaResponseInvalid);
616 return false;
617 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700618
Vyshu Khota4c5413d2020-11-04 16:17:25 -0800619 out_package.fp = package.fp;
620
Sen Jiangcdd52062017-05-18 15:33:10 -0700621 if (i < is_delta_payloads.size())
622 out_package.is_delta = ParseBool(is_delta_payloads[i]);
Sen Jiangcdd52062017-05-18 15:33:10 -0700623
Sen Jiang81259682017-03-30 15:11:30 -0700624 output_object->packages.push_back(std::move(out_package));
625 }
626
627 return true;
628}
629
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700630// Removes the candidate URLs which are excluded within packages, if all the
631// candidate URLs are excluded within a package, the package will be excluded.
632void ProcessExclusions(OmahaResponse* output_object,
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700633 OmahaRequestParams* params,
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700634 ExcluderInterface* excluder) {
635 for (auto package_it = output_object->packages.begin();
636 package_it != output_object->packages.end();
637 /* Increment logic in loop */) {
638 // If package cannot be excluded, quickly continue.
639 if (!package_it->can_exclude) {
640 ++package_it;
641 continue;
642 }
643 // Remove the excluded payload URLs.
644 for (auto payload_url_it = package_it->payload_urls.begin();
645 payload_url_it != package_it->payload_urls.end();
646 /* Increment logic in loop */) {
647 auto exclusion_name = utils::GetExclusionName(*payload_url_it);
648 // If payload URL is not excluded, quickly continue.
649 if (!excluder->IsExcluded(exclusion_name)) {
650 ++payload_url_it;
651 continue;
652 }
653 LOG(INFO) << "Excluding payload URL=" << *payload_url_it
654 << " for payload hash=" << package_it->hash;
655 payload_url_it = package_it->payload_urls.erase(payload_url_it);
656 }
657 // If there are no candidate payload URLs, remove the package.
658 if (package_it->payload_urls.empty()) {
659 LOG(INFO) << "Excluding payload hash=" << package_it->hash;
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700660 // Need to set DLC as not updated so correct metrics can be sent when an
661 // update is completed.
662 params->SetDlcNoUpdate(package_it->app_id);
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700663 package_it = output_object->packages.erase(package_it);
664 continue;
665 }
666 ++package_it;
667 }
668}
669
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700670// Parses the 2 key version strings kernel_version and firmware_version. If the
671// field is not present, or cannot be parsed the values default to 0xffff.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700672void ParseRollbackVersions(int allowed_milestones,
673 OmahaParserData* parser_data,
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700674 OmahaResponse* output_object) {
675 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700676 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700677 &output_object->rollback_key_version.firmware_key,
678 &output_object->rollback_key_version.firmware);
679 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700680 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700681 &output_object->rollback_key_version.kernel_key,
682 &output_object->rollback_key_version.kernel);
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700683
684 // Create the attribute name strings for milestone N - allowed_milestones.
685 const string firmware_max_rollforward_attr =
686 base::StringPrintf("%s_%i", kAttrFirmwareVersion, allowed_milestones);
687 const string kernel_max_rollforward_attr =
688 base::StringPrintf("%s_%i", kAttrKernelVersion, allowed_milestones);
689
690 const bool max_firmware_and_kernel_exist =
691 parser_data->updatecheck_attrs.count(firmware_max_rollforward_attr) > 0 &&
692 parser_data->updatecheck_attrs.count(kernel_max_rollforward_attr) > 0;
693
694 string firmware_version;
695 string kernel_version;
696 if (max_firmware_and_kernel_exist) {
697 firmware_version =
698 parser_data->updatecheck_attrs[firmware_max_rollforward_attr];
699 kernel_version =
700 parser_data->updatecheck_attrs[kernel_max_rollforward_attr];
701 }
702
703 LOG(INFO) << "For milestone N-" << allowed_milestones
704 << " firmware_key_version=" << firmware_version
705 << " kernel_key_version=" << kernel_version;
706
707 OmahaResponse::RollbackKeyVersion version;
708 utils::ParseRollbackKeyVersion(
709 firmware_version, &version.firmware_key, &version.firmware);
710 utils::ParseRollbackKeyVersion(
711 kernel_version, &version.kernel_key, &version.kernel);
712
713 output_object->past_rollback_key_version = std::move(version);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700714}
715
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700716} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000717
David Zeuthene8ed8632014-07-24 13:38:10 -0400718bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700719 OmahaResponse* output_object,
720 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700721 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700722 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700723 return false;
724 }
725
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800726 // chromium-os:37289: The PollInterval is not supported by Omaha server
727 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700728 // slow down the request rate from the server-side. Note that the PollInterval
729 // is not persisted, so it has to be sent by the server on every response to
730 // guarantee that the scheduler uses this value (otherwise, if the device got
731 // rebooted after the last server-indicated value, it'll revert to the default
732 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
733 // based on the assumption that we perform an update check every hour so that
734 // the max value of 8 will roughly be equivalent to one work day. If we decide
735 // to use PollInterval permanently, we should update the
736 // max_update_checks_allowed to take PollInterval into account. Note: The
737 // parsing for PollInterval happens even before parsing of the status because
738 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400739 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700740 &output_object->poll_interval);
741
David Zeuthen639aa362014-02-03 16:23:44 -0800742 // Check for the "elapsed_days" attribute in the "daystart"
743 // element. This is the number of days since Jan 1 2007, 0:00
744 // PST. If we don't have a persisted value of the Omaha InstallDate,
745 // we'll use it to calculate it and then persist it.
Amin Hassani538bd592020-11-04 20:46:08 -0800746 if (ParseInstallDate(parser_data, output_object) && !HasInstallDate()) {
David Zeuthen639aa362014-02-03 16:23:44 -0800747 // Since output_object->install_date_days is never negative, the
748 // elapsed_days -> install-date calculation is reduced to simply
749 // rounding down to the nearest number divisible by 7.
750 int remainder = output_object->install_date_days % 7;
751 int install_date_days_rounded =
752 output_object->install_date_days - remainder;
Amin Hassani538bd592020-11-04 20:46:08 -0800753 if (PersistInstallDate(install_date_days_rounded,
David Zeuthen639aa362014-02-03 16:23:44 -0800754 kProvisionedFromOmahaResponse)) {
755 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
Amin Hassanida35b872020-11-04 17:54:44 -0800756 << install_date_days_rounded << " days.";
David Zeuthen639aa362014-02-03 16:23:44 -0800757 }
758 }
759
Alex Deymo00d79ac2015-06-29 15:41:49 -0700760 // We persist the cohorts sent by omaha even if the status is "noupdate".
Jae Hoon Kime2cac612020-11-02 18:30:29 -0800761 PersistCohorts(*parser_data);
Alex Deymo00d79ac2015-06-29 15:41:49 -0700762
Amin Hassani2cbb0692019-10-30 13:36:17 -0700763 PersistEolInfo(parser_data->updatecheck_attrs);
764
Marton Hunyady199152d2018-05-07 19:08:48 +0200765 // Rollback-related updatecheck attributes.
766 // Defaults to false if attribute is not present.
767 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -0700768 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700769
Amin Hassani61789032020-11-13 16:20:12 -0800770 const auto* params = SystemState::Get()->request_params();
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700771 // Parses the rollback versions of the current image. If the fields do not
772 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700773 ParseRollbackVersions(
Amin Hassani61789032020-11-13 16:20:12 -0800774 params->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -0700775
David Zeuthene8ed8632014-07-24 13:38:10 -0400776 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700777 return false;
778
David Zeuthene8ed8632014-07-24 13:38:10 -0400779 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700780 return false;
781
Sen Jiang0affc2c2017-02-10 15:55:05 -0800782 // Package has to be parsed after Params now because ParseParams need to make
783 // sure that postinstall action exists.
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700784 for (auto& app : parser_data->apps) {
785 // Only allow exclusions for a non-critical package during an update. For
786 // non-critical package installations, let the errors propagate instead
787 // of being handled inside update_engine as installations are a dlcservice
788 // specific feature.
Amin Hassani61789032020-11-13 16:20:12 -0800789 bool can_exclude = !params->is_install() && params->IsDlcAppId(app.id);
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700790 if (!ParsePackage(&app, output_object, can_exclude, completer))
Sen Jiang81259682017-03-30 15:11:30 -0700791 return false;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700792 }
Sen Jiang0affc2c2017-02-10 15:55:05 -0800793
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700794 return true;
795}
796
David Zeuthene8ed8632014-07-24 13:38:10 -0400797bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700798 OmahaResponse* output_object,
799 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700800 output_object->update_exists = false;
Amin Hassani61789032020-11-13 16:20:12 -0800801 auto* params = SystemState::Get()->request_params();
Xiaochu Liu6310be62018-10-11 15:09:03 -0700802 for (const auto& app : parser_data->apps) {
803 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -0700804 if (status == kValNoUpdate) {
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800805 // If the app is a DLC, allow status "noupdate" to support DLC
806 // deprecations.
Amin Hassani61789032020-11-13 16:20:12 -0800807 if (params->IsDlcAppId(app.id)) {
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800808 LOG(INFO) << "No update for <app> " << app.id
809 << " but update continuing since a DLC.";
Amin Hassani61789032020-11-13 16:20:12 -0800810 params->SetDlcNoUpdate(app.id);
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800811 continue;
812 }
Sen Jiang00adf7b2017-06-26 15:57:29 -0700813 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -0700814 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700815 output_object->update_exists = false;
816 break;
Sen Jiang81259682017-03-30 15:11:30 -0700817 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700818 auto const& attr_no_update =
819 app.action_postinstall_attrs.find(kAttrNoUpdate);
820 if (attr_no_update != app.action_postinstall_attrs.end() &&
821 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700822 // noupdate="true" in postinstall attributes means it's an update to
823 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -0700824 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700825 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700826 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700827 output_object->update_exists = true;
828 }
Amin Hassani61789032020-11-13 16:20:12 -0800829 } else if (status.empty() && params->is_install() &&
830 params->GetAppId() == app.id) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700831 // Skips the platform app for install operation.
832 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -0700833 } else {
834 LOG(ERROR) << "Unknown Omaha response status: " << status;
835 completer->set_code(ErrorCode::kOmahaResponseInvalid);
836 return false;
837 }
838 }
839 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700840 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700841 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700842 }
843
Sen Jiang81259682017-03-30 15:11:30 -0700844 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700845}
846
David Zeuthene8ed8632014-07-24 13:38:10 -0400847bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700848 OmahaResponse* output_object,
849 ScopedActionCompleter* completer) {
Amin Hassani61789032020-11-13 16:20:12 -0800850 const auto* params = SystemState::Get()->request_params();
Sen Jiang81259682017-03-30 15:11:30 -0700851 map<string, string> attrs;
852 for (auto& app : parser_data->apps) {
Amin Hassani61789032020-11-13 16:20:12 -0800853 if (app.id == params->GetAppId()) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700854 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -0700855 output_object->version = app.manifest_version;
Amin Hassani61789032020-11-13 16:20:12 -0800856 } else if (params->is_install() &&
857 app.manifest_version != params->app_version()) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700858 LOG(WARNING) << "An app has a different version (" << app.manifest_version
859 << ") that is different than platform app version ("
Amin Hassani61789032020-11-13 16:20:12 -0800860 << params->app_version() << ").";
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700861 }
862 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700863 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700864 }
Sen Jiang81259682017-03-30 15:11:30 -0700865 }
Amin Hassani61789032020-11-13 16:20:12 -0800866 if (params->is_install()) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700867 LOG(INFO) << "Use request version for Install operation.";
Amin Hassani61789032020-11-13 16:20:12 -0800868 output_object->version = params->app_version();
Xiaochu Liu6310be62018-10-11 15:09:03 -0700869 }
Chris Sosa3b748432013-06-20 16:42:59 -0700870 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700871 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700872 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700873 return false;
874 }
875
David Zeuthene8ed8632014-07-24 13:38:10 -0400876 if (attrs.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800877 LOG(ERROR) << "Omaha Response has no postinstall event action.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700878 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700879 return false;
880 }
881
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800882 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -0700883 output_object->more_info_url = attrs[kAttrMoreInfo];
884 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
885 output_object->deadline = attrs[kAttrDeadline];
886 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700887 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -0700888 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700889 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -0700890 ParseBool(attrs[kAttrDisableP2PForSharing]);
891 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800892
Amin Hassani6600a562018-09-24 15:17:19 -0700893 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800894 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800895 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700896
Jay Srinivasan08262882012-12-28 19:29:43 -0800897 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -0700898 ParseBool(attrs[kAttrDisablePayloadBackoff]);
899 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800900
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700901 return true;
902}
903
David Zeuthene8ed8632014-07-24 13:38:10 -0400904// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000905// and fill in the appropriate fields of the output object. Also, notifies
906// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800907void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -0700908 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000909 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800910 string current_response(response_buffer_.begin(), response_buffer_.end());
911 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700912
Amin Hassani538bd592020-11-04 20:46:08 -0800913 PayloadStateInterface* const payload_state =
914 SystemState::Get()->payload_state();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700915
Zentaro Kavanagh76af2662018-05-15 10:54:53 -0700916 // Set the max kernel key version based on whether rollback is allowed.
917 SetMaxKernelKeyVersionForRollback();
918
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700919 // Events are best effort transactions -- assume they always succeed.
920 if (IsEvent()) {
921 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700922 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700923 return;
924 }
925
Amin Hassanid3d84212019-08-17 00:27:44 -0700926 ErrorCode aux_error_code = fetcher->GetAuxiliaryErrorCode();
927 if (aux_error_code != ErrorCode::kSuccess) {
928 metrics::DownloadErrorCode download_error_code =
929 metrics_utils::GetDownloadErrorCode(aux_error_code);
Amin Hassani538bd592020-11-04 20:46:08 -0800930 SystemState::Get()->metrics_reporter()->ReportUpdateCheckMetrics(
Amin Hassanid3d84212019-08-17 00:27:44 -0700931 metrics::CheckResult::kUnset,
932 metrics::CheckReaction::kUnset,
933 download_error_code);
934 }
935
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700936 if (!successful) {
Darin Petkovedc522e2010-11-05 09:35:17 -0700937 int code = GetHTTPResponseCode();
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700938 LOG(ERROR) << "Omaha request network transfer failed with HTTPResponseCode="
939 << code;
Saint Chou6431c332020-07-29 14:04:14 +0000940 // Makes sure we send proper error values.
Darin Petkovedc522e2010-11-05 09:35:17 -0700941 if (code < 0 || code >= 1000) {
942 code = 999;
Saint Chou6431c332020-07-29 14:04:14 +0000943 LOG(WARNING) << "Converting to proper HTTPResponseCode=" << code;
Darin Petkovedc522e2010-11-05 09:35:17 -0700944 }
David Zeuthena99981f2013-04-29 13:42:47 -0700945 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700946 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000947 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700948 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000949
David Zeuthene8ed8632014-07-24 13:38:10 -0400950 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400951 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400952 XML_SetUserData(parser, &parser_data);
953 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400954 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800955 XML_Status res =
956 XML_Parse(parser,
957 reinterpret_cast<const char*>(response_buffer_.data()),
958 response_buffer_.size(),
959 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400960
961 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700962 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800963 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
964 << XML_GetCurrentLineNumber(parser) << " col "
965 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -0700966 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400967 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
968 if (response_buffer_.empty()) {
969 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
970 } else if (parser_data.entity_decl) {
971 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
972 }
973 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000974 return;
975 }
Amin Hassani91f48b42018-08-06 17:47:14 -0700976 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000977
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700978 // Update the last ping day preferences based on the server daystart response
979 // even if we didn't send a ping. Omaha always includes the daystart in the
980 // response, but log the error if it didn't.
Amin Hassani538bd592020-11-04 20:46:08 -0800981 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, SystemState::Get()->prefs()))
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700982 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700983
Amin Hassani1677e812017-06-21 13:36:36 -0700984 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
985 // we have got a response from omaha and if its value has never been set to
986 // true before. Failure of this function should be ignored. There should be no
987 // need to check if a=-1 has been sent because older devices have already sent
988 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
989 // future checks.
Amin Hassani538bd592020-11-04 20:46:08 -0800990 if (!SystemState::Get()->hardware()->GetFirstActiveOmahaPingSent()) {
991 if (!SystemState::Get()->hardware()->SetFirstActiveOmahaPingSent()) {
992 SystemState::Get()->metrics_reporter()->ReportInternalErrorCode(
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700993 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
994 }
Amin Hassani1677e812017-06-21 13:36:36 -0700995 }
996
Andrewe045aef2020-01-08 16:29:22 -0800997 // Create/update the metadata files for each DLC app received.
998 StorePingReply(parser_data);
999
Thieu Le116fda32011-04-19 11:01:54 -07001000 if (!HasOutputPipe()) {
1001 // Just set success to whether or not the http transfer succeeded,
1002 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001003 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001004 return;
1005 }
1006
Darin Petkov6a5b3222010-07-13 14:55:28 -07001007 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001008 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001009 return;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001010 ProcessExclusions(&output_object,
Amin Hassani538bd592020-11-04 20:46:08 -08001011 SystemState::Get()->request_params(),
1012 SystemState::Get()->update_attempter()->GetExcluder());
David Zeuthen8f191b22013-08-06 12:27:50 -07001013 output_object.update_exists = true;
1014 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001015
Toni Barzic61544e62018-10-11 14:37:30 -07001016 LoadOrPersistUpdateFirstSeenAtPref();
1017
Weidong Guo421ff332017-04-17 10:08:38 -07001018 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -07001019 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -07001020 // No need to change output_object.update_exists here, since the value
1021 // has been output to the pipe.
1022 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001023 return;
1024 }
1025
David Zeuthen8f191b22013-08-06 12:27:50 -07001026 // If Omaha says to disable p2p, respect that
1027 if (output_object.disable_p2p_for_downloading) {
1028 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1029 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001030 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001031 }
1032 if (output_object.disable_p2p_for_sharing) {
1033 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1034 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001035 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001036 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001037
1038 // Update the payload state with the current response. The payload state
1039 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001040 // from what's stored already. We are updating the payload state as late
1041 // as possible in this method so that if a new release gets pushed and then
1042 // got pulled back due to some issues, we don't want to clear our internal
1043 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001044 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001045
David Zeuthen8f191b22013-08-06 12:27:50 -07001046 // It could be we've already exceeded the deadline for when p2p is
1047 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001048 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001049 payload_state->P2PNewAttempt();
1050 if (!payload_state->P2PAttemptAllowed()) {
1051 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1052 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001053 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001054 }
1055 }
1056
1057 // From here on, we'll complete stuff in CompleteProcessing() so
1058 // disable |completer| since we'll create a new one in that
1059 // function.
1060 completer.set_should_complete(false);
1061
1062 // If we're allowed to use p2p for downloading we do not pay
1063 // attention to wall-clock-based waiting if the URL is indeed
1064 // available via p2p. Therefore, check if the file is available via
1065 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001066 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001067 LookupPayloadViaP2P(output_object);
1068 } else {
1069 CompleteProcessing();
1070 }
1071}
1072
1073void OmahaRequestAction::CompleteProcessing() {
1074 ScopedActionCompleter completer(processor_, this);
1075 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
Amin Hassani538bd592020-11-04 20:46:08 -08001076 PayloadStateInterface* payload_state = SystemState::Get()->payload_state();
David Zeuthen8f191b22013-08-06 12:27:50 -07001077
1078 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001079 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001080 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001081 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001082 return;
1083 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001084
Chris Sosa20f005c2013-09-05 13:53:08 -07001085 if (payload_state->ShouldBackoffDownload()) {
1086 output_object.update_exists = false;
1087 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
Amin Hassanida35b872020-11-04 17:54:44 -08001088 << "attempts.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001089 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001090 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001091 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001092 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001093}
1094
1095void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1096 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1097 if (!url.empty()) {
Amin Hassani538bd592020-11-04 20:46:08 -08001098 SystemState::Get()->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001099 } else {
1100 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1101 << "because no suitable peer could be found.";
Amin Hassani538bd592020-11-04 20:46:08 -08001102 SystemState::Get()->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001103 }
1104 CompleteProcessing();
1105}
1106
1107void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001108 // If the device is in the middle of an update, the state variables
1109 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1110 // tracks the offset and length of the operation currently in
1111 // progress. The offset is based from the end of the manifest which
1112 // is kPrefsManifestMetadataSize bytes long.
1113 //
1114 // To make forward progress and avoid deadlocks, we need to find a
1115 // peer that has at least the entire operation we're currently
1116 // working on. Otherwise we may end up in a situation where two
1117 // devices bounce back and forth downloading from each other,
1118 // neither making any forward progress until one of them decides to
1119 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1120 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001121 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001122 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001123 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001124 int64_t next_data_offset = 0;
1125 int64_t next_data_length = 0;
Amin Hassani538bd592020-11-04 20:46:08 -08001126 if (SystemState::Get()->prefs()->GetInt64(kPrefsManifestMetadataSize,
1127 &manifest_metadata_size) &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001128 manifest_metadata_size != -1 &&
Amin Hassani538bd592020-11-04 20:46:08 -08001129 SystemState::Get()->prefs()->GetInt64(kPrefsManifestSignatureSize,
1130 &manifest_signature_size) &&
Alex Deymof25eb492016-02-26 00:20:08 -08001131 manifest_signature_size != -1 &&
Amin Hassani538bd592020-11-04 20:46:08 -08001132 SystemState::Get()->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
1133 &next_data_offset) &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001134 next_data_offset != -1 &&
Amin Hassani538bd592020-11-04 20:46:08 -08001135 SystemState::Get()->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1136 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001137 minimum_size = manifest_metadata_size + manifest_signature_size +
1138 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001139 }
1140
Sen Jiang0affc2c2017-02-10 15:55:05 -08001141 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001142 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001143 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001144 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001145 string file_id =
1146 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Amin Hassani538bd592020-11-04 20:46:08 -08001147 if (SystemState::Get()->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001148 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1149 << " minimum_size=" << minimum_size;
Amin Hassani538bd592020-11-04 20:46:08 -08001150 SystemState::Get()->p2p_manager()->LookupUrlForFile(
David Zeuthen8f191b22013-08-06 12:27:50 -07001151 file_id,
1152 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001153 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001154 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1155 base::Unretained(this)));
1156 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001157}
1158
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001159bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Amin Hassani61789032020-11-13 16:20:12 -08001160 const auto* params = SystemState::Get()->request_params();
1161 if (params->interactive()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001162 LOG(INFO) << "Not deferring download because update is interactive.";
1163 return false;
1164 }
1165
David Zeuthen8f191b22013-08-06 12:27:50 -07001166 // If we're using p2p to download _and_ we have a p2p URL, we never
1167 // defer the download. This is because the download will always
1168 // happen from a peer on the LAN and we've been waiting in line for
1169 // our turn.
Amin Hassani538bd592020-11-04 20:46:08 -08001170 const PayloadStateInterface* payload_state =
1171 SystemState::Get()->payload_state();
Gilad Arnold74b5f552014-10-07 08:17:16 -07001172 if (payload_state->GetUsingP2PForDownloading() &&
1173 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001174 LOG(INFO) << "Download not deferred because download "
1175 << "will happen from a local peer (via p2p).";
1176 return false;
1177 }
1178
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001179 // We should defer the downloads only if we've first satisfied the
1180 // wall-clock-based-waiting period and then the update-check-based waiting
1181 // period, if required.
Amin Hassani61789032020-11-13 16:20:12 -08001182 if (!params->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001183 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1184 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001185 return false;
1186 }
1187
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001188 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001189 case kWallClockWaitNotSatisfied:
1190 // We haven't even satisfied the first condition, passing the
1191 // wall-clock-based waiting period, so we should defer the downloads
1192 // until that happens.
1193 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1194 return true;
1195
1196 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1197 LOG(INFO) << "wall-clock-based-wait satisfied and "
1198 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001199 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001200
1201 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1202 // Wall-clock-based waiting period is satisfied, and it's determined
1203 // that we do not need the update-check-based wait. so no need to
1204 // defer downloads.
1205 LOG(INFO) << "wall-clock-based-wait satisfied and "
1206 << "update-check-based-wait is not required.";
1207 return false;
1208
1209 default:
1210 // Returning false for this default case so we err on the
1211 // side of downloading updates than deferring in case of any bugs.
1212 NOTREACHED();
1213 return false;
1214 }
1215}
1216
1217OmahaRequestAction::WallClockWaitResult
1218OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001219 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001220 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1221 if (update_first_seen_at == base::Time()) {
1222 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
Amin Hassanida35b872020-11-04 17:54:44 -08001223 "persisted.";
May Lippert60aa3ca2018-08-15 16:55:29 -07001224 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001225 }
1226
Sen Jiang7c1171e2016-06-23 11:35:40 -07001227 TimeDelta elapsed_time =
Amin Hassani538bd592020-11-04 20:46:08 -08001228 SystemState::Get()->clock()->GetWallclockTime() - update_first_seen_at;
Sen Jiang7c1171e2016-06-23 11:35:40 -07001229 TimeDelta max_scatter_period =
1230 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001231 int64_t staging_wait_time_in_days = 0;
1232 // Use staging and its default max value if staging is on.
Amin Hassani538bd592020-11-04 20:46:08 -08001233 if (SystemState::Get()->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1234 &staging_wait_time_in_days) &&
Adolfo Victoria497044c2018-07-18 07:51:42 -07001235 staging_wait_time_in_days > 0)
1236 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001237
Amin Hassani61789032020-11-13 16:20:12 -08001238 const auto* params = SystemState::Get()->request_params();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001239 LOG(INFO) << "Waiting Period = "
Amin Hassani61789032020-11-13 16:20:12 -08001240 << utils::FormatSecs(params->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001241 << ", Time Elapsed = "
1242 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001243 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001244
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001245 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001246 // The deadline is set for all rules which serve a delta update from a
1247 // previous FSI, which means this update will be applied mostly in OOBE
1248 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1249 // quickly.
Amin Hassanida35b872020-11-04 17:54:44 -08001250 LOG(INFO) << "Not scattering as deadline flag is set.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001251 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1252 }
1253
1254 if (max_scatter_period.InDays() == 0) {
1255 // This means the Omaha rule creator decides that this rule
1256 // should not be scattered irrespective of the policy.
1257 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1258 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1259 }
1260
1261 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001262 // This means we've waited more than the upperbound wait in the rule
1263 // from the time we first saw a valid update available to us.
1264 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001265 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1266 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1267 }
1268
1269 // This means we are required to participate in scattering.
1270 // See if our turn has arrived now.
Amin Hassani61789032020-11-13 16:20:12 -08001271 TimeDelta remaining_wait_time = params->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001272 if (remaining_wait_time.InSeconds() <= 0) {
1273 // Yes, it's our turn now.
1274 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1275
1276 // But we can't download until the update-check-count-based wait is also
1277 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani61789032020-11-13 16:20:12 -08001278 return params->update_check_count_wait_enabled()
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001279 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1280 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001281 }
1282
1283 // Not our turn yet, so we have to wait until our turn to
1284 // help scatter the downloads across all clients of the enterprise.
1285 LOG(INFO) << "Update deferred for another "
1286 << utils::FormatSecs(remaining_wait_time.InSeconds())
1287 << " per policy.";
1288 return kWallClockWaitNotSatisfied;
1289}
1290
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001291bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001292 int64_t update_check_count_value;
Amin Hassani61789032020-11-13 16:20:12 -08001293 const auto* params = SystemState::Get()->request_params();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001294
Amin Hassani538bd592020-11-04 20:46:08 -08001295 if (SystemState::Get()->prefs()->Exists(kPrefsUpdateCheckCount)) {
1296 if (!SystemState::Get()->prefs()->GetInt64(kPrefsUpdateCheckCount,
1297 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001298 // We are unable to read the update check count from file for some reason.
1299 // So let's proceed anyway so as to not stall the update.
1300 LOG(ERROR) << "Unable to read update check count. "
1301 << "Skipping update-check-count-based-wait.";
1302 return true;
1303 }
1304 } else {
1305 // This file does not exist. This means we haven't started our update
1306 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001307 update_check_count_value =
Amin Hassani61789032020-11-13 16:20:12 -08001308 base::RandInt(params->min_update_checks_needed(),
1309 params->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001310
1311 LOG(INFO) << "Randomly picked update check count value = "
1312 << update_check_count_value;
1313
1314 // Write out the initial value of update_check_count_value.
Amin Hassani538bd592020-11-04 20:46:08 -08001315 if (!SystemState::Get()->prefs()->SetInt64(kPrefsUpdateCheckCount,
1316 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001317 // We weren't able to write the update check count file for some reason.
1318 // So let's proceed anyway so as to not stall the update.
1319 LOG(ERROR) << "Unable to write update check count. "
1320 << "Skipping update-check-count-based-wait.";
1321 return true;
1322 }
1323 }
1324
1325 if (update_check_count_value == 0) {
1326 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1327 return true;
1328 }
1329
1330 if (update_check_count_value < 0 ||
Amin Hassani61789032020-11-13 16:20:12 -08001331 update_check_count_value > params->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001332 // We err on the side of skipping scattering logic instead of stalling
1333 // a machine from receiving any updates in case of any unexpected state.
1334 LOG(ERROR) << "Invalid value for update check count detected. "
1335 << "Skipping update-check-count-based-wait.";
1336 return true;
1337 }
1338
1339 // Legal value, we need to wait for more update checks to happen
1340 // until this becomes 0.
1341 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001342 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001343 return false;
1344}
1345
David Zeuthen639aa362014-02-03 16:23:44 -08001346// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001347bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001348 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001349 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001350 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001351 return false;
1352
1353 if (elapsed_days < 0)
1354 return false;
1355
1356 output_object->install_date_days = elapsed_days;
1357 return true;
1358}
1359
1360// static
Amin Hassani538bd592020-11-04 20:46:08 -08001361bool OmahaRequestAction::HasInstallDate() {
1362 PrefsInterface* prefs = SystemState::Get()->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001363 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001364 return false;
1365
1366 return prefs->Exists(kPrefsInstallDateDays);
1367}
1368
1369// static
1370bool OmahaRequestAction::PersistInstallDate(
David Zeuthen639aa362014-02-03 16:23:44 -08001371 int install_date_days,
1372 InstallDateProvisioningSource source) {
1373 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1374
Amin Hassani538bd592020-11-04 20:46:08 -08001375 PrefsInterface* prefs = SystemState::Get()->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001376 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001377 return false;
1378
1379 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1380 return false;
1381
Amin Hassani538bd592020-11-04 20:46:08 -08001382 SystemState::Get()->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001383 static_cast<int>(source), // Sample.
1384 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001385 return true;
1386}
1387
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001388void OmahaRequestAction::PersistCohortData(const string& prefs_key,
1389 const Optional<string>& new_value) {
1390 if (!new_value)
1391 return;
1392 const string& value = new_value.value();
Amin Hassani538bd592020-11-04 20:46:08 -08001393 if (value.empty() && SystemState::Get()->prefs()->Exists(prefs_key)) {
1394 if (!SystemState::Get()->prefs()->Delete(prefs_key))
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001395 LOG(ERROR) << "Failed to remove stored " << prefs_key << "value.";
1396 else
1397 LOG(INFO) << "Removed stored " << prefs_key << " value.";
1398 } else if (!value.empty()) {
Amin Hassani538bd592020-11-04 20:46:08 -08001399 if (!SystemState::Get()->prefs()->SetString(prefs_key, value))
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001400 LOG(INFO) << "Failed to store new setting " << prefs_key << " as "
1401 << value;
1402 else
1403 LOG(INFO) << "Stored cohort setting " << prefs_key << " as " << value;
Alex Deymo8e18f932015-03-27 16:16:59 -07001404 }
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001405}
1406
1407void OmahaRequestAction::PersistCohorts(const OmahaParserData& parser_data) {
Amin Hassani61789032020-11-13 16:20:12 -08001408 const auto* params = SystemState::Get()->request_params();
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001409 for (const auto& app : parser_data.apps) {
1410 // For platform App ID.
Amin Hassani61789032020-11-13 16:20:12 -08001411 if (app.id == params->GetAppId()) {
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001412 PersistCohortData(kPrefsOmahaCohort, app.cohort);
1413 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
1414 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
Amin Hassani61789032020-11-13 16:20:12 -08001415 } else if (params->IsDlcAppId(app.id)) {
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001416 string dlc_id;
Amin Hassani61789032020-11-13 16:20:12 -08001417 if (!params->GetDlcId(app.id, &dlc_id)) {
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001418 LOG(WARNING) << "Skip persisting cohorts for DLC App ID=" << app.id
1419 << " as it is not in the request params.";
1420 continue;
1421 }
Amin Hassani538bd592020-11-04 20:46:08 -08001422 PrefsInterface* prefs = SystemState::Get()->prefs();
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001423 PersistCohortData(
1424 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohort}),
1425 app.cohort);
1426 PersistCohortData(
1427 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohortName}),
1428 app.cohortname);
1429 PersistCohortData(
1430 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohortHint}),
1431 app.cohorthint);
1432 } else {
1433 LOG(WARNING) << "Skip persisting cohorts for unknown App ID=" << app.id;
1434 }
1435 }
Alex Deymo8e18f932015-03-27 16:16:59 -07001436}
1437
Amin Hassani2cbb0692019-10-30 13:36:17 -07001438bool OmahaRequestAction::PersistEolInfo(const map<string, string>& attrs) {
Jae Hoon Kimb3146742019-11-07 13:24:24 -08001439 // If EOL date attribute is not sent, don't delete the old persisted EOL
1440 // date information.
Jae Hoon Kim051627a2019-09-03 12:56:32 -07001441 auto eol_date_attr = attrs.find(kAttrEolDate);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07001442 if (eol_date_attr != attrs.end()) {
1443 const auto& eol_date = eol_date_attr->second;
Amin Hassani538bd592020-11-04 20:46:08 -08001444 if (!SystemState::Get()->prefs()->SetString(kPrefsOmahaEolDate, eol_date)) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07001445 LOG(ERROR) << "Setting EOL date failed.";
1446 return false;
1447 }
1448 LOG(INFO) << "Set EOL date to " << eol_date;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001449 }
Amin Hassani2cbb0692019-10-30 13:36:17 -07001450 return true;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001451}
1452
David Zeuthen33bae492014-02-25 16:16:18 -08001453void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1454 // We only want to report this on "update check".
1455 if (ping_only_ || event_ != nullptr)
1456 return;
1457
1458 metrics::CheckResult result = metrics::CheckResult::kUnset;
1459 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1460 metrics::DownloadErrorCode download_error_code =
1461 metrics::DownloadErrorCode::kUnset;
1462
1463 // Regular update attempt.
1464 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001465 case ErrorCode::kSuccess:
1466 // OK, we parsed the response successfully but that does
1467 // necessarily mean that an update is available.
1468 if (HasOutputPipe()) {
1469 const OmahaResponse& response = GetOutputObject();
1470 if (response.update_exists) {
1471 result = metrics::CheckResult::kUpdateAvailable;
1472 reaction = metrics::CheckReaction::kUpdating;
1473 } else {
1474 result = metrics::CheckResult::kNoUpdateAvailable;
1475 }
David Zeuthen33bae492014-02-25 16:16:18 -08001476 } else {
1477 result = metrics::CheckResult::kNoUpdateAvailable;
1478 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001479 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001480
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001481 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1482 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1483 result = metrics::CheckResult::kUpdateAvailable;
1484 reaction = metrics::CheckReaction::kIgnored;
1485 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001486
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001487 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1488 result = metrics::CheckResult::kUpdateAvailable;
1489 reaction = metrics::CheckReaction::kDeferring;
1490 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001491
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001492 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1493 result = metrics::CheckResult::kUpdateAvailable;
1494 reaction = metrics::CheckReaction::kBackingOff;
1495 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001496
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001497 default:
1498 // We report two flavors of errors, "Download errors" and "Parsing
1499 // error". Try to convert to the former and if that doesn't work
1500 // we know it's the latter.
1501 metrics::DownloadErrorCode tmp_error =
1502 metrics_utils::GetDownloadErrorCode(code);
1503 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1504 result = metrics::CheckResult::kDownloadError;
1505 download_error_code = tmp_error;
1506 } else {
1507 result = metrics::CheckResult::kParsingError;
1508 }
1509 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001510 }
1511
Amin Hassani538bd592020-11-04 20:46:08 -08001512 SystemState::Get()->metrics_reporter()->ReportUpdateCheckMetrics(
1513 result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001514}
1515
Toni Barzic61544e62018-10-11 14:37:30 -07001516bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1517 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001518 // Note: policy decision to not update to a version we rolled back from.
1519 string rollback_version =
Amin Hassani538bd592020-11-04 20:46:08 -08001520 SystemState::Get()->payload_state()->GetRollbackVersion();
Amin Hassani61789032020-11-13 16:20:12 -08001521 const auto* params = SystemState::Get()->request_params();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001522 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001523 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001524 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001525 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001526 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001527 return true;
1528 }
1529 }
1530
Amin Hassani538bd592020-11-04 20:46:08 -08001531 if (SystemState::Get()->hardware()->IsOOBEEnabled() &&
1532 !SystemState::Get()->hardware()->IsOOBEComplete(nullptr) &&
Toni Barzic61544e62018-10-11 14:37:30 -07001533 (response.deadline.empty() ||
Amin Hassani538bd592020-11-04 20:46:08 -08001534 SystemState::Get()->payload_state()->GetRollbackHappened()) &&
Amin Hassani61789032020-11-13 16:20:12 -08001535 params->app_version() != "ForcedUpdate") {
Toni Barzic61544e62018-10-11 14:37:30 -07001536 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1537 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1538 return true;
1539 }
1540
Weidong Guo421ff332017-04-17 10:08:38 -07001541 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001542 LOG(INFO) << "Update is not allowed over current connection.";
1543 return true;
1544 }
1545
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001546 // Currently non-critical updates always update alongside the platform update
1547 // (a critical update) so this case should never actually be hit if the
1548 // request to Omaha for updates are correct. In other words, stop the update
1549 // from happening as there are no packages in the response to process.
1550 if (response.packages.empty()) {
1551 LOG(ERROR) << "All packages were excluded.";
1552 }
1553
Chris Sosa77f79e82014-06-02 18:16:24 -07001554 // Note: We could technically delete the UpdateFirstSeenAt state when we
1555 // return true. If we do, it'll mean a device has to restart the
1556 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1557 // turned on again. On the other hand, it also increases the chance of update
1558 // starvation if an admin turns AU on/off more frequently. We choose to err on
1559 // the side of preventing starvation at the cost of not applying scattering in
1560 // those cases.
1561 return false;
1562}
1563
Weidong Guo421ff332017-04-17 10:08:38 -07001564bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1565 const OmahaResponse& response) const {
Amin Hassani538bd592020-11-04 20:46:08 -08001566 PrefsInterface* prefs = SystemState::Get()->prefs();
Weidong Guo421ff332017-04-17 10:08:38 -07001567
1568 if (!prefs) {
1569 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1570 "not available.";
1571 return false;
1572 }
1573
1574 bool is_allowed;
1575
1576 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1577 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1578 is_allowed) {
1579 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1580 "set to true.";
1581 return true;
1582 }
1583
1584 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1585 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1586 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1587 "set to false or does not exist while target does not exist.";
1588 return false;
1589 }
1590
1591 std::string target_version;
1592 int64_t target_size;
1593
1594 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1595 &target_version) ||
1596 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1597 LOG(INFO) << "Disabling updates over cellular as the target version or "
1598 "size is not accessible.";
1599 return false;
1600 }
1601
1602 uint64_t total_packages_size = 0;
1603 for (const auto& package : response.packages) {
1604 total_packages_size += package.size;
1605 }
1606 if (target_version == response.version &&
1607 static_cast<uint64_t>(target_size) == total_packages_size) {
1608 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1609 "omaha response.";
1610 return true;
1611 } else {
1612 LOG(INFO) << "Disabling updates over cellular as the target does not"
1613 "match the omaha response.";
1614 return false;
1615 }
1616}
1617
1618bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1619 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001620 ConnectionType type;
1621 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001622 ConnectionManagerInterface* connection_manager =
Amin Hassani538bd592020-11-04 20:46:08 -08001623 SystemState::Get()->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001624 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001625 LOG(INFO) << "We could not determine our connection type. "
1626 << "Defaulting to allow updates.";
1627 return true;
1628 }
Weidong Guo421ff332017-04-17 10:08:38 -07001629
Chris Sosa77f79e82014-06-02 18:16:24 -07001630 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001631 bool is_device_policy_set =
1632 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1633 // Treats tethered connection as if it is cellular connection.
1634 bool is_over_cellular = type == ConnectionType::kCellular ||
1635 tethering == ConnectionTethering::kConfirmed;
1636
1637 if (!is_over_cellular) {
1638 // There's no need to further check user preferences as we are not over
1639 // cellular connection.
1640 if (!is_allowed)
1641 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1642 } else if (is_device_policy_set) {
1643 // There's no need to further check user preferences as the device policy
1644 // is set regarding updates over cellular.
1645 if (!is_allowed)
1646 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1647 } else {
1648 // Deivce policy is not set, so user preferences overwrite whether to
1649 // allow updates over cellular.
1650 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1651 if (!is_allowed)
1652 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1653 }
1654
Chris Sosa77f79e82014-06-02 18:16:24 -07001655 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001656 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001657 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1658 return is_allowed;
1659}
1660
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001661bool OmahaRequestAction::IsRollbackEnabled() const {
1662 if (policy_provider_->IsConsumerDevice()) {
1663 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1664 return false;
1665 }
1666
1667 if (!policy_provider_->device_policy_is_loaded()) {
1668 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1669 return true;
1670 }
1671
1672 int allowed_milestones;
1673 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1674 &allowed_milestones)) {
1675 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1676 "Defaulting to rollback enabled.";
1677 return true;
1678 }
1679
1680 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1681 return allowed_milestones > 0;
1682}
1683
1684void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001685 int max_kernel_rollforward;
Amin Hassani538bd592020-11-04 20:46:08 -08001686 int min_kernel_version =
1687 SystemState::Get()->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001688 if (IsRollbackEnabled()) {
1689 // If rollback is enabled, set the max kernel key version to the current
1690 // kernel key version. This has the effect of freezing kernel key roll
1691 // forwards.
1692 //
1693 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1694 // key roll forward happens until the server side components of rollback
1695 // are implemented. Future changes will allow the Omaha server to return
1696 // the kernel key version from max_rollback_versions in the past. At that
1697 // point the max kernel key version will be set to that value, creating a
1698 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001699 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001700 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001701 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001702 } else {
1703 // For devices that are not rollback enabled (ie. consumer devices), the
1704 // max kernel key version is set to 0xfffffffe, which is logically
1705 // infinity. This maintains the previous behavior that that kernel key
1706 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001707 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001708 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001709 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001710 }
1711
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001712 bool max_rollforward_set =
Amin Hassani538bd592020-11-04 20:46:08 -08001713 SystemState::Get()->hardware()->SetMaxKernelKeyRollforward(
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001714 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001715 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001716 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001717 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001718 // Report metrics
Amin Hassani538bd592020-11-04 20:46:08 -08001719 SystemState::Get()->metrics_reporter()->ReportKeyVersionMetrics(
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001720 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001721}
1722
May Lippert60aa3ca2018-08-15 16:55:29 -07001723base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1724 Time update_first_seen_at;
1725 int64_t update_first_seen_at_int;
Amin Hassani538bd592020-11-04 20:46:08 -08001726 if (SystemState::Get()->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1727 if (SystemState::Get()->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1728 &update_first_seen_at_int)) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001729 // Note: This timestamp could be that of ANY update we saw in the past
1730 // (not necessarily this particular update we're considering to apply)
1731 // but never got to apply because of some reason (e.g. stop AU policy,
1732 // updates being pulled out from Omaha, changes in target version prefix,
1733 // new update being rolled out, etc.). But for the purposes of scattering
1734 // it doesn't matter which update the timestamp corresponds to. i.e.
1735 // the clock starts ticking the first time we see an update and we're
1736 // ready to apply when the random wait period is satisfied relative to
1737 // that first seen timestamp.
1738 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1739 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1740 << utils::ToString(update_first_seen_at);
1741 } else {
1742 // This seems like an unexpected error where the persisted value exists
1743 // but it's not readable for some reason.
1744 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1745 return base::Time();
1746 }
1747 } else {
Amin Hassani538bd592020-11-04 20:46:08 -08001748 update_first_seen_at = SystemState::Get()->clock()->GetWallclockTime();
May Lippert60aa3ca2018-08-15 16:55:29 -07001749 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Amin Hassani538bd592020-11-04 20:46:08 -08001750 if (SystemState::Get()->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1751 update_first_seen_at_int)) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001752 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1753 << utils::ToString(update_first_seen_at);
1754 } else {
1755 // This seems like an unexpected error where the value cannot be
1756 // persisted for some reason.
1757 LOG(INFO) << "UpdateFirstSeenAt value "
1758 << utils::ToString(update_first_seen_at)
1759 << " cannot be persisted";
1760 return base::Time();
1761 }
1762 }
1763 return update_first_seen_at;
1764}
1765
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001766} // namespace chromeos_update_engine