blob: 3a0b91c7c50eacb5f89a99479b70c058de980e1e [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
Darin Petkov6a5b3222010-07-13 14:55:28 -070017#include "update_engine/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"
47#include "update_engine/common/platform_constants.h"
Andrewe045aef2020-01-08 16:29:22 -080048#include "update_engine/common/prefs.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080049#include "update_engine/common/prefs_interface.h"
50#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070051#include "update_engine/connection_manager_interface.h"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070052#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080053#include "update_engine/metrics_utils.h"
Amin Hassani7fca2862019-03-28 16:09:22 -070054#include "update_engine/omaha_request_builder_xml.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070055#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070056#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080057#include "update_engine/payload_state_interface.h"
Jae Hoon Kim694eeb02020-06-01 14:24:08 -070058#include "update_engine/update_attempter.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";
101constexpr char kAttrHashSha256[] = "hash_sha256";
102// Deprecated: "hash"; Although we still need to pass it from the server for
103// backward compatibility.
104constexpr char kAttrName[] = "name";
105// Deprecated: "sha256"; Although we still need to pass it from the server for
106// backward compatibility.
107constexpr char kAttrSize[] = "size";
108constexpr char kAttrStatus[] = "status";
109
110// List of values that we interpret in the Omaha response:
111constexpr char kValPostInstall[] = "postinstall";
112constexpr char kValNoUpdate[] = "noupdate";
113
Alex Deymob3fa53b2016-04-18 19:57:58 -0700114// updatecheck attributes (without the underscore prefix).
Amin Hassani2cbb0692019-10-30 13:36:17 -0700115// Deprecated: "eol"
Jae Hoon Kim051627a2019-09-03 12:56:32 -0700116constexpr char kAttrEolDate[] = "eol_date";
Amin Hassani6600a562018-09-24 15:17:19 -0700117constexpr char kAttrRollback[] = "rollback";
118constexpr char kAttrFirmwareVersion[] = "firmware_version";
119constexpr char kAttrKernelVersion[] = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -0700120
David Zeuthene8ed8632014-07-24 13:38:10 -0400121// Struct used for holding data obtained when parsing the XML.
122struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400123 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
124
125 // Pointer to the expat XML_Parser object.
126 XML_Parser xml_parser;
127
David Zeuthene8ed8632014-07-24 13:38:10 -0400128 // This is the state of the parser as it's processing the XML.
129 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400130 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400131 string current_path;
132
133 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400134 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700135 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400136 string daystart_elapsed_days;
137 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800138
Sen Jiang81259682017-03-30 15:11:30 -0700139 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700140 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700141 vector<string> url_codebase;
142 string manifest_version;
143 map<string, string> action_postinstall_attrs;
144 string updatecheck_status;
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700145 Optional<string> cohort;
146 Optional<string> cohorthint;
147 Optional<string> cohortname;
Sen Jiang81259682017-03-30 15:11:30 -0700148
149 struct Package {
150 string name;
151 string size;
152 string hash;
153 };
154 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800155 };
Sen Jiang81259682017-03-30 15:11:30 -0700156 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400157};
158
159namespace {
160
161// Callback function invoked by expat.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800162void ParserHandlerStart(void* user_data,
163 const XML_Char* element,
David Zeuthene8ed8632014-07-24 13:38:10 -0400164 const XML_Char** attr) {
165 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
166
167 if (data->failed)
168 return;
169
170 data->current_path += string("/") + element;
171
172 map<string, string> attrs;
173 if (attr != nullptr) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800174 for (int n = 0; attr[n] != nullptr && attr[n + 1] != nullptr; n += 2) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400175 string key = attr[n];
176 string value = attr[n + 1];
177 attrs[key] = value;
178 }
179 }
180
Alex Deymo8e18f932015-03-27 16:16:59 -0700181 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700182 OmahaParserData::App app;
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700183 if (attrs.find(kAttrAppId) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700184 app.id = attrs[kAttrAppId];
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700185 if (attrs.find(kAttrCohort) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700186 app.cohort = attrs[kAttrCohort];
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700187 if (attrs.find(kAttrCohortHint) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700188 app.cohorthint = attrs[kAttrCohortHint];
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700189 if (attrs.find(kAttrCohortName) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700190 app.cohortname = attrs[kAttrCohortName];
Sen Jiangb1e063a2017-09-15 17:44:31 -0700191 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700192 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700193 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700194 data->apps.back().updatecheck_status = attrs[kAttrStatus];
Sen Jiang81259682017-03-30 15:11:30 -0700195 if (data->updatecheck_poll_interval.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700196 data->updatecheck_poll_interval = attrs[kAttrPollInterval];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700197 // Omaha sends arbitrary key-value pairs as extra attributes starting with
198 // an underscore.
199 for (const auto& attr : attrs) {
200 if (!attr.first.empty() && attr.first[0] == '_')
201 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
202 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400203 } else if (data->current_path == "/response/daystart") {
204 // Get the install-date.
Amin Hassani6600a562018-09-24 15:17:19 -0700205 data->daystart_elapsed_days = attrs[kAttrElapsedDays];
206 data->daystart_elapsed_seconds = attrs[kAttrElapsedSeconds];
David Zeuthene8ed8632014-07-24 13:38:10 -0400207 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
208 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700209 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700210 data->apps.back().url_codebase.push_back(attrs[kAttrCodeBase]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800211 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400212 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800213 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700214 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700215 data->apps.back().packages.push_back({.name = attrs[kAttrName],
216 .size = attrs[kAttrSize],
217 .hash = attrs[kAttrHashSha256]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400218 } else if (data->current_path == "/response/app/updatecheck/manifest") {
219 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700220 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700221 data->apps.back().manifest_version = attrs[kAttrVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400222 } else if (data->current_path ==
223 "/response/app/updatecheck/manifest/actions/action") {
224 // We only care about the postinstall action.
Amin Hassani6600a562018-09-24 15:17:19 -0700225 if (attrs[kAttrEvent] == kValPostInstall && !data->apps.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700226 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400227 }
228 }
229}
230
231// Callback function invoked by expat.
232void ParserHandlerEnd(void* user_data, const XML_Char* element) {
233 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
234 if (data->failed)
235 return;
236
237 const string path_suffix = string("/") + element;
238
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800239 if (!base::EndsWith(
240 data->current_path, path_suffix, base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400241 LOG(ERROR) << "Unexpected end element '" << element
242 << "' with current_path='" << data->current_path << "'";
243 data->failed = true;
244 return;
245 }
246 data->current_path.resize(data->current_path.size() - path_suffix.size());
247}
248
David Zeuthenf3e28012014-08-26 18:23:52 -0400249// Callback function invoked by expat.
250//
251// This is called for entity declarations. Since Omaha is guaranteed
252// to never return any XML with entities our course of action is to
253// just stop parsing. This avoids potential resource exhaustion
254// problems AKA the "billion laughs". CVE-2013-0340.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800255void ParserHandlerEntityDecl(void* user_data,
256 const XML_Char* entity_name,
David Zeuthenf3e28012014-08-26 18:23:52 -0400257 int is_parameter_entity,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800258 const XML_Char* value,
David Zeuthenf3e28012014-08-26 18:23:52 -0400259 int value_length,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800260 const XML_Char* base,
261 const XML_Char* system_id,
262 const XML_Char* public_id,
263 const XML_Char* notation_name) {
David Zeuthenf3e28012014-08-26 18:23:52 -0400264 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
265
266 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
267 data->failed = true;
268 data->entity_decl = true;
269 XML_StopParser(data->xml_parser, false);
270}
271
David Zeuthene8ed8632014-07-24 13:38:10 -0400272} // namespace
273
Alex Deymoc1c17b42015-11-23 03:53:15 -0300274OmahaRequestAction::OmahaRequestAction(
275 SystemState* system_state,
276 OmahaEvent* event,
277 std::unique_ptr<HttpFetcher> http_fetcher,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700278 bool ping_only,
279 const string& session_id)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800280 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800281 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700282 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300283 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800284 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700285 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700286 ping_active_days_(0),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700287 ping_roll_call_days_(0),
288 session_id_(session_id) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800289 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700290}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000291
Darin Petkov6a5b3222010-07-13 14:55:28 -0700292OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000293
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700294// Calculates the value to use for the ping days parameter.
295int OmahaRequestAction::CalculatePingDays(const string& key) {
Andrewe045aef2020-01-08 16:29:22 -0800296 int days = kPingNeverPinged;
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700297 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800298 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700299 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
300 if (days < 0) {
301 // If |days| is negative, then the system clock must have jumped
302 // back in time since the ping was sent. Mark the value so that
303 // it doesn't get sent to the server but we still update the
304 // last ping daystart preference. This way the next ping time
305 // will be correct, hopefully.
306 days = kPingTimeJump;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800307 LOG(WARNING)
308 << "System clock jumped back in time. Resetting ping daystarts.";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700309 }
310 }
311 return days;
312}
313
314void OmahaRequestAction::InitPingDays() {
315 // We send pings only along with update checks, not with events.
316 if (IsEvent()) {
317 return;
318 }
319 // TODO(petkov): Figure a way to distinguish active use pings
320 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700321 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700322 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
323 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
324}
325
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700326bool OmahaRequestAction::ShouldPing() const {
Andrewe045aef2020-01-08 16:29:22 -0800327 if (ping_active_days_ == kPingNeverPinged &&
328 ping_roll_call_days_ == kPingNeverPinged) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700329 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
330 if (powerwash_count > 0) {
331 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
332 << "powerwash_count is " << powerwash_count;
333 return false;
334 }
Amin Hassani1677e812017-06-21 13:36:36 -0700335 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
336 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
337 << "the first_active_omaha_ping_sent is true";
338 return false;
339 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700340 return true;
341 }
342 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
343}
344
David Zeuthen639aa362014-02-03 16:23:44 -0800345// static
346int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
347 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700348 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800349 return -1;
350
351 // If we have the value stored on disk, just return it.
352 int64_t stored_value;
353 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
354 // Convert and sanity-check.
355 int install_date_days = static_cast<int>(stored_value);
356 if (install_date_days >= 0)
357 return install_date_days;
358 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
359 << install_date_days << " looks suspicious.";
360 prefs->Delete(kPrefsInstallDateDays);
361 }
362
363 // Otherwise, if OOBE is not complete then do nothing and wait for
364 // ParseResponse() to call ParseInstallDate() and then
365 // PersistInstallDate() to set the kPrefsInstallDateDays state
366 // variable. Once that is done, we'll then report back in future
367 // Omaha requests. This works exactly because OOBE triggers an
368 // update check.
369 //
370 // However, if OOBE is complete and the kPrefsInstallDateDays state
371 // variable is not set, there are two possibilities
372 //
373 // 1. The update check in OOBE failed so we never got a response
374 // from Omaha (no network etc.); or
375 //
376 // 2. OOBE was done on an older version that didn't write to the
377 // kPrefsInstallDateDays state variable.
378 //
379 // In both cases, we approximate the install date by simply
380 // inspecting the timestamp of when OOBE happened.
381
382 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700383 if (!system_state->hardware()->IsOOBEEnabled() ||
384 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800385 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700386 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800387 return -1;
388 }
389
390 int num_days;
391 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
392 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
393 << "as its value '" << utils::ToString(time_of_oobe)
394 << "' looks suspicious.";
395 return -1;
396 }
397
398 // Persist this to disk, for future use.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800399 if (!OmahaRequestAction::PersistInstallDate(
400 system_state, num_days, kProvisionedFromOOBEMarker))
David Zeuthen639aa362014-02-03 16:23:44 -0800401 return -1;
402
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800403 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to " << num_days
404 << " days";
David Zeuthen639aa362014-02-03 16:23:44 -0800405
406 return num_days;
407}
408
Andrewe045aef2020-01-08 16:29:22 -0800409void OmahaRequestAction::StorePingReply(
410 const OmahaParserData& parser_data) const {
411 for (const auto& app : parser_data.apps) {
412 auto it = params_->dlc_apps_params().find(app.id);
413 if (it == params_->dlc_apps_params().end())
414 continue;
415
416 const OmahaRequestParams::AppParams& dlc_params = it->second;
Andrew065d78d2020-04-07 15:43:07 -0700417 const string& dlc_id = dlc_params.name;
Andrewe045aef2020-01-08 16:29:22 -0800418 // Skip if the ping for this DLC was not sent.
419 if (!dlc_params.send_ping)
420 continue;
421
Andrew065d78d2020-04-07 15:43:07 -0700422 PrefsInterface* prefs = system_state_->prefs();
Andrewe045aef2020-01-08 16:29:22 -0800423 // Reset the active metadata value to |kPingInactiveValue|.
Andrew065d78d2020-04-07 15:43:07 -0700424 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -0700425 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -0700426 if (!prefs->SetInt64(active_key, kPingInactiveValue))
427 LOG(ERROR) << "Failed to set the value of ping metadata '" << active_key
428 << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800429
Andrew065d78d2020-04-07 15:43:07 -0700430 auto last_rollcall_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -0700431 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -0700432 if (!prefs->SetString(last_rollcall_key, parser_data.daystart_elapsed_days))
Andrewe045aef2020-01-08 16:29:22 -0800433 LOG(ERROR) << "Failed to set the value of ping metadata '"
Andrew065d78d2020-04-07 15:43:07 -0700434 << last_rollcall_key << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800435
436 if (dlc_params.ping_active) {
437 // Write the value of elapsed_days into |kPrefsPingLastActive| only if
438 // the previous ping was an active one.
Andrew065d78d2020-04-07 15:43:07 -0700439 auto last_active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -0700440 prefs->CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -0700441 if (!prefs->SetString(last_active_key, parser_data.daystart_elapsed_days))
Andrewe045aef2020-01-08 16:29:22 -0800442 LOG(ERROR) << "Failed to set the value of ping metadata '"
Andrew065d78d2020-04-07 15:43:07 -0700443 << last_active_key << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800444 }
445 }
446}
447
Darin Petkov6a5b3222010-07-13 14:55:28 -0700448void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000449 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700450 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700451 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700452 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700453 return;
454 }
David Zeuthen639aa362014-02-03 16:23:44 -0800455
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700456 OmahaRequestBuilderXml omaha_request(event_.get(),
457 params_,
458 ping_only_,
459 ShouldPing(), // include_ping
460 ping_active_days_,
461 ping_roll_call_days_,
462 GetInstallDate(system_state_),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700463 system_state_->prefs(),
464 session_id_);
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700465 string request_post = omaha_request.GetRequest();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700466
Sen Jiang42fa45e2018-03-12 11:02:14 -0700467 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700468 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
469 params_->interactive() ? "fg" : "bg");
470 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
471 http_fetcher_->SetHeader(
472 kXGoogleUpdateUpdater,
473 base::StringPrintf(
474 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
475
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800476 http_fetcher_->SetPostData(
477 request_post.data(), request_post.size(), kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700478 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700479 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700480 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000481}
482
Darin Petkov6a5b3222010-07-13 14:55:28 -0700483void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000484 http_fetcher_->TerminateTransfer();
485}
486
487// We just store the response in the buffer. Once we've received all bytes,
488// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700489bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800490 const void* bytes,
491 size_t length) {
492 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
493 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700494 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000495}
496
497namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000498
499// Parses a 64 bit base-10 int from a string and returns it. Returns 0
500// on error. If the string contains "0", that's indistinguishable from
501// error.
502off_t ParseInt(const string& str) {
503 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700504 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000505 if (rc < 1) {
506 // failure
507 return 0;
508 }
509 return ret;
510}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700511
David Zeuthene8ed8632014-07-24 13:38:10 -0400512// Parses |str| and returns |true| if, and only if, its value is "true".
513bool ParseBool(const string& str) {
514 return str == "true";
515}
516
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700517// Update the last ping day preferences based on the server daystart
518// response. Returns true on success, false otherwise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800519bool UpdateLastPingDays(OmahaParserData* parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700520 int64_t elapsed_seconds = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800521 TEST_AND_RETURN_FALSE(base::StringToInt64(
522 parser_data->daystart_elapsed_seconds, &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700523 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
524
525 // Remember the local time that matches the server's last midnight
526 // time.
527 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
528 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
529 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
530 return true;
531}
Sen Jiang81259682017-03-30 15:11:30 -0700532
533// Parses the package node in the given XML document and populates
534// |output_object| if valid. Returns true if we should continue the parsing.
535// False otherwise, in which case it sets any error code using |completer|.
536bool ParsePackage(OmahaParserData::App* app,
537 OmahaResponse* output_object,
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700538 bool can_exclude,
Sen Jiang81259682017-03-30 15:11:30 -0700539 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700540 if (app->updatecheck_status.empty() ||
541 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700542 if (!app->packages.empty()) {
543 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
544 completer->set_code(ErrorCode::kOmahaResponseInvalid);
545 return false;
546 }
547 return true;
548 }
549 if (app->packages.empty()) {
550 LOG(ERROR) << "Omaha Response has no packages";
551 completer->set_code(ErrorCode::kOmahaResponseInvalid);
552 return false;
553 }
554 if (app->url_codebase.empty()) {
555 LOG(ERROR) << "No Omaha Response URLs";
556 completer->set_code(ErrorCode::kOmahaResponseInvalid);
557 return false;
558 }
559 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
560 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700561 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700562 ":",
563 base::TRIM_WHITESPACE,
564 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700565 vector<string> metadata_signatures = base::SplitString(
566 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
567 ":",
568 base::TRIM_WHITESPACE,
569 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700570 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700571 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700572 ":",
573 base::TRIM_WHITESPACE,
574 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700575 for (size_t i = 0; i < app->packages.size(); i++) {
576 const auto& package = app->packages[i];
577 if (package.name.empty()) {
578 LOG(ERROR) << "Omaha Response has empty package name";
579 completer->set_code(ErrorCode::kOmahaResponseInvalid);
580 return false;
581 }
582 LOG(INFO) << "Found package " << package.name;
583
584 OmahaResponse::Package out_package;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700585 out_package.can_exclude = can_exclude;
Sen Jiang81259682017-03-30 15:11:30 -0700586 for (const string& codebase : app->url_codebase) {
587 if (codebase.empty()) {
588 LOG(ERROR) << "Omaha Response URL has empty codebase";
589 completer->set_code(ErrorCode::kOmahaResponseInvalid);
590 return false;
591 }
592 out_package.payload_urls.push_back(codebase + package.name);
593 }
594 // Parse the payload size.
595 base::StringToUint64(package.size, &out_package.size);
596 if (out_package.size <= 0) {
597 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
598 completer->set_code(ErrorCode::kOmahaResponseInvalid);
599 return false;
600 }
601 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
602
603 if (i < metadata_sizes.size())
604 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
605 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
606 << " bytes";
607
608 if (i < metadata_signatures.size())
609 out_package.metadata_signature = metadata_signatures[i];
610 LOG(INFO) << "Payload metadata signature = "
611 << out_package.metadata_signature;
612
613 out_package.hash = package.hash;
614 if (out_package.hash.empty()) {
615 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
616 completer->set_code(ErrorCode::kOmahaResponseInvalid);
617 return false;
618 }
619 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700620
621 if (i < is_delta_payloads.size())
622 out_package.is_delta = ParseBool(is_delta_payloads[i]);
623 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
624
Sen Jiang81259682017-03-30 15:11:30 -0700625 output_object->packages.push_back(std::move(out_package));
626 }
627
628 return true;
629}
630
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700631// Removes the candidate URLs which are excluded within packages, if all the
632// candidate URLs are excluded within a package, the package will be excluded.
633void ProcessExclusions(OmahaResponse* output_object,
634 ExcluderInterface* excluder) {
635 for (auto package_it = output_object->packages.begin();
636 package_it != output_object->packages.end();
637 /* Increment logic in loop */) {
638 // If package cannot be excluded, quickly continue.
639 if (!package_it->can_exclude) {
640 ++package_it;
641 continue;
642 }
643 // Remove the excluded payload URLs.
644 for (auto payload_url_it = package_it->payload_urls.begin();
645 payload_url_it != package_it->payload_urls.end();
646 /* Increment logic in loop */) {
647 auto exclusion_name = utils::GetExclusionName(*payload_url_it);
648 // If payload URL is not excluded, quickly continue.
649 if (!excluder->IsExcluded(exclusion_name)) {
650 ++payload_url_it;
651 continue;
652 }
653 LOG(INFO) << "Excluding payload URL=" << *payload_url_it
654 << " for payload hash=" << package_it->hash;
655 payload_url_it = package_it->payload_urls.erase(payload_url_it);
656 }
657 // If there are no candidate payload URLs, remove the package.
658 if (package_it->payload_urls.empty()) {
659 LOG(INFO) << "Excluding payload hash=" << package_it->hash;
660 package_it = output_object->packages.erase(package_it);
661 continue;
662 }
663 ++package_it;
664 }
665}
666
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700667// Parses the 2 key version strings kernel_version and firmware_version. If the
668// field is not present, or cannot be parsed the values default to 0xffff.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700669void ParseRollbackVersions(int allowed_milestones,
670 OmahaParserData* parser_data,
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700671 OmahaResponse* output_object) {
672 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700673 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700674 &output_object->rollback_key_version.firmware_key,
675 &output_object->rollback_key_version.firmware);
676 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700677 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700678 &output_object->rollback_key_version.kernel_key,
679 &output_object->rollback_key_version.kernel);
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700680
681 // Create the attribute name strings for milestone N - allowed_milestones.
682 const string firmware_max_rollforward_attr =
683 base::StringPrintf("%s_%i", kAttrFirmwareVersion, allowed_milestones);
684 const string kernel_max_rollforward_attr =
685 base::StringPrintf("%s_%i", kAttrKernelVersion, allowed_milestones);
686
687 const bool max_firmware_and_kernel_exist =
688 parser_data->updatecheck_attrs.count(firmware_max_rollforward_attr) > 0 &&
689 parser_data->updatecheck_attrs.count(kernel_max_rollforward_attr) > 0;
690
691 string firmware_version;
692 string kernel_version;
693 if (max_firmware_and_kernel_exist) {
694 firmware_version =
695 parser_data->updatecheck_attrs[firmware_max_rollforward_attr];
696 kernel_version =
697 parser_data->updatecheck_attrs[kernel_max_rollforward_attr];
698 }
699
700 LOG(INFO) << "For milestone N-" << allowed_milestones
701 << " firmware_key_version=" << firmware_version
702 << " kernel_key_version=" << kernel_version;
703
704 OmahaResponse::RollbackKeyVersion version;
705 utils::ParseRollbackKeyVersion(
706 firmware_version, &version.firmware_key, &version.firmware);
707 utils::ParseRollbackKeyVersion(
708 kernel_version, &version.kernel_key, &version.kernel);
709
710 output_object->past_rollback_key_version = std::move(version);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700711}
712
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700713} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000714
David Zeuthene8ed8632014-07-24 13:38:10 -0400715bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700716 OmahaResponse* output_object,
717 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700718 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700719 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700720 return false;
721 }
Sen Jiang81259682017-03-30 15:11:30 -0700722 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700723
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800724 // chromium-os:37289: The PollInterval is not supported by Omaha server
725 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700726 // slow down the request rate from the server-side. Note that the PollInterval
727 // is not persisted, so it has to be sent by the server on every response to
728 // guarantee that the scheduler uses this value (otherwise, if the device got
729 // rebooted after the last server-indicated value, it'll revert to the default
730 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
731 // based on the assumption that we perform an update check every hour so that
732 // the max value of 8 will roughly be equivalent to one work day. If we decide
733 // to use PollInterval permanently, we should update the
734 // max_update_checks_allowed to take PollInterval into account. Note: The
735 // parsing for PollInterval happens even before parsing of the status because
736 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400737 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700738 &output_object->poll_interval);
739
David Zeuthen639aa362014-02-03 16:23:44 -0800740 // Check for the "elapsed_days" attribute in the "daystart"
741 // element. This is the number of days since Jan 1 2007, 0:00
742 // PST. If we don't have a persisted value of the Omaha InstallDate,
743 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400744 if (ParseInstallDate(parser_data, output_object) &&
745 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800746 // Since output_object->install_date_days is never negative, the
747 // elapsed_days -> install-date calculation is reduced to simply
748 // rounding down to the nearest number divisible by 7.
749 int remainder = output_object->install_date_days % 7;
750 int install_date_days_rounded =
751 output_object->install_date_days - remainder;
752 if (PersistInstallDate(system_state_,
753 install_date_days_rounded,
754 kProvisionedFromOmahaResponse)) {
755 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
756 << install_date_days_rounded << " days";
757 }
758 }
759
Alex Deymo00d79ac2015-06-29 15:41:49 -0700760 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700761 for (const auto& app : parser_data->apps) {
762 if (app.id == params_->GetAppId()) {
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700763 if (app.cohort)
764 PersistCohortData(kPrefsOmahaCohort, app.cohort.value());
765 if (app.cohorthint)
766 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint.value());
767 if (app.cohortname)
768 PersistCohortData(kPrefsOmahaCohortName, app.cohortname.value());
Sen Jiangb1e063a2017-09-15 17:44:31 -0700769 break;
770 }
771 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700772
Amin Hassani2cbb0692019-10-30 13:36:17 -0700773 PersistEolInfo(parser_data->updatecheck_attrs);
774
Marton Hunyady199152d2018-05-07 19:08:48 +0200775 // Rollback-related updatecheck attributes.
776 // Defaults to false if attribute is not present.
777 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -0700778 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700779
780 // Parses the rollback versions of the current image. If the fields do not
781 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700782 ParseRollbackVersions(
783 params_->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -0700784
David Zeuthene8ed8632014-07-24 13:38:10 -0400785 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700786 return false;
787
David Zeuthene8ed8632014-07-24 13:38:10 -0400788 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700789 return false;
790
Sen Jiang0affc2c2017-02-10 15:55:05 -0800791 // Package has to be parsed after Params now because ParseParams need to make
792 // sure that postinstall action exists.
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700793 for (auto& app : parser_data->apps) {
794 // Only allow exclusions for a non-critical package during an update. For
795 // non-critical package installations, let the errors propagate instead
796 // of being handled inside update_engine as installations are a dlcservice
797 // specific feature.
798 bool can_exclude = !params_->is_install() && params_->IsDlcAppId(app.id);
799 if (!ParsePackage(&app, output_object, can_exclude, completer))
Sen Jiang81259682017-03-30 15:11:30 -0700800 return false;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -0700801 }
Sen Jiang0affc2c2017-02-10 15:55:05 -0800802
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700803 return true;
804}
805
David Zeuthene8ed8632014-07-24 13:38:10 -0400806bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700807 OmahaResponse* output_object,
808 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700809 output_object->update_exists = false;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700810 for (const auto& app : parser_data->apps) {
811 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -0700812 if (status == kValNoUpdate) {
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800813 // If the app is a DLC, allow status "noupdate" to support DLC
814 // deprecations.
815 if (params_->IsDlcAppId(app.id)) {
816 LOG(INFO) << "No update for <app> " << app.id
817 << " but update continuing since a DLC.";
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700818 params_->SetDlcNoUpdate(app.id);
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800819 continue;
820 }
Sen Jiang00adf7b2017-06-26 15:57:29 -0700821 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -0700822 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700823 output_object->update_exists = false;
824 break;
Sen Jiang81259682017-03-30 15:11:30 -0700825 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700826 auto const& attr_no_update =
827 app.action_postinstall_attrs.find(kAttrNoUpdate);
828 if (attr_no_update != app.action_postinstall_attrs.end() &&
829 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700830 // noupdate="true" in postinstall attributes means it's an update to
831 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -0700832 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700833 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700834 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700835 output_object->update_exists = true;
836 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700837 } else if (status.empty() && params_->is_install() &&
838 params_->GetAppId() == app.id) {
839 // Skips the platform app for install operation.
840 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -0700841 } else {
842 LOG(ERROR) << "Unknown Omaha response status: " << status;
843 completer->set_code(ErrorCode::kOmahaResponseInvalid);
844 return false;
845 }
846 }
847 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700848 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700849 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700850 }
851
Sen Jiang81259682017-03-30 15:11:30 -0700852 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700853}
854
David Zeuthene8ed8632014-07-24 13:38:10 -0400855bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700856 OmahaResponse* output_object,
857 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700858 map<string, string> attrs;
859 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700860 if (app.id == params_->GetAppId()) {
861 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -0700862 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700863 } else if (!params_->system_app_id().empty() &&
864 app.id == params_->system_app_id()) {
865 // this is the system app (this check is intentionally skipped if there is
866 // no system_app_id set)
867 output_object->system_version = app.manifest_version;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700868 } else if (params_->is_install() &&
869 app.manifest_version != params_->app_version()) {
870 LOG(WARNING) << "An app has a different version (" << app.manifest_version
871 << ") that is different than platform app version ("
872 << params_->app_version() << ")";
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700873 }
874 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700875 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700876 }
Sen Jiang81259682017-03-30 15:11:30 -0700877 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700878 if (params_->is_install()) {
879 LOG(INFO) << "Use request version for Install operation.";
880 output_object->version = params_->app_version();
881 }
Chris Sosa3b748432013-06-20 16:42:59 -0700882 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700883 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700884 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700885 return false;
886 }
887
888 LOG(INFO) << "Received omaha response to update to version "
889 << output_object->version;
890
David Zeuthene8ed8632014-07-24 13:38:10 -0400891 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700892 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700893 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700894 return false;
895 }
896
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800897 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -0700898 output_object->more_info_url = attrs[kAttrMoreInfo];
899 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
900 output_object->deadline = attrs[kAttrDeadline];
901 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700902 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -0700903 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700904 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -0700905 ParseBool(attrs[kAttrDisableP2PForSharing]);
906 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800907
Amin Hassani6600a562018-09-24 15:17:19 -0700908 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800909 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800910 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700911
Jay Srinivasan08262882012-12-28 19:29:43 -0800912 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -0700913 ParseBool(attrs[kAttrDisablePayloadBackoff]);
914 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800915
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700916 return true;
917}
918
David Zeuthene8ed8632014-07-24 13:38:10 -0400919// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000920// and fill in the appropriate fields of the output object. Also, notifies
921// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800922void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -0700923 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000924 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800925 string current_response(response_buffer_.begin(), response_buffer_.end());
926 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700927
Gilad Arnold74b5f552014-10-07 08:17:16 -0700928 PayloadStateInterface* const payload_state = system_state_->payload_state();
929
Zentaro Kavanagh76af2662018-05-15 10:54:53 -0700930 // Set the max kernel key version based on whether rollback is allowed.
931 SetMaxKernelKeyVersionForRollback();
932
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700933 // Events are best effort transactions -- assume they always succeed.
934 if (IsEvent()) {
935 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700936 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700937 return;
938 }
939
Amin Hassanid3d84212019-08-17 00:27:44 -0700940 ErrorCode aux_error_code = fetcher->GetAuxiliaryErrorCode();
941 if (aux_error_code != ErrorCode::kSuccess) {
942 metrics::DownloadErrorCode download_error_code =
943 metrics_utils::GetDownloadErrorCode(aux_error_code);
944 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
945 system_state_,
946 metrics::CheckResult::kUnset,
947 metrics::CheckReaction::kUnset,
948 download_error_code);
949 }
950
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700951 if (!successful) {
Darin Petkovedc522e2010-11-05 09:35:17 -0700952 int code = GetHTTPResponseCode();
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700953 LOG(ERROR) << "Omaha request network transfer failed with HTTPResponseCode="
954 << code;
Darin Petkovedc522e2010-11-05 09:35:17 -0700955 // Makes sure we send sane error values.
956 if (code < 0 || code >= 1000) {
957 code = 999;
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700958 LOG(WARNING) << "Converting to sane HTTPResponseCode=" << code;
Darin Petkovedc522e2010-11-05 09:35:17 -0700959 }
David Zeuthena99981f2013-04-29 13:42:47 -0700960 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700961 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000962 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700963 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000964
David Zeuthene8ed8632014-07-24 13:38:10 -0400965 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400966 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400967 XML_SetUserData(parser, &parser_data);
968 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400969 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800970 XML_Status res =
971 XML_Parse(parser,
972 reinterpret_cast<const char*>(response_buffer_.data()),
973 response_buffer_.size(),
974 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400975
976 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700977 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800978 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
979 << XML_GetCurrentLineNumber(parser) << " col "
980 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -0700981 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400982 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
983 if (response_buffer_.empty()) {
984 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
985 } else if (parser_data.entity_decl) {
986 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
987 }
988 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000989 return;
990 }
Amin Hassani91f48b42018-08-06 17:47:14 -0700991 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000992
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700993 // Update the last ping day preferences based on the server daystart response
994 // even if we didn't send a ping. Omaha always includes the daystart in the
995 // response, but log the error if it didn't.
996 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
997 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700998
Amin Hassani1677e812017-06-21 13:36:36 -0700999 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1000 // we have got a response from omaha and if its value has never been set to
1001 // true before. Failure of this function should be ignored. There should be no
1002 // need to check if a=-1 has been sent because older devices have already sent
1003 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1004 // future checks.
1005 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -07001006 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
1007 system_state_->metrics_reporter()->ReportInternalErrorCode(
1008 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
1009 }
Amin Hassani1677e812017-06-21 13:36:36 -07001010 }
1011
Andrewe045aef2020-01-08 16:29:22 -08001012 // Create/update the metadata files for each DLC app received.
1013 StorePingReply(parser_data);
1014
Thieu Le116fda32011-04-19 11:01:54 -07001015 if (!HasOutputPipe()) {
1016 // Just set success to whether or not the http transfer succeeded,
1017 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001018 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001019 return;
1020 }
1021
Darin Petkov6a5b3222010-07-13 14:55:28 -07001022 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001023 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001024 return;
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001025 ProcessExclusions(&output_object,
1026 system_state_->update_attempter()->GetExcluder());
David Zeuthen8f191b22013-08-06 12:27:50 -07001027 output_object.update_exists = true;
1028 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001029
Toni Barzic61544e62018-10-11 14:37:30 -07001030 LoadOrPersistUpdateFirstSeenAtPref();
1031
Weidong Guo421ff332017-04-17 10:08:38 -07001032 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -07001033 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -07001034 // No need to change output_object.update_exists here, since the value
1035 // has been output to the pipe.
1036 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001037 return;
1038 }
1039
David Zeuthen8f191b22013-08-06 12:27:50 -07001040 // If Omaha says to disable p2p, respect that
1041 if (output_object.disable_p2p_for_downloading) {
1042 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1043 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001044 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001045 }
1046 if (output_object.disable_p2p_for_sharing) {
1047 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1048 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001049 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001050 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001051
1052 // Update the payload state with the current response. The payload state
1053 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001054 // from what's stored already. We are updating the payload state as late
1055 // as possible in this method so that if a new release gets pushed and then
1056 // got pulled back due to some issues, we don't want to clear our internal
1057 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001058 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001059
David Zeuthen8f191b22013-08-06 12:27:50 -07001060 // It could be we've already exceeded the deadline for when p2p is
1061 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001062 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001063 payload_state->P2PNewAttempt();
1064 if (!payload_state->P2PAttemptAllowed()) {
1065 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1066 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001067 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001068 }
1069 }
1070
1071 // From here on, we'll complete stuff in CompleteProcessing() so
1072 // disable |completer| since we'll create a new one in that
1073 // function.
1074 completer.set_should_complete(false);
1075
1076 // If we're allowed to use p2p for downloading we do not pay
1077 // attention to wall-clock-based waiting if the URL is indeed
1078 // available via p2p. Therefore, check if the file is available via
1079 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001080 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001081 LookupPayloadViaP2P(output_object);
1082 } else {
1083 CompleteProcessing();
1084 }
1085}
1086
1087void OmahaRequestAction::CompleteProcessing() {
1088 ScopedActionCompleter completer(processor_, this);
1089 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1090 PayloadStateInterface* payload_state = system_state_->payload_state();
1091
1092 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001093 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001094 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001095 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001096 return;
1097 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001098
Chris Sosa20f005c2013-09-05 13:53:08 -07001099 if (payload_state->ShouldBackoffDownload()) {
1100 output_object.update_exists = false;
1101 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1102 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001103 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001104 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001105 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001106 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001107}
1108
1109void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1110 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1111 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001112 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001113 } else {
1114 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1115 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001116 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001117 }
1118 CompleteProcessing();
1119}
1120
1121void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001122 // If the device is in the middle of an update, the state variables
1123 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1124 // tracks the offset and length of the operation currently in
1125 // progress. The offset is based from the end of the manifest which
1126 // is kPrefsManifestMetadataSize bytes long.
1127 //
1128 // To make forward progress and avoid deadlocks, we need to find a
1129 // peer that has at least the entire operation we're currently
1130 // working on. Otherwise we may end up in a situation where two
1131 // devices bounce back and forth downloading from each other,
1132 // neither making any forward progress until one of them decides to
1133 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1134 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001135 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001136 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001137 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001138 int64_t next_data_offset = 0;
1139 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001140 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001141 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1142 &manifest_metadata_size) &&
1143 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001144 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1145 &manifest_signature_size) &&
1146 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001147 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001148 &next_data_offset) &&
1149 next_data_offset != -1 &&
1150 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1151 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001152 minimum_size = manifest_metadata_size + manifest_signature_size +
1153 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001154 }
1155
Sen Jiang0affc2c2017-02-10 15:55:05 -08001156 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001157 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001158 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001159 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001160 string file_id =
1161 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001162 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001163 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1164 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001165 system_state_->p2p_manager()->LookupUrlForFile(
1166 file_id,
1167 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001168 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001169 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1170 base::Unretained(this)));
1171 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001172}
1173
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001174bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001175 if (params_->interactive()) {
1176 LOG(INFO) << "Not deferring download because update is interactive.";
1177 return false;
1178 }
1179
David Zeuthen8f191b22013-08-06 12:27:50 -07001180 // If we're using p2p to download _and_ we have a p2p URL, we never
1181 // defer the download. This is because the download will always
1182 // happen from a peer on the LAN and we've been waiting in line for
1183 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001184 const PayloadStateInterface* payload_state = system_state_->payload_state();
1185 if (payload_state->GetUsingP2PForDownloading() &&
1186 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001187 LOG(INFO) << "Download not deferred because download "
1188 << "will happen from a local peer (via p2p).";
1189 return false;
1190 }
1191
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001192 // We should defer the downloads only if we've first satisfied the
1193 // wall-clock-based-waiting period and then the update-check-based waiting
1194 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001195 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001196 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1197 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001198 return false;
1199 }
1200
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001201 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001202 case kWallClockWaitNotSatisfied:
1203 // We haven't even satisfied the first condition, passing the
1204 // wall-clock-based waiting period, so we should defer the downloads
1205 // until that happens.
1206 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1207 return true;
1208
1209 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1210 LOG(INFO) << "wall-clock-based-wait satisfied and "
1211 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001212 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001213
1214 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1215 // Wall-clock-based waiting period is satisfied, and it's determined
1216 // that we do not need the update-check-based wait. so no need to
1217 // defer downloads.
1218 LOG(INFO) << "wall-clock-based-wait satisfied and "
1219 << "update-check-based-wait is not required.";
1220 return false;
1221
1222 default:
1223 // Returning false for this default case so we err on the
1224 // side of downloading updates than deferring in case of any bugs.
1225 NOTREACHED();
1226 return false;
1227 }
1228}
1229
1230OmahaRequestAction::WallClockWaitResult
1231OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001232 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001233 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1234 if (update_first_seen_at == base::Time()) {
1235 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
1236 "persisted";
1237 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001238 }
1239
Sen Jiang7c1171e2016-06-23 11:35:40 -07001240 TimeDelta elapsed_time =
1241 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1242 TimeDelta max_scatter_period =
1243 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001244 int64_t staging_wait_time_in_days = 0;
1245 // Use staging and its default max value if staging is on.
1246 if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1247 &staging_wait_time_in_days) &&
1248 staging_wait_time_in_days > 0)
1249 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001250
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001251 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001252 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001253 << ", Time Elapsed = "
1254 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001255 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001256
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001257 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001258 // The deadline is set for all rules which serve a delta update from a
1259 // previous FSI, which means this update will be applied mostly in OOBE
1260 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1261 // quickly.
1262 LOG(INFO) << "Not scattering as deadline flag is set";
1263 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1264 }
1265
1266 if (max_scatter_period.InDays() == 0) {
1267 // This means the Omaha rule creator decides that this rule
1268 // should not be scattered irrespective of the policy.
1269 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1270 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1271 }
1272
1273 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001274 // This means we've waited more than the upperbound wait in the rule
1275 // from the time we first saw a valid update available to us.
1276 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001277 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1278 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1279 }
1280
1281 // This means we are required to participate in scattering.
1282 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001283 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001284 if (remaining_wait_time.InSeconds() <= 0) {
1285 // Yes, it's our turn now.
1286 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1287
1288 // But we can't download until the update-check-count-based wait is also
1289 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001290 return params_->update_check_count_wait_enabled()
1291 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1292 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001293 }
1294
1295 // Not our turn yet, so we have to wait until our turn to
1296 // help scatter the downloads across all clients of the enterprise.
1297 LOG(INFO) << "Update deferred for another "
1298 << utils::FormatSecs(remaining_wait_time.InSeconds())
1299 << " per policy.";
1300 return kWallClockWaitNotSatisfied;
1301}
1302
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001303bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001304 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001305
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001306 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1307 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1308 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001309 // We are unable to read the update check count from file for some reason.
1310 // So let's proceed anyway so as to not stall the update.
1311 LOG(ERROR) << "Unable to read update check count. "
1312 << "Skipping update-check-count-based-wait.";
1313 return true;
1314 }
1315 } else {
1316 // This file does not exist. This means we haven't started our update
1317 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001318 update_check_count_value =
1319 base::RandInt(params_->min_update_checks_needed(),
1320 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001321
1322 LOG(INFO) << "Randomly picked update check count value = "
1323 << update_check_count_value;
1324
1325 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001326 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1327 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001328 // We weren't able to write the update check count file for some reason.
1329 // So let's proceed anyway so as to not stall the update.
1330 LOG(ERROR) << "Unable to write update check count. "
1331 << "Skipping update-check-count-based-wait.";
1332 return true;
1333 }
1334 }
1335
1336 if (update_check_count_value == 0) {
1337 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1338 return true;
1339 }
1340
1341 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001342 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001343 // We err on the side of skipping scattering logic instead of stalling
1344 // a machine from receiving any updates in case of any unexpected state.
1345 LOG(ERROR) << "Invalid value for update check count detected. "
1346 << "Skipping update-check-count-based-wait.";
1347 return true;
1348 }
1349
1350 // Legal value, we need to wait for more update checks to happen
1351 // until this becomes 0.
1352 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001353 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001354 return false;
1355}
1356
David Zeuthen639aa362014-02-03 16:23:44 -08001357// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001358bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001359 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001360 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001361 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001362 return false;
1363
1364 if (elapsed_days < 0)
1365 return false;
1366
1367 output_object->install_date_days = elapsed_days;
1368 return true;
1369}
1370
1371// static
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001372bool OmahaRequestAction::HasInstallDate(SystemState* system_state) {
David Zeuthen639aa362014-02-03 16:23:44 -08001373 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001374 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001375 return false;
1376
1377 return prefs->Exists(kPrefsInstallDateDays);
1378}
1379
1380// static
1381bool OmahaRequestAction::PersistInstallDate(
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001382 SystemState* system_state,
David Zeuthen639aa362014-02-03 16:23:44 -08001383 int install_date_days,
1384 InstallDateProvisioningSource source) {
1385 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1386
1387 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001388 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001389 return false;
1390
1391 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1392 return false;
1393
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001394 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001395 static_cast<int>(source), // Sample.
1396 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001397 return true;
1398}
1399
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001400bool OmahaRequestAction::PersistCohortData(const string& prefs_key,
1401 const string& new_value) {
Alex Deymo8e18f932015-03-27 16:16:59 -07001402 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1403 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1404 return system_state_->prefs()->Delete(prefs_key);
1405 } else if (!new_value.empty()) {
1406 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1407 return system_state_->prefs()->SetString(prefs_key, new_value);
1408 }
1409 return true;
1410}
1411
Amin Hassani2cbb0692019-10-30 13:36:17 -07001412bool OmahaRequestAction::PersistEolInfo(const map<string, string>& attrs) {
Jae Hoon Kimb3146742019-11-07 13:24:24 -08001413 // If EOL date attribute is not sent, don't delete the old persisted EOL
1414 // date information.
Jae Hoon Kim051627a2019-09-03 12:56:32 -07001415 auto eol_date_attr = attrs.find(kAttrEolDate);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07001416 if (eol_date_attr != attrs.end()) {
1417 const auto& eol_date = eol_date_attr->second;
1418 if (!system_state_->prefs()->SetString(kPrefsOmahaEolDate, eol_date)) {
1419 LOG(ERROR) << "Setting EOL date failed.";
1420 return false;
1421 }
1422 LOG(INFO) << "Set EOL date to " << eol_date;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001423 }
Amin Hassani2cbb0692019-10-30 13:36:17 -07001424 return true;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001425}
1426
David Zeuthen33bae492014-02-25 16:16:18 -08001427void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1428 // We only want to report this on "update check".
1429 if (ping_only_ || event_ != nullptr)
1430 return;
1431
1432 metrics::CheckResult result = metrics::CheckResult::kUnset;
1433 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1434 metrics::DownloadErrorCode download_error_code =
1435 metrics::DownloadErrorCode::kUnset;
1436
1437 // Regular update attempt.
1438 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001439 case ErrorCode::kSuccess:
1440 // OK, we parsed the response successfully but that does
1441 // necessarily mean that an update is available.
1442 if (HasOutputPipe()) {
1443 const OmahaResponse& response = GetOutputObject();
1444 if (response.update_exists) {
1445 result = metrics::CheckResult::kUpdateAvailable;
1446 reaction = metrics::CheckReaction::kUpdating;
1447 } else {
1448 result = metrics::CheckResult::kNoUpdateAvailable;
1449 }
David Zeuthen33bae492014-02-25 16:16:18 -08001450 } else {
1451 result = metrics::CheckResult::kNoUpdateAvailable;
1452 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001453 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001454
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001455 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1456 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1457 result = metrics::CheckResult::kUpdateAvailable;
1458 reaction = metrics::CheckReaction::kIgnored;
1459 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001460
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001461 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1462 result = metrics::CheckResult::kUpdateAvailable;
1463 reaction = metrics::CheckReaction::kDeferring;
1464 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001465
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001466 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1467 result = metrics::CheckResult::kUpdateAvailable;
1468 reaction = metrics::CheckReaction::kBackingOff;
1469 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001470
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001471 default:
1472 // We report two flavors of errors, "Download errors" and "Parsing
1473 // error". Try to convert to the former and if that doesn't work
1474 // we know it's the latter.
1475 metrics::DownloadErrorCode tmp_error =
1476 metrics_utils::GetDownloadErrorCode(code);
1477 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1478 result = metrics::CheckResult::kDownloadError;
1479 download_error_code = tmp_error;
1480 } else {
1481 result = metrics::CheckResult::kParsingError;
1482 }
1483 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001484 }
1485
Amin Hassanid3d84212019-08-17 00:27:44 -07001486 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1487 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001488}
1489
Toni Barzic61544e62018-10-11 14:37:30 -07001490bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1491 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001492 // Note: policy decision to not update to a version we rolled back from.
1493 string rollback_version =
1494 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001495 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001496 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001497 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001498 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001499 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001500 return true;
1501 }
1502 }
1503
Toni Barzic61544e62018-10-11 14:37:30 -07001504 if (system_state_->hardware()->IsOOBEEnabled() &&
1505 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
1506 (response.deadline.empty() ||
1507 system_state_->payload_state()->GetRollbackHappened()) &&
1508 params_->app_version() != "ForcedUpdate") {
1509 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1510 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1511 return true;
1512 }
1513
Weidong Guo421ff332017-04-17 10:08:38 -07001514 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001515 LOG(INFO) << "Update is not allowed over current connection.";
1516 return true;
1517 }
1518
Jae Hoon Kim694eeb02020-06-01 14:24:08 -07001519 // Currently non-critical updates always update alongside the platform update
1520 // (a critical update) so this case should never actually be hit if the
1521 // request to Omaha for updates are correct. In other words, stop the update
1522 // from happening as there are no packages in the response to process.
1523 if (response.packages.empty()) {
1524 LOG(ERROR) << "All packages were excluded.";
1525 }
1526
Chris Sosa77f79e82014-06-02 18:16:24 -07001527 // Note: We could technically delete the UpdateFirstSeenAt state when we
1528 // return true. If we do, it'll mean a device has to restart the
1529 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1530 // turned on again. On the other hand, it also increases the chance of update
1531 // starvation if an admin turns AU on/off more frequently. We choose to err on
1532 // the side of preventing starvation at the cost of not applying scattering in
1533 // those cases.
1534 return false;
1535}
1536
Weidong Guo421ff332017-04-17 10:08:38 -07001537bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1538 const OmahaResponse& response) const {
1539 PrefsInterface* prefs = system_state_->prefs();
1540
1541 if (!prefs) {
1542 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1543 "not available.";
1544 return false;
1545 }
1546
1547 bool is_allowed;
1548
1549 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1550 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1551 is_allowed) {
1552 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1553 "set to true.";
1554 return true;
1555 }
1556
1557 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1558 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1559 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1560 "set to false or does not exist while target does not exist.";
1561 return false;
1562 }
1563
1564 std::string target_version;
1565 int64_t target_size;
1566
1567 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1568 &target_version) ||
1569 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1570 LOG(INFO) << "Disabling updates over cellular as the target version or "
1571 "size is not accessible.";
1572 return false;
1573 }
1574
1575 uint64_t total_packages_size = 0;
1576 for (const auto& package : response.packages) {
1577 total_packages_size += package.size;
1578 }
1579 if (target_version == response.version &&
1580 static_cast<uint64_t>(target_size) == total_packages_size) {
1581 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1582 "omaha response.";
1583 return true;
1584 } else {
1585 LOG(INFO) << "Disabling updates over cellular as the target does not"
1586 "match the omaha response.";
1587 return false;
1588 }
1589}
1590
1591bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1592 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001593 ConnectionType type;
1594 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001595 ConnectionManagerInterface* connection_manager =
1596 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001597 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001598 LOG(INFO) << "We could not determine our connection type. "
1599 << "Defaulting to allow updates.";
1600 return true;
1601 }
Weidong Guo421ff332017-04-17 10:08:38 -07001602
Chris Sosa77f79e82014-06-02 18:16:24 -07001603 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001604 bool is_device_policy_set =
1605 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1606 // Treats tethered connection as if it is cellular connection.
1607 bool is_over_cellular = type == ConnectionType::kCellular ||
1608 tethering == ConnectionTethering::kConfirmed;
1609
1610 if (!is_over_cellular) {
1611 // There's no need to further check user preferences as we are not over
1612 // cellular connection.
1613 if (!is_allowed)
1614 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1615 } else if (is_device_policy_set) {
1616 // There's no need to further check user preferences as the device policy
1617 // is set regarding updates over cellular.
1618 if (!is_allowed)
1619 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1620 } else {
1621 // Deivce policy is not set, so user preferences overwrite whether to
1622 // allow updates over cellular.
1623 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1624 if (!is_allowed)
1625 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1626 }
1627
Chris Sosa77f79e82014-06-02 18:16:24 -07001628 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001629 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001630 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1631 return is_allowed;
1632}
1633
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001634bool OmahaRequestAction::IsRollbackEnabled() const {
1635 if (policy_provider_->IsConsumerDevice()) {
1636 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1637 return false;
1638 }
1639
1640 if (!policy_provider_->device_policy_is_loaded()) {
1641 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1642 return true;
1643 }
1644
1645 int allowed_milestones;
1646 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1647 &allowed_milestones)) {
1648 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1649 "Defaulting to rollback enabled.";
1650 return true;
1651 }
1652
1653 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1654 return allowed_milestones > 0;
1655}
1656
1657void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001658 int max_kernel_rollforward;
1659 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001660 if (IsRollbackEnabled()) {
1661 // If rollback is enabled, set the max kernel key version to the current
1662 // kernel key version. This has the effect of freezing kernel key roll
1663 // forwards.
1664 //
1665 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1666 // key roll forward happens until the server side components of rollback
1667 // are implemented. Future changes will allow the Omaha server to return
1668 // the kernel key version from max_rollback_versions in the past. At that
1669 // point the max kernel key version will be set to that value, creating a
1670 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001671 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001672 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001673 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001674 } else {
1675 // For devices that are not rollback enabled (ie. consumer devices), the
1676 // max kernel key version is set to 0xfffffffe, which is logically
1677 // infinity. This maintains the previous behavior that that kernel key
1678 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001679 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001680 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001681 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001682 }
1683
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001684 bool max_rollforward_set =
1685 system_state_->hardware()->SetMaxKernelKeyRollforward(
1686 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001687 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001688 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001689 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001690 // Report metrics
1691 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1692 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001693}
1694
May Lippert60aa3ca2018-08-15 16:55:29 -07001695base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1696 Time update_first_seen_at;
1697 int64_t update_first_seen_at_int;
1698 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1699 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1700 &update_first_seen_at_int)) {
1701 // Note: This timestamp could be that of ANY update we saw in the past
1702 // (not necessarily this particular update we're considering to apply)
1703 // but never got to apply because of some reason (e.g. stop AU policy,
1704 // updates being pulled out from Omaha, changes in target version prefix,
1705 // new update being rolled out, etc.). But for the purposes of scattering
1706 // it doesn't matter which update the timestamp corresponds to. i.e.
1707 // the clock starts ticking the first time we see an update and we're
1708 // ready to apply when the random wait period is satisfied relative to
1709 // that first seen timestamp.
1710 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1711 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1712 << utils::ToString(update_first_seen_at);
1713 } else {
1714 // This seems like an unexpected error where the persisted value exists
1715 // but it's not readable for some reason.
1716 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1717 return base::Time();
1718 }
1719 } else {
1720 update_first_seen_at = system_state_->clock()->GetWallclockTime();
1721 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
1722 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1723 update_first_seen_at_int)) {
1724 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1725 << utils::ToString(update_first_seen_at);
1726 } else {
1727 // This seems like an unexpected error where the value cannot be
1728 // persisted for some reason.
1729 LOG(INFO) << "UpdateFirstSeenAt value "
1730 << utils::ToString(update_first_seen_at)
1731 << " cannot be persisted";
1732 return base::Time();
1733 }
1734 }
1735 return update_first_seen_at;
1736}
1737
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001738} // namespace chromeos_update_engine