blob: cad0c67428d6d1ba9c38e210ec750064cc2d4866 [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"
51#include "update_engine/common/utils.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070052#include "update_engine/cros/connection_manager_interface.h"
53#include "update_engine/cros/omaha_request_builder_xml.h"
54#include "update_engine/cros/omaha_request_params.h"
55#include "update_engine/cros/p2p_manager.h"
56#include "update_engine/cros/payload_state_interface.h"
57#include "update_engine/cros/update_attempter.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080058#include "update_engine/metrics_utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000059
Jae Hoon Kimebea3392020-04-27 13:27:35 -070060using base::Optional;
Darin Petkov1cbd78f2010-07-29 12:38:34 -070061using base::Time;
62using base::TimeDelta;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080063using chromeos_update_manager::kRollforwardInfinity;
David Zeuthene8ed8632014-07-24 13:38:10 -040064using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000065using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040066using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000067
68namespace chromeos_update_engine {
69
Amin Hassani6600a562018-09-24 15:17:19 -070070// List of custom attributes that we interpret in the Omaha response:
71constexpr char kAttrDeadline[] = "deadline";
72constexpr char kAttrDisableP2PForDownloading[] = "DisableP2PForDownloading";
73constexpr char kAttrDisableP2PForSharing[] = "DisableP2PForSharing";
74constexpr char kAttrDisablePayloadBackoff[] = "DisablePayloadBackoff";
75constexpr char kAttrVersion[] = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080076// Deprecated: "IsDelta"
Amin Hassani6600a562018-09-24 15:17:19 -070077constexpr char kAttrIsDeltaPayload[] = "IsDeltaPayload";
78constexpr char kAttrMaxFailureCountPerUrl[] = "MaxFailureCountPerUrl";
79constexpr char kAttrMaxDaysToScatter[] = "MaxDaysToScatter";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080080// Deprecated: "ManifestSignatureRsa"
81// Deprecated: "ManifestSize"
Amin Hassani6600a562018-09-24 15:17:19 -070082constexpr char kAttrMetadataSignatureRsa[] = "MetadataSignatureRsa";
83constexpr char kAttrMetadataSize[] = "MetadataSize";
84constexpr char kAttrMoreInfo[] = "MoreInfo";
85constexpr char kAttrNoUpdate[] = "noupdate";
Don Garrett42bd3aa2013-04-10 18:14:56 -070086// Deprecated: "NeedsAdmin"
Amin Hassani6600a562018-09-24 15:17:19 -070087constexpr char kAttrPollInterval[] = "PollInterval";
88constexpr char kAttrPowerwash[] = "Powerwash";
89constexpr char kAttrPrompt[] = "Prompt";
90constexpr char kAttrPublicKeyRsa[] = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080091
Amin Hassani6600a562018-09-24 15:17:19 -070092// List of attributes that we interpret in the Omaha response:
93constexpr char kAttrAppId[] = "appid";
94constexpr char kAttrCodeBase[] = "codebase";
95constexpr char kAttrCohort[] = "cohort";
96constexpr char kAttrCohortHint[] = "cohorthint";
97constexpr char kAttrCohortName[] = "cohortname";
98constexpr char kAttrElapsedDays[] = "elapsed_days";
99constexpr char kAttrElapsedSeconds[] = "elapsed_seconds";
100constexpr char kAttrEvent[] = "event";
Vyshu Khota4c5413d2020-11-04 16:17:25 -0800101constexpr char kAttrFp[] = "fp";
Amin Hassani6600a562018-09-24 15:17:19 -0700102constexpr char kAttrHashSha256[] = "hash_sha256";
103// Deprecated: "hash"; Although we still need to pass it from the server for
104// backward compatibility.
105constexpr char kAttrName[] = "name";
106// Deprecated: "sha256"; Although we still need to pass it from the server for
107// backward compatibility.
108constexpr char kAttrSize[] = "size";
109constexpr char kAttrStatus[] = "status";
110
111// List of values that we interpret in the Omaha response:
112constexpr char kValPostInstall[] = "postinstall";
113constexpr char kValNoUpdate[] = "noupdate";
114
Alex Deymob3fa53b2016-04-18 19:57:58 -0700115// updatecheck attributes (without the underscore prefix).
Amin Hassani2cbb0692019-10-30 13:36:17 -0700116// Deprecated: "eol"
Jae Hoon Kim051627a2019-09-03 12:56:32 -0700117constexpr char kAttrEolDate[] = "eol_date";
Amin Hassani6600a562018-09-24 15:17:19 -0700118constexpr char kAttrRollback[] = "rollback";
119constexpr char kAttrFirmwareVersion[] = "firmware_version";
120constexpr char kAttrKernelVersion[] = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -0700121
David Zeuthene8ed8632014-07-24 13:38:10 -0400122// Struct used for holding data obtained when parsing the XML.
123struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400124 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
125
126 // Pointer to the expat XML_Parser object.
127 XML_Parser xml_parser;
128
David Zeuthene8ed8632014-07-24 13:38:10 -0400129 // This is the state of the parser as it's processing the XML.
130 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400131 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400132 string current_path;
133
134 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400135 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700136 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400137 string daystart_elapsed_days;
138 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800139
Sen Jiang81259682017-03-30 15:11:30 -0700140 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700141 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700142 vector<string> url_codebase;
143 string manifest_version;
144 map<string, string> action_postinstall_attrs;
145 string updatecheck_status;
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700146 Optional<string> cohort;
147 Optional<string> cohorthint;
148 Optional<string> cohortname;
Sen Jiang81259682017-03-30 15:11:30 -0700149
150 struct Package {
151 string name;
152 string size;
153 string hash;
Vyshu Khota4c5413d2020-11-04 16:17:25 -0800154 string fp;
Sen Jiang81259682017-03-30 15:11:30 -0700155 };
156 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800157 };
Sen Jiang81259682017-03-30 15:11:30 -0700158 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400159};
160
161namespace {
162
163// Callback function invoked by expat.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800164void ParserHandlerStart(void* user_data,
165 const XML_Char* element,
David Zeuthene8ed8632014-07-24 13:38:10 -0400166 const XML_Char** attr) {
167 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
168
169 if (data->failed)
170 return;
171
172 data->current_path += string("/") + element;
173
174 map<string, string> attrs;
175 if (attr != nullptr) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800176 for (int n = 0; attr[n] != nullptr && attr[n + 1] != nullptr; n += 2) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400177 string key = attr[n];
178 string value = attr[n + 1];
179 attrs[key] = value;
180 }
181 }
182
Alex Deymo8e18f932015-03-27 16:16:59 -0700183 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700184 OmahaParserData::App app;
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700185 if (attrs.find(kAttrAppId) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700186 app.id = attrs[kAttrAppId];
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700187 if (attrs.find(kAttrCohort) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700188 app.cohort = attrs[kAttrCohort];
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700189 if (attrs.find(kAttrCohortHint) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700190 app.cohorthint = attrs[kAttrCohortHint];
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700191 if (attrs.find(kAttrCohortName) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700192 app.cohortname = attrs[kAttrCohortName];
Sen Jiangb1e063a2017-09-15 17:44:31 -0700193 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700194 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700195 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700196 data->apps.back().updatecheck_status = attrs[kAttrStatus];
Sen Jiang81259682017-03-30 15:11:30 -0700197 if (data->updatecheck_poll_interval.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700198 data->updatecheck_poll_interval = attrs[kAttrPollInterval];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700199 // Omaha sends arbitrary key-value pairs as extra attributes starting with
200 // an underscore.
201 for (const auto& attr : attrs) {
202 if (!attr.first.empty() && attr.first[0] == '_')
203 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
204 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400205 } else if (data->current_path == "/response/daystart") {
206 // Get the install-date.
Amin Hassani6600a562018-09-24 15:17:19 -0700207 data->daystart_elapsed_days = attrs[kAttrElapsedDays];
208 data->daystart_elapsed_seconds = attrs[kAttrElapsedSeconds];
David Zeuthene8ed8632014-07-24 13:38:10 -0400209 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
210 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700211 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700212 data->apps.back().url_codebase.push_back(attrs[kAttrCodeBase]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800213 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400214 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800215 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700216 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700217 data->apps.back().packages.push_back({.name = attrs[kAttrName],
218 .size = attrs[kAttrSize],
Vyshu Khota4c5413d2020-11-04 16:17:25 -0800219 .hash = attrs[kAttrHashSha256],
220 .fp = attrs[kAttrFp]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400221 } else if (data->current_path == "/response/app/updatecheck/manifest") {
222 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700223 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700224 data->apps.back().manifest_version = attrs[kAttrVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400225 } else if (data->current_path ==
226 "/response/app/updatecheck/manifest/actions/action") {
227 // We only care about the postinstall action.
Amin Hassani6600a562018-09-24 15:17:19 -0700228 if (attrs[kAttrEvent] == kValPostInstall && !data->apps.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700229 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400230 }
231 }
232}
233
234// Callback function invoked by expat.
235void ParserHandlerEnd(void* user_data, const XML_Char* element) {
236 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
237 if (data->failed)
238 return;
239
240 const string path_suffix = string("/") + element;
241
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800242 if (!base::EndsWith(
243 data->current_path, path_suffix, base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400244 LOG(ERROR) << "Unexpected end element '" << element
245 << "' with current_path='" << data->current_path << "'";
246 data->failed = true;
247 return;
248 }
249 data->current_path.resize(data->current_path.size() - path_suffix.size());
250}
251
David Zeuthenf3e28012014-08-26 18:23:52 -0400252// Callback function invoked by expat.
253//
254// This is called for entity declarations. Since Omaha is guaranteed
255// to never return any XML with entities our course of action is to
256// just stop parsing. This avoids potential resource exhaustion
257// problems AKA the "billion laughs". CVE-2013-0340.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800258void ParserHandlerEntityDecl(void* user_data,
259 const XML_Char* entity_name,
David Zeuthenf3e28012014-08-26 18:23:52 -0400260 int is_parameter_entity,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800261 const XML_Char* value,
David Zeuthenf3e28012014-08-26 18:23:52 -0400262 int value_length,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800263 const XML_Char* base,
264 const XML_Char* system_id,
265 const XML_Char* public_id,
266 const XML_Char* notation_name) {
David Zeuthenf3e28012014-08-26 18:23:52 -0400267 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
268
269 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
270 data->failed = true;
271 data->entity_decl = true;
272 XML_StopParser(data->xml_parser, false);
273}
274
David Zeuthene8ed8632014-07-24 13:38:10 -0400275} // namespace
276
Alex Deymoc1c17b42015-11-23 03:53:15 -0300277OmahaRequestAction::OmahaRequestAction(
278 SystemState* system_state,
279 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)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800283 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800284 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700285 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300286 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800287 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700288 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700289 ping_active_days_(0),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700290 ping_roll_call_days_(0),
291 session_id_(session_id) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800292 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700293}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000294
Darin Petkov6a5b3222010-07-13 14:55:28 -0700295OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000296
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700297// Calculates the value to use for the ping days parameter.
298int OmahaRequestAction::CalculatePingDays(const string& key) {
Andrewe045aef2020-01-08 16:29:22 -0800299 int days = kPingNeverPinged;
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700300 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800301 if (system_state_->prefs()->GetInt64(key, &last_ping) && 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) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700332 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
333 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 Hassani1677e812017-06-21 13:36:36 -0700338 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
339 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
349int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
350 PrefsInterface* prefs = system_state->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;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700386 if (!system_state->hardware()->IsOOBEEnabled() ||
387 !system_state->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 Hassani7cc8bb02019-01-14 16:29:47 -0800402 if (!OmahaRequestAction::PersistInstallDate(
403 system_state, num_days, 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
Andrew065d78d2020-04-07 15:43:07 -0700425 PrefsInterface* prefs = system_state_->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_,
465 GetInstallDate(system_state_),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700466 system_state_->prefs(),
467 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.
David Zeuthene8ed8632014-07-24 13:38:10 -0400745 if (ParseInstallDate(parser_data, output_object) &&
746 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800747 // Since output_object->install_date_days is never negative, the
748 // elapsed_days -> install-date calculation is reduced to simply
749 // rounding down to the nearest number divisible by 7.
750 int remainder = output_object->install_date_days % 7;
751 int install_date_days_rounded =
752 output_object->install_date_days - remainder;
753 if (PersistInstallDate(system_state_,
754 install_date_days_rounded,
755 kProvisionedFromOmahaResponse)) {
756 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
Amin Hassanida35b872020-11-04 17:54:44 -0800757 << install_date_days_rounded << " days.";
David Zeuthen639aa362014-02-03 16:23:44 -0800758 }
759 }
760
Alex Deymo00d79ac2015-06-29 15:41:49 -0700761 // We persist the cohorts sent by omaha even if the status is "noupdate".
Jae Hoon Kime2cac612020-11-02 18:30:29 -0800762 PersistCohorts(*parser_data);
Alex Deymo00d79ac2015-06-29 15:41:49 -0700763
Amin Hassani2cbb0692019-10-30 13:36:17 -0700764 PersistEolInfo(parser_data->updatecheck_attrs);
765
Marton Hunyady199152d2018-05-07 19:08:48 +0200766 // Rollback-related updatecheck attributes.
767 // Defaults to false if attribute is not present.
768 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -0700769 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700770
771 // Parses the rollback versions of the current image. If the fields do not
772 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700773 ParseRollbackVersions(
774 params_->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -0700775
David Zeuthene8ed8632014-07-24 13:38:10 -0400776 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700777 return false;
778
David Zeuthene8ed8632014-07-24 13:38:10 -0400779 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700780 return false;
781
Sen Jiang0affc2c2017-02-10 15:55:05 -0800782 // Package has to be parsed after Params now because ParseParams need to make
783 // sure that postinstall action exists.
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700784 for (auto& app : parser_data->apps) {
785 // Only allow exclusions for a non-critical package during an update. For
786 // non-critical package installations, let the errors propagate instead
787 // of being handled inside update_engine as installations are a dlcservice
788 // specific feature.
789 bool can_exclude = !params_->is_install() && params_->IsDlcAppId(app.id);
790 if (!ParsePackage(&app, output_object, can_exclude, completer))
Sen Jiang81259682017-03-30 15:11:30 -0700791 return false;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700792 }
Sen Jiang0affc2c2017-02-10 15:55:05 -0800793
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700794 return true;
795}
796
David Zeuthene8ed8632014-07-24 13:38:10 -0400797bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700798 OmahaResponse* output_object,
799 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700800 output_object->update_exists = false;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700801 for (const auto& app : parser_data->apps) {
802 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -0700803 if (status == kValNoUpdate) {
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800804 // If the app is a DLC, allow status "noupdate" to support DLC
805 // deprecations.
806 if (params_->IsDlcAppId(app.id)) {
807 LOG(INFO) << "No update for <app> " << app.id
808 << " but update continuing since a DLC.";
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700809 params_->SetDlcNoUpdate(app.id);
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800810 continue;
811 }
Sen Jiang00adf7b2017-06-26 15:57:29 -0700812 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -0700813 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700814 output_object->update_exists = false;
815 break;
Sen Jiang81259682017-03-30 15:11:30 -0700816 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700817 auto const& attr_no_update =
818 app.action_postinstall_attrs.find(kAttrNoUpdate);
819 if (attr_no_update != app.action_postinstall_attrs.end() &&
820 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700821 // noupdate="true" in postinstall attributes means it's an update to
822 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -0700823 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700824 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700825 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700826 output_object->update_exists = true;
827 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700828 } else if (status.empty() && params_->is_install() &&
829 params_->GetAppId() == app.id) {
830 // Skips the platform app for install operation.
831 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -0700832 } else {
833 LOG(ERROR) << "Unknown Omaha response status: " << status;
834 completer->set_code(ErrorCode::kOmahaResponseInvalid);
835 return false;
836 }
837 }
838 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700839 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700840 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700841 }
842
Sen Jiang81259682017-03-30 15:11:30 -0700843 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700844}
845
David Zeuthene8ed8632014-07-24 13:38:10 -0400846bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700847 OmahaResponse* output_object,
848 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700849 map<string, string> attrs;
850 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700851 if (app.id == params_->GetAppId()) {
852 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -0700853 output_object->version = app.manifest_version;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700854 } else if (params_->is_install() &&
855 app.manifest_version != params_->app_version()) {
856 LOG(WARNING) << "An app has a different version (" << app.manifest_version
857 << ") that is different than platform app version ("
Amin Hassanida35b872020-11-04 17:54:44 -0800858 << params_->app_version() << ").";
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700859 }
860 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700861 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700862 }
Sen Jiang81259682017-03-30 15:11:30 -0700863 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700864 if (params_->is_install()) {
865 LOG(INFO) << "Use request version for Install operation.";
866 output_object->version = params_->app_version();
867 }
Chris Sosa3b748432013-06-20 16:42:59 -0700868 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700869 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700870 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700871 return false;
872 }
873
David Zeuthene8ed8632014-07-24 13:38:10 -0400874 if (attrs.empty()) {
Amin Hassanida35b872020-11-04 17:54:44 -0800875 LOG(ERROR) << "Omaha Response has no postinstall event action.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700876 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700877 return false;
878 }
879
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800880 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -0700881 output_object->more_info_url = attrs[kAttrMoreInfo];
882 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
883 output_object->deadline = attrs[kAttrDeadline];
884 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700885 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -0700886 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700887 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -0700888 ParseBool(attrs[kAttrDisableP2PForSharing]);
889 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800890
Amin Hassani6600a562018-09-24 15:17:19 -0700891 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800892 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800893 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700894
Jay Srinivasan08262882012-12-28 19:29:43 -0800895 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -0700896 ParseBool(attrs[kAttrDisablePayloadBackoff]);
897 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800898
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700899 return true;
900}
901
David Zeuthene8ed8632014-07-24 13:38:10 -0400902// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000903// and fill in the appropriate fields of the output object. Also, notifies
904// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800905void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -0700906 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000907 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800908 string current_response(response_buffer_.begin(), response_buffer_.end());
909 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700910
Gilad Arnold74b5f552014-10-07 08:17:16 -0700911 PayloadStateInterface* const payload_state = system_state_->payload_state();
912
Zentaro Kavanagh76af2662018-05-15 10:54:53 -0700913 // Set the max kernel key version based on whether rollback is allowed.
914 SetMaxKernelKeyVersionForRollback();
915
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700916 // Events are best effort transactions -- assume they always succeed.
917 if (IsEvent()) {
918 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700919 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700920 return;
921 }
922
Amin Hassanid3d84212019-08-17 00:27:44 -0700923 ErrorCode aux_error_code = fetcher->GetAuxiliaryErrorCode();
924 if (aux_error_code != ErrorCode::kSuccess) {
925 metrics::DownloadErrorCode download_error_code =
926 metrics_utils::GetDownloadErrorCode(aux_error_code);
927 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
928 system_state_,
929 metrics::CheckResult::kUnset,
930 metrics::CheckReaction::kUnset,
931 download_error_code);
932 }
933
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700934 if (!successful) {
Darin Petkovedc522e2010-11-05 09:35:17 -0700935 int code = GetHTTPResponseCode();
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700936 LOG(ERROR) << "Omaha request network transfer failed with HTTPResponseCode="
937 << code;
Saint Chou6431c332020-07-29 14:04:14 +0000938 // Makes sure we send proper error values.
Darin Petkovedc522e2010-11-05 09:35:17 -0700939 if (code < 0 || code >= 1000) {
940 code = 999;
Saint Chou6431c332020-07-29 14:04:14 +0000941 LOG(WARNING) << "Converting to proper HTTPResponseCode=" << code;
Darin Petkovedc522e2010-11-05 09:35:17 -0700942 }
David Zeuthena99981f2013-04-29 13:42:47 -0700943 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700944 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000945 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700946 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000947
David Zeuthene8ed8632014-07-24 13:38:10 -0400948 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400949 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400950 XML_SetUserData(parser, &parser_data);
951 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400952 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800953 XML_Status res =
954 XML_Parse(parser,
955 reinterpret_cast<const char*>(response_buffer_.data()),
956 response_buffer_.size(),
957 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400958
959 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700960 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800961 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
962 << XML_GetCurrentLineNumber(parser) << " col "
963 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -0700964 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400965 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
966 if (response_buffer_.empty()) {
967 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
968 } else if (parser_data.entity_decl) {
969 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
970 }
971 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000972 return;
973 }
Amin Hassani91f48b42018-08-06 17:47:14 -0700974 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000975
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700976 // Update the last ping day preferences based on the server daystart response
977 // even if we didn't send a ping. Omaha always includes the daystart in the
978 // response, but log the error if it didn't.
979 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
980 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700981
Amin Hassani1677e812017-06-21 13:36:36 -0700982 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
983 // we have got a response from omaha and if its value has never been set to
984 // true before. Failure of this function should be ignored. There should be no
985 // need to check if a=-1 has been sent because older devices have already sent
986 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
987 // future checks.
988 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700989 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
990 system_state_->metrics_reporter()->ReportInternalErrorCode(
991 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
992 }
Amin Hassani1677e812017-06-21 13:36:36 -0700993 }
994
Andrewe045aef2020-01-08 16:29:22 -0800995 // Create/update the metadata files for each DLC app received.
996 StorePingReply(parser_data);
997
Thieu Le116fda32011-04-19 11:01:54 -0700998 if (!HasOutputPipe()) {
999 // Just set success to whether or not the http transfer succeeded,
1000 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001001 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001002 return;
1003 }
1004
Darin Petkov6a5b3222010-07-13 14:55:28 -07001005 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001006 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001007 return;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001008 ProcessExclusions(&output_object,
Jae Hoon Kim3e69b4c2020-06-16 09:23:39 -07001009 system_state_->request_params(),
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001010 system_state_->update_attempter()->GetExcluder());
David Zeuthen8f191b22013-08-06 12:27:50 -07001011 output_object.update_exists = true;
1012 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001013
Toni Barzic61544e62018-10-11 14:37:30 -07001014 LoadOrPersistUpdateFirstSeenAtPref();
1015
Weidong Guo421ff332017-04-17 10:08:38 -07001016 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -07001017 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -07001018 // No need to change output_object.update_exists here, since the value
1019 // has been output to the pipe.
1020 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001021 return;
1022 }
1023
David Zeuthen8f191b22013-08-06 12:27:50 -07001024 // If Omaha says to disable p2p, respect that
1025 if (output_object.disable_p2p_for_downloading) {
1026 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1027 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001028 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001029 }
1030 if (output_object.disable_p2p_for_sharing) {
1031 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1032 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001033 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001034 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001035
1036 // Update the payload state with the current response. The payload state
1037 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001038 // from what's stored already. We are updating the payload state as late
1039 // as possible in this method so that if a new release gets pushed and then
1040 // got pulled back due to some issues, we don't want to clear our internal
1041 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001042 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001043
David Zeuthen8f191b22013-08-06 12:27:50 -07001044 // It could be we've already exceeded the deadline for when p2p is
1045 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001046 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001047 payload_state->P2PNewAttempt();
1048 if (!payload_state->P2PAttemptAllowed()) {
1049 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1050 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001051 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001052 }
1053 }
1054
1055 // From here on, we'll complete stuff in CompleteProcessing() so
1056 // disable |completer| since we'll create a new one in that
1057 // function.
1058 completer.set_should_complete(false);
1059
1060 // If we're allowed to use p2p for downloading we do not pay
1061 // attention to wall-clock-based waiting if the URL is indeed
1062 // available via p2p. Therefore, check if the file is available via
1063 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001064 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001065 LookupPayloadViaP2P(output_object);
1066 } else {
1067 CompleteProcessing();
1068 }
1069}
1070
1071void OmahaRequestAction::CompleteProcessing() {
1072 ScopedActionCompleter completer(processor_, this);
1073 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1074 PayloadStateInterface* payload_state = system_state_->payload_state();
1075
1076 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001077 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001078 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001079 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001080 return;
1081 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001082
Chris Sosa20f005c2013-09-05 13:53:08 -07001083 if (payload_state->ShouldBackoffDownload()) {
1084 output_object.update_exists = false;
1085 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
Amin Hassanida35b872020-11-04 17:54:44 -08001086 << "attempts.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001087 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001088 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001089 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001090 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001091}
1092
1093void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1094 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1095 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001096 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001097 } else {
1098 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1099 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001100 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001101 }
1102 CompleteProcessing();
1103}
1104
1105void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001106 // If the device is in the middle of an update, the state variables
1107 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1108 // tracks the offset and length of the operation currently in
1109 // progress. The offset is based from the end of the manifest which
1110 // is kPrefsManifestMetadataSize bytes long.
1111 //
1112 // To make forward progress and avoid deadlocks, we need to find a
1113 // peer that has at least the entire operation we're currently
1114 // working on. Otherwise we may end up in a situation where two
1115 // devices bounce back and forth downloading from each other,
1116 // neither making any forward progress until one of them decides to
1117 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1118 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001119 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001120 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001121 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001122 int64_t next_data_offset = 0;
1123 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001124 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001125 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1126 &manifest_metadata_size) &&
1127 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001128 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1129 &manifest_signature_size) &&
1130 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001131 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001132 &next_data_offset) &&
1133 next_data_offset != -1 &&
1134 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1135 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001136 minimum_size = manifest_metadata_size + manifest_signature_size +
1137 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001138 }
1139
Sen Jiang0affc2c2017-02-10 15:55:05 -08001140 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001141 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001142 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001143 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001144 string file_id =
1145 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001146 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001147 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1148 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001149 system_state_->p2p_manager()->LookupUrlForFile(
1150 file_id,
1151 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001152 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001153 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1154 base::Unretained(this)));
1155 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001156}
1157
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001158bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001159 if (params_->interactive()) {
1160 LOG(INFO) << "Not deferring download because update is interactive.";
1161 return false;
1162 }
1163
David Zeuthen8f191b22013-08-06 12:27:50 -07001164 // If we're using p2p to download _and_ we have a p2p URL, we never
1165 // defer the download. This is because the download will always
1166 // happen from a peer on the LAN and we've been waiting in line for
1167 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001168 const PayloadStateInterface* payload_state = system_state_->payload_state();
1169 if (payload_state->GetUsingP2PForDownloading() &&
1170 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001171 LOG(INFO) << "Download not deferred because download "
1172 << "will happen from a local peer (via p2p).";
1173 return false;
1174 }
1175
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001176 // We should defer the downloads only if we've first satisfied the
1177 // wall-clock-based-waiting period and then the update-check-based waiting
1178 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001179 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001180 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1181 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001182 return false;
1183 }
1184
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001185 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001186 case kWallClockWaitNotSatisfied:
1187 // We haven't even satisfied the first condition, passing the
1188 // wall-clock-based waiting period, so we should defer the downloads
1189 // until that happens.
1190 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1191 return true;
1192
1193 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1194 LOG(INFO) << "wall-clock-based-wait satisfied and "
1195 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001196 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001197
1198 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1199 // Wall-clock-based waiting period is satisfied, and it's determined
1200 // that we do not need the update-check-based wait. so no need to
1201 // defer downloads.
1202 LOG(INFO) << "wall-clock-based-wait satisfied and "
1203 << "update-check-based-wait is not required.";
1204 return false;
1205
1206 default:
1207 // Returning false for this default case so we err on the
1208 // side of downloading updates than deferring in case of any bugs.
1209 NOTREACHED();
1210 return false;
1211 }
1212}
1213
1214OmahaRequestAction::WallClockWaitResult
1215OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001216 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001217 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1218 if (update_first_seen_at == base::Time()) {
1219 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
Amin Hassanida35b872020-11-04 17:54:44 -08001220 "persisted.";
May Lippert60aa3ca2018-08-15 16:55:29 -07001221 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001222 }
1223
Sen Jiang7c1171e2016-06-23 11:35:40 -07001224 TimeDelta elapsed_time =
1225 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1226 TimeDelta max_scatter_period =
1227 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001228 int64_t staging_wait_time_in_days = 0;
1229 // Use staging and its default max value if staging is on.
1230 if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1231 &staging_wait_time_in_days) &&
1232 staging_wait_time_in_days > 0)
1233 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001234
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001235 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001236 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001237 << ", Time Elapsed = "
1238 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001239 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001240
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001241 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001242 // The deadline is set for all rules which serve a delta update from a
1243 // previous FSI, which means this update will be applied mostly in OOBE
1244 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1245 // quickly.
Amin Hassanida35b872020-11-04 17:54:44 -08001246 LOG(INFO) << "Not scattering as deadline flag is set.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001247 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1248 }
1249
1250 if (max_scatter_period.InDays() == 0) {
1251 // This means the Omaha rule creator decides that this rule
1252 // should not be scattered irrespective of the policy.
1253 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1254 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1255 }
1256
1257 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001258 // This means we've waited more than the upperbound wait in the rule
1259 // from the time we first saw a valid update available to us.
1260 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001261 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1262 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1263 }
1264
1265 // This means we are required to participate in scattering.
1266 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001267 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001268 if (remaining_wait_time.InSeconds() <= 0) {
1269 // Yes, it's our turn now.
1270 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1271
1272 // But we can't download until the update-check-count-based wait is also
1273 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001274 return params_->update_check_count_wait_enabled()
1275 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1276 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001277 }
1278
1279 // Not our turn yet, so we have to wait until our turn to
1280 // help scatter the downloads across all clients of the enterprise.
1281 LOG(INFO) << "Update deferred for another "
1282 << utils::FormatSecs(remaining_wait_time.InSeconds())
1283 << " per policy.";
1284 return kWallClockWaitNotSatisfied;
1285}
1286
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001287bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001288 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001289
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001290 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1291 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1292 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001293 // We are unable to read the update check count from file for some reason.
1294 // So let's proceed anyway so as to not stall the update.
1295 LOG(ERROR) << "Unable to read update check count. "
1296 << "Skipping update-check-count-based-wait.";
1297 return true;
1298 }
1299 } else {
1300 // This file does not exist. This means we haven't started our update
1301 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001302 update_check_count_value =
1303 base::RandInt(params_->min_update_checks_needed(),
1304 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001305
1306 LOG(INFO) << "Randomly picked update check count value = "
1307 << update_check_count_value;
1308
1309 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001310 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1311 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001312 // We weren't able to write the update check count file for some reason.
1313 // So let's proceed anyway so as to not stall the update.
1314 LOG(ERROR) << "Unable to write update check count. "
1315 << "Skipping update-check-count-based-wait.";
1316 return true;
1317 }
1318 }
1319
1320 if (update_check_count_value == 0) {
1321 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1322 return true;
1323 }
1324
1325 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001326 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001327 // We err on the side of skipping scattering logic instead of stalling
1328 // a machine from receiving any updates in case of any unexpected state.
1329 LOG(ERROR) << "Invalid value for update check count detected. "
1330 << "Skipping update-check-count-based-wait.";
1331 return true;
1332 }
1333
1334 // Legal value, we need to wait for more update checks to happen
1335 // until this becomes 0.
1336 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001337 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001338 return false;
1339}
1340
David Zeuthen639aa362014-02-03 16:23:44 -08001341// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001342bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001343 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001344 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001345 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001346 return false;
1347
1348 if (elapsed_days < 0)
1349 return false;
1350
1351 output_object->install_date_days = elapsed_days;
1352 return true;
1353}
1354
1355// static
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001356bool OmahaRequestAction::HasInstallDate(SystemState* system_state) {
David Zeuthen639aa362014-02-03 16:23:44 -08001357 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001358 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001359 return false;
1360
1361 return prefs->Exists(kPrefsInstallDateDays);
1362}
1363
1364// static
1365bool OmahaRequestAction::PersistInstallDate(
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001366 SystemState* system_state,
David Zeuthen639aa362014-02-03 16:23:44 -08001367 int install_date_days,
1368 InstallDateProvisioningSource source) {
1369 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1370
1371 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001372 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001373 return false;
1374
1375 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1376 return false;
1377
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001378 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001379 static_cast<int>(source), // Sample.
1380 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001381 return true;
1382}
1383
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001384void OmahaRequestAction::PersistCohortData(const string& prefs_key,
1385 const Optional<string>& new_value) {
1386 if (!new_value)
1387 return;
1388 const string& value = new_value.value();
1389 if (value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1390 if (!system_state_->prefs()->Delete(prefs_key))
1391 LOG(ERROR) << "Failed to remove stored " << prefs_key << "value.";
1392 else
1393 LOG(INFO) << "Removed stored " << prefs_key << " value.";
1394 } else if (!value.empty()) {
1395 if (!system_state_->prefs()->SetString(prefs_key, value))
1396 LOG(INFO) << "Failed to store new setting " << prefs_key << " as "
1397 << value;
1398 else
1399 LOG(INFO) << "Stored cohort setting " << prefs_key << " as " << value;
Alex Deymo8e18f932015-03-27 16:16:59 -07001400 }
Jae Hoon Kime2cac612020-11-02 18:30:29 -08001401}
1402
1403void OmahaRequestAction::PersistCohorts(const OmahaParserData& parser_data) {
1404 for (const auto& app : parser_data.apps) {
1405 // For platform App ID.
1406 if (app.id == params_->GetAppId()) {
1407 PersistCohortData(kPrefsOmahaCohort, app.cohort);
1408 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
1409 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
1410 } else if (params_->IsDlcAppId(app.id)) {
1411 string dlc_id;
1412 if (!params_->GetDlcId(app.id, &dlc_id)) {
1413 LOG(WARNING) << "Skip persisting cohorts for DLC App ID=" << app.id
1414 << " as it is not in the request params.";
1415 continue;
1416 }
1417 PrefsInterface* prefs = system_state_->prefs();
1418 PersistCohortData(
1419 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohort}),
1420 app.cohort);
1421 PersistCohortData(
1422 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohortName}),
1423 app.cohortname);
1424 PersistCohortData(
1425 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsOmahaCohortHint}),
1426 app.cohorthint);
1427 } else {
1428 LOG(WARNING) << "Skip persisting cohorts for unknown App ID=" << app.id;
1429 }
1430 }
Alex Deymo8e18f932015-03-27 16:16:59 -07001431}
1432
Amin Hassani2cbb0692019-10-30 13:36:17 -07001433bool OmahaRequestAction::PersistEolInfo(const map<string, string>& attrs) {
Jae Hoon Kimb3146742019-11-07 13:24:24 -08001434 // If EOL date attribute is not sent, don't delete the old persisted EOL
1435 // date information.
Jae Hoon Kim051627a2019-09-03 12:56:32 -07001436 auto eol_date_attr = attrs.find(kAttrEolDate);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07001437 if (eol_date_attr != attrs.end()) {
1438 const auto& eol_date = eol_date_attr->second;
1439 if (!system_state_->prefs()->SetString(kPrefsOmahaEolDate, eol_date)) {
1440 LOG(ERROR) << "Setting EOL date failed.";
1441 return false;
1442 }
1443 LOG(INFO) << "Set EOL date to " << eol_date;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001444 }
Amin Hassani2cbb0692019-10-30 13:36:17 -07001445 return true;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001446}
1447
David Zeuthen33bae492014-02-25 16:16:18 -08001448void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1449 // We only want to report this on "update check".
1450 if (ping_only_ || event_ != nullptr)
1451 return;
1452
1453 metrics::CheckResult result = metrics::CheckResult::kUnset;
1454 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1455 metrics::DownloadErrorCode download_error_code =
1456 metrics::DownloadErrorCode::kUnset;
1457
1458 // Regular update attempt.
1459 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001460 case ErrorCode::kSuccess:
1461 // OK, we parsed the response successfully but that does
1462 // necessarily mean that an update is available.
1463 if (HasOutputPipe()) {
1464 const OmahaResponse& response = GetOutputObject();
1465 if (response.update_exists) {
1466 result = metrics::CheckResult::kUpdateAvailable;
1467 reaction = metrics::CheckReaction::kUpdating;
1468 } else {
1469 result = metrics::CheckResult::kNoUpdateAvailable;
1470 }
David Zeuthen33bae492014-02-25 16:16:18 -08001471 } else {
1472 result = metrics::CheckResult::kNoUpdateAvailable;
1473 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001474 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001475
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001476 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1477 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1478 result = metrics::CheckResult::kUpdateAvailable;
1479 reaction = metrics::CheckReaction::kIgnored;
1480 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001481
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001482 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1483 result = metrics::CheckResult::kUpdateAvailable;
1484 reaction = metrics::CheckReaction::kDeferring;
1485 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001486
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001487 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1488 result = metrics::CheckResult::kUpdateAvailable;
1489 reaction = metrics::CheckReaction::kBackingOff;
1490 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001491
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001492 default:
1493 // We report two flavors of errors, "Download errors" and "Parsing
1494 // error". Try to convert to the former and if that doesn't work
1495 // we know it's the latter.
1496 metrics::DownloadErrorCode tmp_error =
1497 metrics_utils::GetDownloadErrorCode(code);
1498 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1499 result = metrics::CheckResult::kDownloadError;
1500 download_error_code = tmp_error;
1501 } else {
1502 result = metrics::CheckResult::kParsingError;
1503 }
1504 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001505 }
1506
Amin Hassanid3d84212019-08-17 00:27:44 -07001507 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1508 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001509}
1510
Toni Barzic61544e62018-10-11 14:37:30 -07001511bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1512 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001513 // Note: policy decision to not update to a version we rolled back from.
1514 string rollback_version =
1515 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001516 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001517 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001518 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001519 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001520 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001521 return true;
1522 }
1523 }
1524
Toni Barzic61544e62018-10-11 14:37:30 -07001525 if (system_state_->hardware()->IsOOBEEnabled() &&
1526 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
1527 (response.deadline.empty() ||
1528 system_state_->payload_state()->GetRollbackHappened()) &&
1529 params_->app_version() != "ForcedUpdate") {
1530 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1531 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1532 return true;
1533 }
1534
Weidong Guo421ff332017-04-17 10:08:38 -07001535 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001536 LOG(INFO) << "Update is not allowed over current connection.";
1537 return true;
1538 }
1539
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001540 // Currently non-critical updates always update alongside the platform update
1541 // (a critical update) so this case should never actually be hit if the
1542 // request to Omaha for updates are correct. In other words, stop the update
1543 // from happening as there are no packages in the response to process.
1544 if (response.packages.empty()) {
1545 LOG(ERROR) << "All packages were excluded.";
1546 }
1547
Chris Sosa77f79e82014-06-02 18:16:24 -07001548 // Note: We could technically delete the UpdateFirstSeenAt state when we
1549 // return true. If we do, it'll mean a device has to restart the
1550 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1551 // turned on again. On the other hand, it also increases the chance of update
1552 // starvation if an admin turns AU on/off more frequently. We choose to err on
1553 // the side of preventing starvation at the cost of not applying scattering in
1554 // those cases.
1555 return false;
1556}
1557
Weidong Guo421ff332017-04-17 10:08:38 -07001558bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1559 const OmahaResponse& response) const {
1560 PrefsInterface* prefs = system_state_->prefs();
1561
1562 if (!prefs) {
1563 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1564 "not available.";
1565 return false;
1566 }
1567
1568 bool is_allowed;
1569
1570 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1571 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1572 is_allowed) {
1573 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1574 "set to true.";
1575 return true;
1576 }
1577
1578 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1579 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1580 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1581 "set to false or does not exist while target does not exist.";
1582 return false;
1583 }
1584
1585 std::string target_version;
1586 int64_t target_size;
1587
1588 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1589 &target_version) ||
1590 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1591 LOG(INFO) << "Disabling updates over cellular as the target version or "
1592 "size is not accessible.";
1593 return false;
1594 }
1595
1596 uint64_t total_packages_size = 0;
1597 for (const auto& package : response.packages) {
1598 total_packages_size += package.size;
1599 }
1600 if (target_version == response.version &&
1601 static_cast<uint64_t>(target_size) == total_packages_size) {
1602 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1603 "omaha response.";
1604 return true;
1605 } else {
1606 LOG(INFO) << "Disabling updates over cellular as the target does not"
1607 "match the omaha response.";
1608 return false;
1609 }
1610}
1611
1612bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1613 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001614 ConnectionType type;
1615 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001616 ConnectionManagerInterface* connection_manager =
1617 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001618 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001619 LOG(INFO) << "We could not determine our connection type. "
1620 << "Defaulting to allow updates.";
1621 return true;
1622 }
Weidong Guo421ff332017-04-17 10:08:38 -07001623
Chris Sosa77f79e82014-06-02 18:16:24 -07001624 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001625 bool is_device_policy_set =
1626 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1627 // Treats tethered connection as if it is cellular connection.
1628 bool is_over_cellular = type == ConnectionType::kCellular ||
1629 tethering == ConnectionTethering::kConfirmed;
1630
1631 if (!is_over_cellular) {
1632 // There's no need to further check user preferences as we are not over
1633 // cellular connection.
1634 if (!is_allowed)
1635 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1636 } else if (is_device_policy_set) {
1637 // There's no need to further check user preferences as the device policy
1638 // is set regarding updates over cellular.
1639 if (!is_allowed)
1640 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1641 } else {
1642 // Deivce policy is not set, so user preferences overwrite whether to
1643 // allow updates over cellular.
1644 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1645 if (!is_allowed)
1646 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1647 }
1648
Chris Sosa77f79e82014-06-02 18:16:24 -07001649 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001650 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001651 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1652 return is_allowed;
1653}
1654
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001655bool OmahaRequestAction::IsRollbackEnabled() const {
1656 if (policy_provider_->IsConsumerDevice()) {
1657 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1658 return false;
1659 }
1660
1661 if (!policy_provider_->device_policy_is_loaded()) {
1662 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1663 return true;
1664 }
1665
1666 int allowed_milestones;
1667 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1668 &allowed_milestones)) {
1669 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1670 "Defaulting to rollback enabled.";
1671 return true;
1672 }
1673
1674 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1675 return allowed_milestones > 0;
1676}
1677
1678void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001679 int max_kernel_rollforward;
1680 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001681 if (IsRollbackEnabled()) {
1682 // If rollback is enabled, set the max kernel key version to the current
1683 // kernel key version. This has the effect of freezing kernel key roll
1684 // forwards.
1685 //
1686 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1687 // key roll forward happens until the server side components of rollback
1688 // are implemented. Future changes will allow the Omaha server to return
1689 // the kernel key version from max_rollback_versions in the past. At that
1690 // point the max kernel key version will be set to that value, creating a
1691 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001692 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001693 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001694 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001695 } else {
1696 // For devices that are not rollback enabled (ie. consumer devices), the
1697 // max kernel key version is set to 0xfffffffe, which is logically
1698 // infinity. This maintains the previous behavior that that kernel key
1699 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001700 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001701 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001702 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001703 }
1704
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001705 bool max_rollforward_set =
1706 system_state_->hardware()->SetMaxKernelKeyRollforward(
1707 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001708 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001709 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001710 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001711 // Report metrics
1712 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1713 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001714}
1715
May Lippert60aa3ca2018-08-15 16:55:29 -07001716base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1717 Time update_first_seen_at;
1718 int64_t update_first_seen_at_int;
1719 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1720 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1721 &update_first_seen_at_int)) {
1722 // Note: This timestamp could be that of ANY update we saw in the past
1723 // (not necessarily this particular update we're considering to apply)
1724 // but never got to apply because of some reason (e.g. stop AU policy,
1725 // updates being pulled out from Omaha, changes in target version prefix,
1726 // new update being rolled out, etc.). But for the purposes of scattering
1727 // it doesn't matter which update the timestamp corresponds to. i.e.
1728 // the clock starts ticking the first time we see an update and we're
1729 // ready to apply when the random wait period is satisfied relative to
1730 // that first seen timestamp.
1731 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1732 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1733 << utils::ToString(update_first_seen_at);
1734 } else {
1735 // This seems like an unexpected error where the persisted value exists
1736 // but it's not readable for some reason.
1737 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1738 return base::Time();
1739 }
1740 } else {
1741 update_first_seen_at = system_state_->clock()->GetWallclockTime();
1742 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
1743 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1744 update_first_seen_at_int)) {
1745 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1746 << utils::ToString(update_first_seen_at);
1747 } else {
1748 // This seems like an unexpected error where the value cannot be
1749 // persisted for some reason.
1750 LOG(INFO) << "UpdateFirstSeenAt value "
1751 << utils::ToString(update_first_seen_at)
1752 << " cannot be persisted";
1753 return base::Time();
1754 }
1755 }
1756 return update_first_seen_at;
1757}
1758
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001759} // namespace chromeos_update_engine