blob: c3a1a114f0cd66b9828af47e58459070110dc508 [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 Hassani538bd592020-11-04 20:46:08 -0800283 : params_(SystemState::Get()->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700284 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300285 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800286 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700287 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700288 ping_active_days_(0),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700289 ping_roll_call_days_(0),
290 session_id_(session_id) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800291 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700292}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000293
Darin Petkov6a5b3222010-07-13 14:55:28 -0700294OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000295
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700296// Calculates the value to use for the ping days parameter.
297int OmahaRequestAction::CalculatePingDays(const string& key) {
Andrewe045aef2020-01-08 16:29:22 -0800298 int days = kPingNeverPinged;
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700299 int64_t last_ping = 0;
Amin Hassani538bd592020-11-04 20:46:08 -0800300 if (SystemState::Get()->prefs()->GetInt64(key, &last_ping) &&
301 last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700302 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
303 if (days < 0) {
304 // If |days| is negative, then the system clock must have jumped
305 // back in time since the ping was sent. Mark the value so that
306 // it doesn't get sent to the server but we still update the
307 // last ping daystart preference. This way the next ping time
308 // will be correct, hopefully.
309 days = kPingTimeJump;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800310 LOG(WARNING)
311 << "System clock jumped back in time. Resetting ping daystarts.";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700312 }
313 }
314 return days;
315}
316
317void OmahaRequestAction::InitPingDays() {
318 // We send pings only along with update checks, not with events.
319 if (IsEvent()) {
320 return;
321 }
322 // TODO(petkov): Figure a way to distinguish active use pings
323 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700324 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700325 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
326 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
327}
328
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700329bool OmahaRequestAction::ShouldPing() const {
Andrewe045aef2020-01-08 16:29:22 -0800330 if (ping_active_days_ == kPingNeverPinged &&
331 ping_roll_call_days_ == kPingNeverPinged) {
Amin Hassani538bd592020-11-04 20:46:08 -0800332 int powerwash_count = SystemState::Get()->hardware()->GetPowerwashCount();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700333 if (powerwash_count > 0) {
334 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
335 << "powerwash_count is " << powerwash_count;
336 return false;
337 }
Amin Hassani538bd592020-11-04 20:46:08 -0800338 if (SystemState::Get()->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani1677e812017-06-21 13:36:36 -0700339 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
Amin Hassanida35b872020-11-04 17:54:44 -0800340 << "the first_active_omaha_ping_sent is true.";
Amin Hassani1677e812017-06-21 13:36:36 -0700341 return false;
342 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700343 return true;
344 }
345 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
346}
347
David Zeuthen639aa362014-02-03 16:23:44 -0800348// static
Amin Hassani538bd592020-11-04 20:46:08 -0800349int OmahaRequestAction::GetInstallDate() {
350 PrefsInterface* prefs = SystemState::Get()->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700351 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800352 return -1;
353
354 // If we have the value stored on disk, just return it.
355 int64_t stored_value;
356 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
Kelvin Zhangebd5e252020-07-22 18:27:06 -0400357 // Convert and validity-check.
David Zeuthen639aa362014-02-03 16:23:44 -0800358 int install_date_days = static_cast<int>(stored_value);
359 if (install_date_days >= 0)
360 return install_date_days;
361 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
362 << install_date_days << " looks suspicious.";
363 prefs->Delete(kPrefsInstallDateDays);
364 }
365
366 // Otherwise, if OOBE is not complete then do nothing and wait for
367 // ParseResponse() to call ParseInstallDate() and then
368 // PersistInstallDate() to set the kPrefsInstallDateDays state
369 // variable. Once that is done, we'll then report back in future
370 // Omaha requests. This works exactly because OOBE triggers an
371 // update check.
372 //
373 // However, if OOBE is complete and the kPrefsInstallDateDays state
374 // variable is not set, there are two possibilities
375 //
376 // 1. The update check in OOBE failed so we never got a response
377 // from Omaha (no network etc.); or
378 //
379 // 2. OOBE was done on an older version that didn't write to the
380 // kPrefsInstallDateDays state variable.
381 //
382 // In both cases, we approximate the install date by simply
383 // inspecting the timestamp of when OOBE happened.
384
385 Time time_of_oobe;
Amin Hassani538bd592020-11-04 20:46:08 -0800386 if (!SystemState::Get()->hardware()->IsOOBEEnabled() ||
387 !SystemState::Get()->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800388 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700389 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800390 return -1;
391 }
392
393 int num_days;
394 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
395 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
396 << "as its value '" << utils::ToString(time_of_oobe)
397 << "' looks suspicious.";
398 return -1;
399 }
400
401 // Persist this to disk, for future use.
Amin Hassani538bd592020-11-04 20:46:08 -0800402 if (!OmahaRequestAction::PersistInstallDate(num_days,
403 kProvisionedFromOOBEMarker))
David Zeuthen639aa362014-02-03 16:23:44 -0800404 return -1;
405
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800406 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to " << num_days
Amin Hassanida35b872020-11-04 17:54:44 -0800407 << " days.";
David Zeuthen639aa362014-02-03 16:23:44 -0800408
409 return num_days;
410}
411
Andrewe045aef2020-01-08 16:29:22 -0800412void OmahaRequestAction::StorePingReply(
413 const OmahaParserData& parser_data) const {
414 for (const auto& app : parser_data.apps) {
415 auto it = params_->dlc_apps_params().find(app.id);
416 if (it == params_->dlc_apps_params().end())
417 continue;
418
419 const OmahaRequestParams::AppParams& dlc_params = it->second;
Andrew065d78d2020-04-07 15:43:07 -0700420 const string& dlc_id = dlc_params.name;
Andrewe045aef2020-01-08 16:29:22 -0800421 // Skip if the ping for this DLC was not sent.
422 if (!dlc_params.send_ping)
423 continue;
424
Amin Hassani538bd592020-11-04 20:46:08 -0800425 PrefsInterface* prefs = SystemState::Get()->prefs();
Andrewe045aef2020-01-08 16:29:22 -0800426 // Reset the active metadata value to |kPingInactiveValue|.
Andrew065d78d2020-04-07 15:43:07 -0700427 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -0700428 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -0700429 if (!prefs->SetInt64(active_key, kPingInactiveValue))
430 LOG(ERROR) << "Failed to set the value of ping metadata '" << active_key
431 << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800432
Andrew065d78d2020-04-07 15:43:07 -0700433 auto last_rollcall_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -0700434 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -0700435 if (!prefs->SetString(last_rollcall_key, parser_data.daystart_elapsed_days))
Andrewe045aef2020-01-08 16:29:22 -0800436 LOG(ERROR) << "Failed to set the value of ping metadata '"
Andrew065d78d2020-04-07 15:43:07 -0700437 << last_rollcall_key << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800438
439 if (dlc_params.ping_active) {
440 // Write the value of elapsed_days into |kPrefsPingLastActive| only if
441 // the previous ping was an active one.
Andrew065d78d2020-04-07 15:43:07 -0700442 auto last_active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -0700443 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -0700444 if (!prefs->SetString(last_active_key, parser_data.daystart_elapsed_days))
Andrewe045aef2020-01-08 16:29:22 -0800445 LOG(ERROR) << "Failed to set the value of ping metadata '"
Andrew065d78d2020-04-07 15:43:07 -0700446 << last_active_key << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800447 }
448 }
449}
450
Darin Petkov6a5b3222010-07-13 14:55:28 -0700451void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000452 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700453 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700454 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700455 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700456 return;
457 }
David Zeuthen639aa362014-02-03 16:23:44 -0800458
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700459 OmahaRequestBuilderXml omaha_request(event_.get(),
460 params_,
461 ping_only_,
462 ShouldPing(), // include_ping
463 ping_active_days_,
464 ping_roll_call_days_,
Amin Hassani538bd592020-11-04 20:46:08 -0800465 GetInstallDate(),
466 SystemState::Get()->prefs(),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700467 session_id_);
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700468 string request_post = omaha_request.GetRequest();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700469
Sen Jiang42fa45e2018-03-12 11:02:14 -0700470 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700471 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
472 params_->interactive() ? "fg" : "bg");
473 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
474 http_fetcher_->SetHeader(
475 kXGoogleUpdateUpdater,
476 base::StringPrintf(
477 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
478
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800479 http_fetcher_->SetPostData(
480 request_post.data(), request_post.size(), kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700481 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700482 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700483 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000484}
485
Darin Petkov6a5b3222010-07-13 14:55:28 -0700486void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000487 http_fetcher_->TerminateTransfer();
488}
489
490// We just store the response in the buffer. Once we've received all bytes,
491// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700492bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800493 const void* bytes,
494 size_t length) {
495 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
496 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700497 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000498}
499
500namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000501
502// Parses a 64 bit base-10 int from a string and returns it. Returns 0
503// on error. If the string contains "0", that's indistinguishable from
504// error.
505off_t ParseInt(const string& str) {
506 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700507 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000508 if (rc < 1) {
509 // failure
510 return 0;
511 }
512 return ret;
513}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700514
David Zeuthene8ed8632014-07-24 13:38:10 -0400515// Parses |str| and returns |true| if, and only if, its value is "true".
516bool ParseBool(const string& str) {
517 return str == "true";
518}
519
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700520// Update the last ping day preferences based on the server daystart
521// response. Returns true on success, false otherwise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800522bool UpdateLastPingDays(OmahaParserData* parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700523 int64_t elapsed_seconds = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800524 TEST_AND_RETURN_FALSE(base::StringToInt64(
525 parser_data->daystart_elapsed_seconds, &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700526 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
527
528 // Remember the local time that matches the server's last midnight
529 // time.
530 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
531 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
532 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
533 return true;
534}
Sen Jiang81259682017-03-30 15:11:30 -0700535
536// Parses the package node in the given XML document and populates
537// |output_object| if valid. Returns true if we should continue the parsing.
538// False otherwise, in which case it sets any error code using |completer|.
539bool ParsePackage(OmahaParserData::App* app,
540 OmahaResponse* output_object,
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700541 bool can_exclude,
Sen Jiang81259682017-03-30 15:11:30 -0700542 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700543 if (app->updatecheck_status.empty() ||
544 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700545 if (!app->packages.empty()) {
546 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
547 completer->set_code(ErrorCode::kOmahaResponseInvalid);
548 return false;
549 }
550 return true;
551 }
552 if (app->packages.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800553 LOG(ERROR) << "Omaha Response has no packages.";
Sen Jiang81259682017-03-30 15:11:30 -0700554 completer->set_code(ErrorCode::kOmahaResponseInvalid);
555 return false;
556 }
557 if (app->url_codebase.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800558 LOG(ERROR) << "No Omaha Response URLs.";
Sen Jiang81259682017-03-30 15:11:30 -0700559 completer->set_code(ErrorCode::kOmahaResponseInvalid);
560 return false;
561 }
Sen Jiang81259682017-03-30 15:11:30 -0700562 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700563 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700564 ":",
565 base::TRIM_WHITESPACE,
566 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700567 vector<string> metadata_signatures = base::SplitString(
568 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
569 ":",
570 base::TRIM_WHITESPACE,
571 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700572 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700573 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700574 ":",
575 base::TRIM_WHITESPACE,
576 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700577 for (size_t i = 0; i < app->packages.size(); i++) {
578 const auto& package = app->packages[i];
579 if (package.name.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800580 LOG(ERROR) << "Omaha Response has empty package name.";
Sen Jiang81259682017-03-30 15:11:30 -0700581 completer->set_code(ErrorCode::kOmahaResponseInvalid);
582 return false;
583 }
Sen Jiang81259682017-03-30 15:11:30 -0700584
585 OmahaResponse::Package out_package;
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700586 out_package.app_id = app->id;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700587 out_package.can_exclude = can_exclude;
Sen Jiang81259682017-03-30 15:11:30 -0700588 for (const string& codebase : app->url_codebase) {
589 if (codebase.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800590 LOG(ERROR) << "Omaha Response URL has empty codebase.";
Sen Jiang81259682017-03-30 15:11:30 -0700591 completer->set_code(ErrorCode::kOmahaResponseInvalid);
592 return false;
593 }
594 out_package.payload_urls.push_back(codebase + package.name);
595 }
Amin Hassanida35b872020-11-04 17:54:44 -0800596
Sen Jiang81259682017-03-30 15:11:30 -0700597 // Parse the payload size.
598 base::StringToUint64(package.size, &out_package.size);
599 if (out_package.size <= 0) {
600 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
601 completer->set_code(ErrorCode::kOmahaResponseInvalid);
602 return false;
603 }
Sen Jiang81259682017-03-30 15:11:30 -0700604
605 if (i < metadata_sizes.size())
606 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
Sen Jiang81259682017-03-30 15:11:30 -0700607
608 if (i < metadata_signatures.size())
609 out_package.metadata_signature = metadata_signatures[i];
Sen Jiang81259682017-03-30 15:11:30 -0700610
611 out_package.hash = package.hash;
612 if (out_package.hash.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800613 LOG(ERROR) << "Omaha Response has empty hash_sha256 value.";
Sen Jiang81259682017-03-30 15:11:30 -0700614 completer->set_code(ErrorCode::kOmahaResponseInvalid);
615 return false;
616 }
Sen Jiangcdd52062017-05-18 15:33:10 -0700617
Vyshu Khota4c5413d2020-11-04 16:17:25 -0800618 out_package.fp = package.fp;
619
Sen Jiangcdd52062017-05-18 15:33:10 -0700620 if (i < is_delta_payloads.size())
621 out_package.is_delta = ParseBool(is_delta_payloads[i]);
Sen Jiangcdd52062017-05-18 15:33:10 -0700622
Sen Jiang81259682017-03-30 15:11:30 -0700623 output_object->packages.push_back(std::move(out_package));
624 }
625
626 return true;
627}
628
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700629// Removes the candidate URLs which are excluded within packages, if all the
630// candidate URLs are excluded within a package, the package will be excluded.
631void ProcessExclusions(OmahaResponse* output_object,
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700632 OmahaRequestParams* params,
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700633 ExcluderInterface* excluder) {
634 for (auto package_it = output_object->packages.begin();
635 package_it != output_object->packages.end();
636 /* Increment logic in loop */) {
637 // If package cannot be excluded, quickly continue.
638 if (!package_it->can_exclude) {
639 ++package_it;
640 continue;
641 }
642 // Remove the excluded payload URLs.
643 for (auto payload_url_it = package_it->payload_urls.begin();
644 payload_url_it != package_it->payload_urls.end();
645 /* Increment logic in loop */) {
646 auto exclusion_name = utils::GetExclusionName(*payload_url_it);
647 // If payload URL is not excluded, quickly continue.
648 if (!excluder->IsExcluded(exclusion_name)) {
649 ++payload_url_it;
650 continue;
651 }
652 LOG(INFO) << "Excluding payload URL=" << *payload_url_it
653 << " for payload hash=" << package_it->hash;
654 payload_url_it = package_it->payload_urls.erase(payload_url_it);
655 }
656 // If there are no candidate payload URLs, remove the package.
657 if (package_it->payload_urls.empty()) {
658 LOG(INFO) << "Excluding payload hash=" << package_it->hash;
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -0700659 // Need to set DLC as not updated so correct metrics can be sent when an
660 // update is completed.
661 params->SetDlcNoUpdate(package_it->app_id);
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700662 package_it = output_object->packages.erase(package_it);
663 continue;
664 }
665 ++package_it;
666 }
667}
668
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700669// Parses the 2 key version strings kernel_version and firmware_version. If the
670// field is not present, or cannot be parsed the values default to 0xffff.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700671void ParseRollbackVersions(int allowed_milestones,
672 OmahaParserData* parser_data,
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700673 OmahaResponse* output_object) {
674 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700675 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700676 &output_object->rollback_key_version.firmware_key,
677 &output_object->rollback_key_version.firmware);
678 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700679 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700680 &output_object->rollback_key_version.kernel_key,
681 &output_object->rollback_key_version.kernel);
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700682
683 // Create the attribute name strings for milestone N - allowed_milestones.
684 const string firmware_max_rollforward_attr =
685 base::StringPrintf("%s_%i", kAttrFirmwareVersion, allowed_milestones);
686 const string kernel_max_rollforward_attr =
687 base::StringPrintf("%s_%i", kAttrKernelVersion, allowed_milestones);
688
689 const bool max_firmware_and_kernel_exist =
690 parser_data->updatecheck_attrs.count(firmware_max_rollforward_attr) > 0 &&
691 parser_data->updatecheck_attrs.count(kernel_max_rollforward_attr) > 0;
692
693 string firmware_version;
694 string kernel_version;
695 if (max_firmware_and_kernel_exist) {
696 firmware_version =
697 parser_data->updatecheck_attrs[firmware_max_rollforward_attr];
698 kernel_version =
699 parser_data->updatecheck_attrs[kernel_max_rollforward_attr];
700 }
701
702 LOG(INFO) << "For milestone N-" << allowed_milestones
703 << " firmware_key_version=" << firmware_version
704 << " kernel_key_version=" << kernel_version;
705
706 OmahaResponse::RollbackKeyVersion version;
707 utils::ParseRollbackKeyVersion(
708 firmware_version, &version.firmware_key, &version.firmware);
709 utils::ParseRollbackKeyVersion(
710 kernel_version, &version.kernel_key, &version.kernel);
711
712 output_object->past_rollback_key_version = std::move(version);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700713}
714
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700715} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000716
David Zeuthene8ed8632014-07-24 13:38:10 -0400717bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700718 OmahaResponse* output_object,
719 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700720 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700721 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700722 return false;
723 }
724
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800725 // chromium-os:37289: The PollInterval is not supported by Omaha server
726 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700727 // slow down the request rate from the server-side. Note that the PollInterval
728 // is not persisted, so it has to be sent by the server on every response to
729 // guarantee that the scheduler uses this value (otherwise, if the device got
730 // rebooted after the last server-indicated value, it'll revert to the default
731 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
732 // based on the assumption that we perform an update check every hour so that
733 // the max value of 8 will roughly be equivalent to one work day. If we decide
734 // to use PollInterval permanently, we should update the
735 // max_update_checks_allowed to take PollInterval into account. Note: The
736 // parsing for PollInterval happens even before parsing of the status because
737 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400738 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700739 &output_object->poll_interval);
740
David Zeuthen639aa362014-02-03 16:23:44 -0800741 // Check for the "elapsed_days" attribute in the "daystart"
742 // element. This is the number of days since Jan 1 2007, 0:00
743 // PST. If we don't have a persisted value of the Omaha InstallDate,
744 // we'll use it to calculate it and then persist it.
Amin Hassani538bd592020-11-04 20:46:08 -0800745 if (ParseInstallDate(parser_data, output_object) && !HasInstallDate()) {
David Zeuthen639aa362014-02-03 16:23:44 -0800746 // Since output_object->install_date_days is never negative, the
747 // elapsed_days -> install-date calculation is reduced to simply
748 // rounding down to the nearest number divisible by 7.
749 int remainder = output_object->install_date_days % 7;
750 int install_date_days_rounded =
751 output_object->install_date_days - remainder;
Amin Hassani538bd592020-11-04 20:46:08 -0800752 if (PersistInstallDate(install_date_days_rounded,
David Zeuthen639aa362014-02-03 16:23:44 -0800753 kProvisionedFromOmahaResponse)) {
754 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
Amin Hassanida35b872020-11-04 17:54:44 -0800755 << install_date_days_rounded << " days.";
David Zeuthen639aa362014-02-03 16:23:44 -0800756 }
757 }
758
Alex Deymo00d79ac2015-06-29 15:41:49 -0700759 // We persist the cohorts sent by omaha even if the status is "noupdate".
Jae Hoon Kime2cac612020-11-02 18:30:29 -0800760 PersistCohorts(*parser_data);
Alex Deymo00d79ac2015-06-29 15:41:49 -0700761
Amin Hassani2cbb0692019-10-30 13:36:17 -0700762 PersistEolInfo(parser_data->updatecheck_attrs);
763
Marton Hunyady199152d2018-05-07 19:08:48 +0200764 // Rollback-related updatecheck attributes.
765 // Defaults to false if attribute is not present.
766 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -0700767 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700768
769 // Parses the rollback versions of the current image. If the fields do not
770 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700771 ParseRollbackVersions(
772 params_->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -0700773
David Zeuthene8ed8632014-07-24 13:38:10 -0400774 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700775 return false;
776
David Zeuthene8ed8632014-07-24 13:38:10 -0400777 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700778 return false;
779
Sen Jiang0affc2c2017-02-10 15:55:05 -0800780 // Package has to be parsed after Params now because ParseParams need to make
781 // sure that postinstall action exists.
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700782 for (auto& app : parser_data->apps) {
783 // Only allow exclusions for a non-critical package during an update. For
784 // non-critical package installations, let the errors propagate instead
785 // of being handled inside update_engine as installations are a dlcservice
786 // specific feature.
787 bool can_exclude = !params_->is_install() && params_->IsDlcAppId(app.id);
788 if (!ParsePackage(&app, output_object, can_exclude, completer))
Sen Jiang81259682017-03-30 15:11:30 -0700789 return false;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700790 }
Sen Jiang0affc2c2017-02-10 15:55:05 -0800791
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700792 return true;
793}
794
David Zeuthene8ed8632014-07-24 13:38:10 -0400795bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700796 OmahaResponse* output_object,
797 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700798 output_object->update_exists = false;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700799 for (const auto& app : parser_data->apps) {
800 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -0700801 if (status == kValNoUpdate) {
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800802 // If the app is a DLC, allow status "noupdate" to support DLC
803 // deprecations.
804 if (params_->IsDlcAppId(app.id)) {
805 LOG(INFO) << "No update for <app> " << app.id
806 << " but update continuing since a DLC.";
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700807 params_->SetDlcNoUpdate(app.id);
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800808 continue;
809 }
Sen Jiang00adf7b2017-06-26 15:57:29 -0700810 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -0700811 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700812 output_object->update_exists = false;
813 break;
Sen Jiang81259682017-03-30 15:11:30 -0700814 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700815 auto const& attr_no_update =
816 app.action_postinstall_attrs.find(kAttrNoUpdate);
817 if (attr_no_update != app.action_postinstall_attrs.end() &&
818 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700819 // noupdate="true" in postinstall attributes means it's an update to
820 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -0700821 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700822 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700823 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700824 output_object->update_exists = true;
825 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700826 } else if (status.empty() && params_->is_install() &&
827 params_->GetAppId() == app.id) {
828 // Skips the platform app for install operation.
829 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -0700830 } else {
831 LOG(ERROR) << "Unknown Omaha response status: " << status;
832 completer->set_code(ErrorCode::kOmahaResponseInvalid);
833 return false;
834 }
835 }
836 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700837 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700838 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700839 }
840
Sen Jiang81259682017-03-30 15:11:30 -0700841 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700842}
843
David Zeuthene8ed8632014-07-24 13:38:10 -0400844bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700845 OmahaResponse* output_object,
846 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700847 map<string, string> attrs;
848 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700849 if (app.id == params_->GetAppId()) {
850 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -0700851 output_object->version = app.manifest_version;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700852 } else if (params_->is_install() &&
853 app.manifest_version != params_->app_version()) {
854 LOG(WARNING) << "An app has a different version (" << app.manifest_version
855 << ") that is different than platform app version ("
Amin Hassanida35b872020-11-04 17:54:44 -0800856 << params_->app_version() << ").";
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700857 }
858 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700859 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700860 }
Sen Jiang81259682017-03-30 15:11:30 -0700861 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700862 if (params_->is_install()) {
863 LOG(INFO) << "Use request version for Install operation.";
864 output_object->version = params_->app_version();
865 }
Chris Sosa3b748432013-06-20 16:42:59 -0700866 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700867 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700868 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700869 return false;
870 }
871
David Zeuthene8ed8632014-07-24 13:38:10 -0400872 if (attrs.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800873 LOG(ERROR) << "Omaha Response has no postinstall event action.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700874 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700875 return false;
876 }
877
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800878 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -0700879 output_object->more_info_url = attrs[kAttrMoreInfo];
880 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
881 output_object->deadline = attrs[kAttrDeadline];
882 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700883 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -0700884 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700885 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -0700886 ParseBool(attrs[kAttrDisableP2PForSharing]);
887 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800888
Amin Hassani6600a562018-09-24 15:17:19 -0700889 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800890 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800891 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700892
Jay Srinivasan08262882012-12-28 19:29:43 -0800893 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -0700894 ParseBool(attrs[kAttrDisablePayloadBackoff]);
895 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800896
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700897 return true;
898}
899
David Zeuthene8ed8632014-07-24 13:38:10 -0400900// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000901// and fill in the appropriate fields of the output object. Also, notifies
902// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800903void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -0700904 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000905 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800906 string current_response(response_buffer_.begin(), response_buffer_.end());
907 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700908
Amin Hassani538bd592020-11-04 20:46:08 -0800909 PayloadStateInterface* const payload_state =
910 SystemState::Get()->payload_state();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700911
Zentaro Kavanagh76af2662018-05-15 10:54:53 -0700912 // Set the max kernel key version based on whether rollback is allowed.
913 SetMaxKernelKeyVersionForRollback();
914
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700915 // Events are best effort transactions -- assume they always succeed.
916 if (IsEvent()) {
917 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700918 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700919 return;
920 }
921
Amin Hassanid3d84212019-08-17 00:27:44 -0700922 ErrorCode aux_error_code = fetcher->GetAuxiliaryErrorCode();
923 if (aux_error_code != ErrorCode::kSuccess) {
924 metrics::DownloadErrorCode download_error_code =
925 metrics_utils::GetDownloadErrorCode(aux_error_code);
Amin Hassani538bd592020-11-04 20:46:08 -0800926 SystemState::Get()->metrics_reporter()->ReportUpdateCheckMetrics(
Amin Hassanid3d84212019-08-17 00:27:44 -0700927 metrics::CheckResult::kUnset,
928 metrics::CheckReaction::kUnset,
929 download_error_code);
930 }
931
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700932 if (!successful) {
Darin Petkovedc522e2010-11-05 09:35:17 -0700933 int code = GetHTTPResponseCode();
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700934 LOG(ERROR) << "Omaha request network transfer failed with HTTPResponseCode="
935 << code;
Saint Chou6431c332020-07-29 14:04:14 +0000936 // Makes sure we send proper error values.
Darin Petkovedc522e2010-11-05 09:35:17 -0700937 if (code < 0 || code >= 1000) {
938 code = 999;
Saint Chou6431c332020-07-29 14:04:14 +0000939 LOG(WARNING) << "Converting to proper HTTPResponseCode=" << code;
Darin Petkovedc522e2010-11-05 09:35:17 -0700940 }
David Zeuthena99981f2013-04-29 13:42:47 -0700941 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700942 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000943 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700944 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000945
David Zeuthene8ed8632014-07-24 13:38:10 -0400946 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400947 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400948 XML_SetUserData(parser, &parser_data);
949 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400950 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800951 XML_Status res =
952 XML_Parse(parser,
953 reinterpret_cast<const char*>(response_buffer_.data()),
954 response_buffer_.size(),
955 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400956
957 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700958 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800959 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
960 << XML_GetCurrentLineNumber(parser) << " col "
961 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -0700962 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400963 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
964 if (response_buffer_.empty()) {
965 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
966 } else if (parser_data.entity_decl) {
967 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
968 }
969 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000970 return;
971 }
Amin Hassani91f48b42018-08-06 17:47:14 -0700972 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000973
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700974 // Update the last ping day preferences based on the server daystart response
975 // even if we didn't send a ping. Omaha always includes the daystart in the
976 // response, but log the error if it didn't.
Amin Hassani538bd592020-11-04 20:46:08 -0800977 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, SystemState::Get()->prefs()))
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700978 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700979
Amin Hassani1677e812017-06-21 13:36:36 -0700980 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
981 // we have got a response from omaha and if its value has never been set to
982 // true before. Failure of this function should be ignored. There should be no
983 // need to check if a=-1 has been sent because older devices have already sent
984 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
985 // future checks.
Amin Hassani538bd592020-11-04 20:46:08 -0800986 if (!SystemState::Get()->hardware()->GetFirstActiveOmahaPingSent()) {
987 if (!SystemState::Get()->hardware()->SetFirstActiveOmahaPingSent()) {
988 SystemState::Get()->metrics_reporter()->ReportInternalErrorCode(
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700989 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
990 }
Amin Hassani1677e812017-06-21 13:36:36 -0700991 }
992
Andrewe045aef2020-01-08 16:29:22 -0800993 // Create/update the metadata files for each DLC app received.
994 StorePingReply(parser_data);
995
Thieu Le116fda32011-04-19 11:01:54 -0700996 if (!HasOutputPipe()) {
997 // Just set success to whether or not the http transfer succeeded,
998 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700999 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001000 return;
1001 }
1002
Darin Petkov6a5b3222010-07-13 14:55:28 -07001003 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001004 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001005 return;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001006 ProcessExclusions(&output_object,
Amin Hassani538bd592020-11-04 20:46:08 -08001007 SystemState::Get()->request_params(),
1008 SystemState::Get()->update_attempter()->GetExcluder());
David Zeuthen8f191b22013-08-06 12:27:50 -07001009 output_object.update_exists = true;
1010 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001011
Toni Barzic61544e62018-10-11 14:37:30 -07001012 LoadOrPersistUpdateFirstSeenAtPref();
1013
Weidong Guo421ff332017-04-17 10:08:38 -07001014 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -07001015 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -07001016 // No need to change output_object.update_exists here, since the value
1017 // has been output to the pipe.
1018 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001019 return;
1020 }
1021
David Zeuthen8f191b22013-08-06 12:27:50 -07001022 // If Omaha says to disable p2p, respect that
1023 if (output_object.disable_p2p_for_downloading) {
1024 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1025 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001026 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001027 }
1028 if (output_object.disable_p2p_for_sharing) {
1029 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1030 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001031 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001032 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001033
1034 // Update the payload state with the current response. The payload state
1035 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001036 // from what's stored already. We are updating the payload state as late
1037 // as possible in this method so that if a new release gets pushed and then
1038 // got pulled back due to some issues, we don't want to clear our internal
1039 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001040 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001041
David Zeuthen8f191b22013-08-06 12:27:50 -07001042 // It could be we've already exceeded the deadline for when p2p is
1043 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001044 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001045 payload_state->P2PNewAttempt();
1046 if (!payload_state->P2PAttemptAllowed()) {
1047 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1048 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001049 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001050 }
1051 }
1052
1053 // From here on, we'll complete stuff in CompleteProcessing() so
1054 // disable |completer| since we'll create a new one in that
1055 // function.
1056 completer.set_should_complete(false);
1057
1058 // If we're allowed to use p2p for downloading we do not pay
1059 // attention to wall-clock-based waiting if the URL is indeed
1060 // available via p2p. Therefore, check if the file is available via
1061 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001062 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001063 LookupPayloadViaP2P(output_object);
1064 } else {
1065 CompleteProcessing();
1066 }
1067}
1068
1069void OmahaRequestAction::CompleteProcessing() {
1070 ScopedActionCompleter completer(processor_, this);
1071 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
Amin Hassani538bd592020-11-04 20:46:08 -08001072 PayloadStateInterface* payload_state = SystemState::Get()->payload_state();
David Zeuthen8f191b22013-08-06 12:27:50 -07001073
1074 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001075 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001076 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001077 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001078 return;
1079 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001080
Chris Sosa20f005c2013-09-05 13:53:08 -07001081 if (payload_state->ShouldBackoffDownload()) {
1082 output_object.update_exists = false;
1083 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
Amin Hassanida35b872020-11-04 17:54:44 -08001084 << "attempts.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001085 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001086 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001087 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001088 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001089}
1090
1091void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1092 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1093 if (!url.empty()) {
Amin Hassani538bd592020-11-04 20:46:08 -08001094 SystemState::Get()->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001095 } else {
1096 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1097 << "because no suitable peer could be found.";
Amin Hassani538bd592020-11-04 20:46:08 -08001098 SystemState::Get()->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001099 }
1100 CompleteProcessing();
1101}
1102
1103void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001104 // If the device is in the middle of an update, the state variables
1105 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1106 // tracks the offset and length of the operation currently in
1107 // progress. The offset is based from the end of the manifest which
1108 // is kPrefsManifestMetadataSize bytes long.
1109 //
1110 // To make forward progress and avoid deadlocks, we need to find a
1111 // peer that has at least the entire operation we're currently
1112 // working on. Otherwise we may end up in a situation where two
1113 // devices bounce back and forth downloading from each other,
1114 // neither making any forward progress until one of them decides to
1115 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1116 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001117 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001118 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001119 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001120 int64_t next_data_offset = 0;
1121 int64_t next_data_length = 0;
Amin Hassani538bd592020-11-04 20:46:08 -08001122 if (SystemState::Get()->prefs()->GetInt64(kPrefsManifestMetadataSize,
1123 &manifest_metadata_size) &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001124 manifest_metadata_size != -1 &&
Amin Hassani538bd592020-11-04 20:46:08 -08001125 SystemState::Get()->prefs()->GetInt64(kPrefsManifestSignatureSize,
1126 &manifest_signature_size) &&
Alex Deymof25eb492016-02-26 00:20:08 -08001127 manifest_signature_size != -1 &&
Amin Hassani538bd592020-11-04 20:46:08 -08001128 SystemState::Get()->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
1129 &next_data_offset) &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001130 next_data_offset != -1 &&
Amin Hassani538bd592020-11-04 20:46:08 -08001131 SystemState::Get()->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1132 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001133 minimum_size = manifest_metadata_size + manifest_signature_size +
1134 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001135 }
1136
Sen Jiang0affc2c2017-02-10 15:55:05 -08001137 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001138 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001139 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001140 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001141 string file_id =
1142 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Amin Hassani538bd592020-11-04 20:46:08 -08001143 if (SystemState::Get()->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001144 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1145 << " minimum_size=" << minimum_size;
Amin Hassani538bd592020-11-04 20:46:08 -08001146 SystemState::Get()->p2p_manager()->LookupUrlForFile(
David Zeuthen8f191b22013-08-06 12:27:50 -07001147 file_id,
1148 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001149 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001150 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1151 base::Unretained(this)));
1152 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001153}
1154
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001155bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001156 if (params_->interactive()) {
1157 LOG(INFO) << "Not deferring download because update is interactive.";
1158 return false;
1159 }
1160
David Zeuthen8f191b22013-08-06 12:27:50 -07001161 // If we're using p2p to download _and_ we have a p2p URL, we never
1162 // defer the download. This is because the download will always
1163 // happen from a peer on the LAN and we've been waiting in line for
1164 // our turn.
Amin Hassani538bd592020-11-04 20:46:08 -08001165 const PayloadStateInterface* payload_state =
1166 SystemState::Get()->payload_state();
Gilad Arnold74b5f552014-10-07 08:17:16 -07001167 if (payload_state->GetUsingP2PForDownloading() &&
1168 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001169 LOG(INFO) << "Download not deferred because download "
1170 << "will happen from a local peer (via p2p).";
1171 return false;
1172 }
1173
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001174 // We should defer the downloads only if we've first satisfied the
1175 // wall-clock-based-waiting period and then the update-check-based waiting
1176 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001177 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001178 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1179 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001180 return false;
1181 }
1182
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001183 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001184 case kWallClockWaitNotSatisfied:
1185 // We haven't even satisfied the first condition, passing the
1186 // wall-clock-based waiting period, so we should defer the downloads
1187 // until that happens.
1188 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1189 return true;
1190
1191 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1192 LOG(INFO) << "wall-clock-based-wait satisfied and "
1193 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001194 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001195
1196 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1197 // Wall-clock-based waiting period is satisfied, and it's determined
1198 // that we do not need the update-check-based wait. so no need to
1199 // defer downloads.
1200 LOG(INFO) << "wall-clock-based-wait satisfied and "
1201 << "update-check-based-wait is not required.";
1202 return false;
1203
1204 default:
1205 // Returning false for this default case so we err on the
1206 // side of downloading updates than deferring in case of any bugs.
1207 NOTREACHED();
1208 return false;
1209 }
1210}
1211
1212OmahaRequestAction::WallClockWaitResult
1213OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001214 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001215 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1216 if (update_first_seen_at == base::Time()) {
1217 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
Amin Hassanida35b872020-11-04 17:54:44 -08001218 "persisted.";
May Lippert60aa3ca2018-08-15 16:55:29 -07001219 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001220 }
1221
Sen Jiang7c1171e2016-06-23 11:35:40 -07001222 TimeDelta elapsed_time =
Amin Hassani538bd592020-11-04 20:46:08 -08001223 SystemState::Get()->clock()->GetWallclockTime() - update_first_seen_at;
Sen Jiang7c1171e2016-06-23 11:35:40 -07001224 TimeDelta max_scatter_period =
1225 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001226 int64_t staging_wait_time_in_days = 0;
1227 // Use staging and its default max value if staging is on.
Amin Hassani538bd592020-11-04 20:46:08 -08001228 if (SystemState::Get()->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1229 &staging_wait_time_in_days) &&
Adolfo Victoria497044c2018-07-18 07:51:42 -07001230 staging_wait_time_in_days > 0)
1231 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001232
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001233 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001234 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001235 << ", Time Elapsed = "
1236 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001237 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001238
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001239 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001240 // The deadline is set for all rules which serve a delta update from a
1241 // previous FSI, which means this update will be applied mostly in OOBE
1242 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1243 // quickly.
Amin Hassanida35b872020-11-04 17:54:44 -08001244 LOG(INFO) << "Not scattering as deadline flag is set.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001245 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1246 }
1247
1248 if (max_scatter_period.InDays() == 0) {
1249 // This means the Omaha rule creator decides that this rule
1250 // should not be scattered irrespective of the policy.
1251 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1252 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1253 }
1254
1255 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001256 // This means we've waited more than the upperbound wait in the rule
1257 // from the time we first saw a valid update available to us.
1258 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001259 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1260 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1261 }
1262
1263 // This means we are required to participate in scattering.
1264 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001265 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001266 if (remaining_wait_time.InSeconds() <= 0) {
1267 // Yes, it's our turn now.
1268 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1269
1270 // But we can't download until the update-check-count-based wait is also
1271 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001272 return params_->update_check_count_wait_enabled()
1273 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1274 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001275 }
1276
1277 // Not our turn yet, so we have to wait until our turn to
1278 // help scatter the downloads across all clients of the enterprise.
1279 LOG(INFO) << "Update deferred for another "
1280 << utils::FormatSecs(remaining_wait_time.InSeconds())
1281 << " per policy.";
1282 return kWallClockWaitNotSatisfied;
1283}
1284
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001285bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001286 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001287
Amin Hassani538bd592020-11-04 20:46:08 -08001288 if (SystemState::Get()->prefs()->Exists(kPrefsUpdateCheckCount)) {
1289 if (!SystemState::Get()->prefs()->GetInt64(kPrefsUpdateCheckCount,
1290 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001291 // We are unable to read the update check count from file for some reason.
1292 // So let's proceed anyway so as to not stall the update.
1293 LOG(ERROR) << "Unable to read update check count. "
1294 << "Skipping update-check-count-based-wait.";
1295 return true;
1296 }
1297 } else {
1298 // This file does not exist. This means we haven't started our update
1299 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001300 update_check_count_value =
1301 base::RandInt(params_->min_update_checks_needed(),
1302 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001303
1304 LOG(INFO) << "Randomly picked update check count value = "
1305 << update_check_count_value;
1306
1307 // Write out the initial value of update_check_count_value.
Amin Hassani538bd592020-11-04 20:46:08 -08001308 if (!SystemState::Get()->prefs()->SetInt64(kPrefsUpdateCheckCount,
1309 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001310 // We weren't able to write the update check count file for some reason.
1311 // So let's proceed anyway so as to not stall the update.
1312 LOG(ERROR) << "Unable to write update check count. "
1313 << "Skipping update-check-count-based-wait.";
1314 return true;
1315 }
1316 }
1317
1318 if (update_check_count_value == 0) {
1319 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1320 return true;
1321 }
1322
1323 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001324 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001325 // We err on the side of skipping scattering logic instead of stalling
1326 // a machine from receiving any updates in case of any unexpected state.
1327 LOG(ERROR) << "Invalid value for update check count detected. "
1328 << "Skipping update-check-count-based-wait.";
1329 return true;
1330 }
1331
1332 // Legal value, we need to wait for more update checks to happen
1333 // until this becomes 0.
1334 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001335 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001336 return false;
1337}
1338
David Zeuthen639aa362014-02-03 16:23:44 -08001339// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001340bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001341 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001342 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001343 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001344 return false;
1345
1346 if (elapsed_days < 0)
1347 return false;
1348
1349 output_object->install_date_days = elapsed_days;
1350 return true;
1351}
1352
1353// static
Amin Hassani538bd592020-11-04 20:46:08 -08001354bool OmahaRequestAction::HasInstallDate() {
1355 PrefsInterface* prefs = SystemState::Get()->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001356 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001357 return false;
1358
1359 return prefs->Exists(kPrefsInstallDateDays);
1360}
1361
1362// static
1363bool OmahaRequestAction::PersistInstallDate(
David Zeuthen639aa362014-02-03 16:23:44 -08001364 int install_date_days,
1365 InstallDateProvisioningSource source) {
1366 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1367
Amin Hassani538bd592020-11-04 20:46:08 -08001368 PrefsInterface* prefs = SystemState::Get()->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001369 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001370 return false;
1371
1372 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1373 return false;
1374
Amin Hassani538bd592020-11-04 20:46:08 -08001375 SystemState::Get()->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001376 static_cast<int>(source), // Sample.
1377 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001378 return true;
1379}
1380
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001381void OmahaRequestAction::PersistCohortData(const string& prefs_key,
1382 const Optional<string>& new_value) {
1383 if (!new_value)
1384 return;
1385 const string& value = new_value.value();
Amin Hassani538bd592020-11-04 20:46:08 -08001386 if (value.empty() && SystemState::Get()->prefs()->Exists(prefs_key)) {
1387 if (!SystemState::Get()->prefs()->Delete(prefs_key))
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001388 LOG(ERROR) << "Failed to remove stored " << prefs_key << "value.";
1389 else
1390 LOG(INFO) << "Removed stored " << prefs_key << " value.";
1391 } else if (!value.empty()) {
Amin Hassani538bd592020-11-04 20:46:08 -08001392 if (!SystemState::Get()->prefs()->SetString(prefs_key, value))
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001393 LOG(INFO) << "Failed to store new setting " << prefs_key << " as "
1394 << value;
1395 else
1396 LOG(INFO) << "Stored cohort setting " << prefs_key << " as " << value;
Alex Deymo8e18f932015-03-27 16:16:59 -07001397 }
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001398}
1399
1400void OmahaRequestAction::PersistCohorts(const OmahaParserData& parser_data) {
1401 for (const auto& app : parser_data.apps) {
1402 // For platform App ID.
1403 if (app.id == params_->GetAppId()) {
1404 PersistCohortData(kPrefsOmahaCohort, app.cohort);
1405 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
1406 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
1407 } else if (params_->IsDlcAppId(app.id)) {
1408 string dlc_id;
1409 if (!params_->GetDlcId(app.id, &dlc_id)) {
1410 LOG(WARNING) << "Skip persisting cohorts for DLC App ID=" << app.id
1411 << " as it is not in the request params.";
1412 continue;
1413 }
Amin Hassani538bd592020-11-04 20:46:08 -08001414 PrefsInterface* prefs = SystemState::Get()->prefs();
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001415 PersistCohortData(
1416 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohort}),
1417 app.cohort);
1418 PersistCohortData(
1419 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohortName}),
1420 app.cohortname);
1421 PersistCohortData(
1422 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohortHint}),
1423 app.cohorthint);
1424 } else {
1425 LOG(WARNING) << "Skip persisting cohorts for unknown App ID=" << app.id;
1426 }
1427 }
Alex Deymo8e18f932015-03-27 16:16:59 -07001428}
1429
Amin Hassani2cbb0692019-10-30 13:36:17 -07001430bool OmahaRequestAction::PersistEolInfo(const map<string, string>& attrs) {
Jae Hoon Kimb3146742019-11-07 13:24:24 -08001431 // If EOL date attribute is not sent, don't delete the old persisted EOL
1432 // date information.
Jae Hoon Kim051627a2019-09-03 12:56:32 -07001433 auto eol_date_attr = attrs.find(kAttrEolDate);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07001434 if (eol_date_attr != attrs.end()) {
1435 const auto& eol_date = eol_date_attr->second;
Amin Hassani538bd592020-11-04 20:46:08 -08001436 if (!SystemState::Get()->prefs()->SetString(kPrefsOmahaEolDate, eol_date)) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07001437 LOG(ERROR) << "Setting EOL date failed.";
1438 return false;
1439 }
1440 LOG(INFO) << "Set EOL date to " << eol_date;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001441 }
Amin Hassani2cbb0692019-10-30 13:36:17 -07001442 return true;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001443}
1444
David Zeuthen33bae492014-02-25 16:16:18 -08001445void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1446 // We only want to report this on "update check".
1447 if (ping_only_ || event_ != nullptr)
1448 return;
1449
1450 metrics::CheckResult result = metrics::CheckResult::kUnset;
1451 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1452 metrics::DownloadErrorCode download_error_code =
1453 metrics::DownloadErrorCode::kUnset;
1454
1455 // Regular update attempt.
1456 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001457 case ErrorCode::kSuccess:
1458 // OK, we parsed the response successfully but that does
1459 // necessarily mean that an update is available.
1460 if (HasOutputPipe()) {
1461 const OmahaResponse& response = GetOutputObject();
1462 if (response.update_exists) {
1463 result = metrics::CheckResult::kUpdateAvailable;
1464 reaction = metrics::CheckReaction::kUpdating;
1465 } else {
1466 result = metrics::CheckResult::kNoUpdateAvailable;
1467 }
David Zeuthen33bae492014-02-25 16:16:18 -08001468 } else {
1469 result = metrics::CheckResult::kNoUpdateAvailable;
1470 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001471 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001472
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001473 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1474 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1475 result = metrics::CheckResult::kUpdateAvailable;
1476 reaction = metrics::CheckReaction::kIgnored;
1477 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001478
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001479 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1480 result = metrics::CheckResult::kUpdateAvailable;
1481 reaction = metrics::CheckReaction::kDeferring;
1482 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001483
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001484 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1485 result = metrics::CheckResult::kUpdateAvailable;
1486 reaction = metrics::CheckReaction::kBackingOff;
1487 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001488
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001489 default:
1490 // We report two flavors of errors, "Download errors" and "Parsing
1491 // error". Try to convert to the former and if that doesn't work
1492 // we know it's the latter.
1493 metrics::DownloadErrorCode tmp_error =
1494 metrics_utils::GetDownloadErrorCode(code);
1495 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1496 result = metrics::CheckResult::kDownloadError;
1497 download_error_code = tmp_error;
1498 } else {
1499 result = metrics::CheckResult::kParsingError;
1500 }
1501 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001502 }
1503
Amin Hassani538bd592020-11-04 20:46:08 -08001504 SystemState::Get()->metrics_reporter()->ReportUpdateCheckMetrics(
1505 result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001506}
1507
Toni Barzic61544e62018-10-11 14:37:30 -07001508bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1509 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001510 // Note: policy decision to not update to a version we rolled back from.
1511 string rollback_version =
Amin Hassani538bd592020-11-04 20:46:08 -08001512 SystemState::Get()->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001513 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001514 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001515 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001516 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001517 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001518 return true;
1519 }
1520 }
1521
Amin Hassani538bd592020-11-04 20:46:08 -08001522 if (SystemState::Get()->hardware()->IsOOBEEnabled() &&
1523 !SystemState::Get()->hardware()->IsOOBEComplete(nullptr) &&
Toni Barzic61544e62018-10-11 14:37:30 -07001524 (response.deadline.empty() ||
Amin Hassani538bd592020-11-04 20:46:08 -08001525 SystemState::Get()->payload_state()->GetRollbackHappened()) &&
Toni Barzic61544e62018-10-11 14:37:30 -07001526 params_->app_version() != "ForcedUpdate") {
1527 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1528 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1529 return true;
1530 }
1531
Weidong Guo421ff332017-04-17 10:08:38 -07001532 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001533 LOG(INFO) << "Update is not allowed over current connection.";
1534 return true;
1535 }
1536
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001537 // Currently non-critical updates always update alongside the platform update
1538 // (a critical update) so this case should never actually be hit if the
1539 // request to Omaha for updates are correct. In other words, stop the update
1540 // from happening as there are no packages in the response to process.
1541 if (response.packages.empty()) {
1542 LOG(ERROR) << "All packages were excluded.";
1543 }
1544
Chris Sosa77f79e82014-06-02 18:16:24 -07001545 // Note: We could technically delete the UpdateFirstSeenAt state when we
1546 // return true. If we do, it'll mean a device has to restart the
1547 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1548 // turned on again. On the other hand, it also increases the chance of update
1549 // starvation if an admin turns AU on/off more frequently. We choose to err on
1550 // the side of preventing starvation at the cost of not applying scattering in
1551 // those cases.
1552 return false;
1553}
1554
Weidong Guo421ff332017-04-17 10:08:38 -07001555bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1556 const OmahaResponse& response) const {
Amin Hassani538bd592020-11-04 20:46:08 -08001557 PrefsInterface* prefs = SystemState::Get()->prefs();
Weidong Guo421ff332017-04-17 10:08:38 -07001558
1559 if (!prefs) {
1560 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1561 "not available.";
1562 return false;
1563 }
1564
1565 bool is_allowed;
1566
1567 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1568 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1569 is_allowed) {
1570 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1571 "set to true.";
1572 return true;
1573 }
1574
1575 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1576 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1577 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1578 "set to false or does not exist while target does not exist.";
1579 return false;
1580 }
1581
1582 std::string target_version;
1583 int64_t target_size;
1584
1585 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1586 &target_version) ||
1587 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1588 LOG(INFO) << "Disabling updates over cellular as the target version or "
1589 "size is not accessible.";
1590 return false;
1591 }
1592
1593 uint64_t total_packages_size = 0;
1594 for (const auto& package : response.packages) {
1595 total_packages_size += package.size;
1596 }
1597 if (target_version == response.version &&
1598 static_cast<uint64_t>(target_size) == total_packages_size) {
1599 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1600 "omaha response.";
1601 return true;
1602 } else {
1603 LOG(INFO) << "Disabling updates over cellular as the target does not"
1604 "match the omaha response.";
1605 return false;
1606 }
1607}
1608
1609bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1610 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001611 ConnectionType type;
1612 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001613 ConnectionManagerInterface* connection_manager =
Amin Hassani538bd592020-11-04 20:46:08 -08001614 SystemState::Get()->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001615 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001616 LOG(INFO) << "We could not determine our connection type. "
1617 << "Defaulting to allow updates.";
1618 return true;
1619 }
Weidong Guo421ff332017-04-17 10:08:38 -07001620
Chris Sosa77f79e82014-06-02 18:16:24 -07001621 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001622 bool is_device_policy_set =
1623 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1624 // Treats tethered connection as if it is cellular connection.
1625 bool is_over_cellular = type == ConnectionType::kCellular ||
1626 tethering == ConnectionTethering::kConfirmed;
1627
1628 if (!is_over_cellular) {
1629 // There's no need to further check user preferences as we are not over
1630 // cellular connection.
1631 if (!is_allowed)
1632 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1633 } else if (is_device_policy_set) {
1634 // There's no need to further check user preferences as the device policy
1635 // is set regarding updates over cellular.
1636 if (!is_allowed)
1637 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1638 } else {
1639 // Deivce policy is not set, so user preferences overwrite whether to
1640 // allow updates over cellular.
1641 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1642 if (!is_allowed)
1643 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1644 }
1645
Chris Sosa77f79e82014-06-02 18:16:24 -07001646 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001647 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001648 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1649 return is_allowed;
1650}
1651
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001652bool OmahaRequestAction::IsRollbackEnabled() const {
1653 if (policy_provider_->IsConsumerDevice()) {
1654 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1655 return false;
1656 }
1657
1658 if (!policy_provider_->device_policy_is_loaded()) {
1659 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1660 return true;
1661 }
1662
1663 int allowed_milestones;
1664 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1665 &allowed_milestones)) {
1666 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1667 "Defaulting to rollback enabled.";
1668 return true;
1669 }
1670
1671 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1672 return allowed_milestones > 0;
1673}
1674
1675void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001676 int max_kernel_rollforward;
Amin Hassani538bd592020-11-04 20:46:08 -08001677 int min_kernel_version =
1678 SystemState::Get()->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001679 if (IsRollbackEnabled()) {
1680 // If rollback is enabled, set the max kernel key version to the current
1681 // kernel key version. This has the effect of freezing kernel key roll
1682 // forwards.
1683 //
1684 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1685 // key roll forward happens until the server side components of rollback
1686 // are implemented. Future changes will allow the Omaha server to return
1687 // the kernel key version from max_rollback_versions in the past. At that
1688 // point the max kernel key version will be set to that value, creating a
1689 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001690 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001691 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001692 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001693 } else {
1694 // For devices that are not rollback enabled (ie. consumer devices), the
1695 // max kernel key version is set to 0xfffffffe, which is logically
1696 // infinity. This maintains the previous behavior that that kernel key
1697 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001698 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001699 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001700 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001701 }
1702
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001703 bool max_rollforward_set =
Amin Hassani538bd592020-11-04 20:46:08 -08001704 SystemState::Get()->hardware()->SetMaxKernelKeyRollforward(
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001705 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001706 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001707 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001708 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001709 // Report metrics
Amin Hassani538bd592020-11-04 20:46:08 -08001710 SystemState::Get()->metrics_reporter()->ReportKeyVersionMetrics(
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001711 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001712}
1713
May Lippert60aa3ca2018-08-15 16:55:29 -07001714base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1715 Time update_first_seen_at;
1716 int64_t update_first_seen_at_int;
Amin Hassani538bd592020-11-04 20:46:08 -08001717 if (SystemState::Get()->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1718 if (SystemState::Get()->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1719 &update_first_seen_at_int)) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001720 // Note: This timestamp could be that of ANY update we saw in the past
1721 // (not necessarily this particular update we're considering to apply)
1722 // but never got to apply because of some reason (e.g. stop AU policy,
1723 // updates being pulled out from Omaha, changes in target version prefix,
1724 // new update being rolled out, etc.). But for the purposes of scattering
1725 // it doesn't matter which update the timestamp corresponds to. i.e.
1726 // the clock starts ticking the first time we see an update and we're
1727 // ready to apply when the random wait period is satisfied relative to
1728 // that first seen timestamp.
1729 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1730 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1731 << utils::ToString(update_first_seen_at);
1732 } else {
1733 // This seems like an unexpected error where the persisted value exists
1734 // but it's not readable for some reason.
1735 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1736 return base::Time();
1737 }
1738 } else {
Amin Hassani538bd592020-11-04 20:46:08 -08001739 update_first_seen_at = SystemState::Get()->clock()->GetWallclockTime();
May Lippert60aa3ca2018-08-15 16:55:29 -07001740 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Amin Hassani538bd592020-11-04 20:46:08 -08001741 if (SystemState::Get()->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1742 update_first_seen_at_int)) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001743 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1744 << utils::ToString(update_first_seen_at);
1745 } else {
1746 // This seems like an unexpected error where the value cannot be
1747 // persisted for some reason.
1748 LOG(INFO) << "UpdateFirstSeenAt value "
1749 << utils::ToString(update_first_seen_at)
1750 << " cannot be persisted";
1751 return base::Time();
1752 }
1753 }
1754 return update_first_seen_at;
1755}
1756
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001757} // namespace chromeos_update_engine