blob: c9b8aa04edf361b6aec6c932b68dfd3f6edb9b27 [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"
rspangler@google.com49fdf182009-10-10 00:57:34 +000058
Jae Hoon Kimebea3392020-04-27 13:27:35 -070059using base::Optional;
Darin Petkov1cbd78f2010-07-29 12:38:34 -070060using base::Time;
61using base::TimeDelta;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080062using chromeos_update_manager::kRollforwardInfinity;
David Zeuthene8ed8632014-07-24 13:38:10 -040063using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000064using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040065using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000066
67namespace chromeos_update_engine {
68
Amin Hassani6600a562018-09-24 15:17:19 -070069// List of custom attributes that we interpret in the Omaha response:
70constexpr char kAttrDeadline[] = "deadline";
71constexpr char kAttrDisableP2PForDownloading[] = "DisableP2PForDownloading";
72constexpr char kAttrDisableP2PForSharing[] = "DisableP2PForSharing";
73constexpr char kAttrDisablePayloadBackoff[] = "DisablePayloadBackoff";
74constexpr char kAttrVersion[] = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080075// Deprecated: "IsDelta"
Amin Hassani6600a562018-09-24 15:17:19 -070076constexpr char kAttrIsDeltaPayload[] = "IsDeltaPayload";
77constexpr char kAttrMaxFailureCountPerUrl[] = "MaxFailureCountPerUrl";
78constexpr char kAttrMaxDaysToScatter[] = "MaxDaysToScatter";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080079// Deprecated: "ManifestSignatureRsa"
80// Deprecated: "ManifestSize"
Amin Hassani6600a562018-09-24 15:17:19 -070081constexpr char kAttrMetadataSignatureRsa[] = "MetadataSignatureRsa";
82constexpr char kAttrMetadataSize[] = "MetadataSize";
83constexpr char kAttrMoreInfo[] = "MoreInfo";
84constexpr char kAttrNoUpdate[] = "noupdate";
Don Garrett42bd3aa2013-04-10 18:14:56 -070085// Deprecated: "NeedsAdmin"
Amin Hassani6600a562018-09-24 15:17:19 -070086constexpr char kAttrPollInterval[] = "PollInterval";
87constexpr char kAttrPowerwash[] = "Powerwash";
88constexpr char kAttrPrompt[] = "Prompt";
89constexpr char kAttrPublicKeyRsa[] = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080090
Amin Hassani6600a562018-09-24 15:17:19 -070091// List of attributes that we interpret in the Omaha response:
92constexpr char kAttrAppId[] = "appid";
93constexpr char kAttrCodeBase[] = "codebase";
94constexpr char kAttrCohort[] = "cohort";
95constexpr char kAttrCohortHint[] = "cohorthint";
96constexpr char kAttrCohortName[] = "cohortname";
97constexpr char kAttrElapsedDays[] = "elapsed_days";
98constexpr char kAttrElapsedSeconds[] = "elapsed_seconds";
99constexpr char kAttrEvent[] = "event";
100constexpr char kAttrHashSha256[] = "hash_sha256";
101// Deprecated: "hash"; Although we still need to pass it from the server for
102// backward compatibility.
103constexpr char kAttrName[] = "name";
104// Deprecated: "sha256"; Although we still need to pass it from the server for
105// backward compatibility.
106constexpr char kAttrSize[] = "size";
107constexpr char kAttrStatus[] = "status";
108
109// List of values that we interpret in the Omaha response:
110constexpr char kValPostInstall[] = "postinstall";
111constexpr char kValNoUpdate[] = "noupdate";
112
Alex Deymob3fa53b2016-04-18 19:57:58 -0700113// updatecheck attributes (without the underscore prefix).
Amin Hassani2cbb0692019-10-30 13:36:17 -0700114// Deprecated: "eol"
Jae Hoon Kim051627a2019-09-03 12:56:32 -0700115constexpr char kAttrEolDate[] = "eol_date";
Amin Hassani6600a562018-09-24 15:17:19 -0700116constexpr char kAttrRollback[] = "rollback";
117constexpr char kAttrFirmwareVersion[] = "firmware_version";
118constexpr char kAttrKernelVersion[] = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -0700119
David Zeuthene8ed8632014-07-24 13:38:10 -0400120// Struct used for holding data obtained when parsing the XML.
121struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400122 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
123
124 // Pointer to the expat XML_Parser object.
125 XML_Parser xml_parser;
126
David Zeuthene8ed8632014-07-24 13:38:10 -0400127 // This is the state of the parser as it's processing the XML.
128 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400129 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400130 string current_path;
131
132 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400133 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700134 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400135 string daystart_elapsed_days;
136 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800137
Sen Jiang81259682017-03-30 15:11:30 -0700138 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700139 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700140 vector<string> url_codebase;
141 string manifest_version;
142 map<string, string> action_postinstall_attrs;
143 string updatecheck_status;
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700144 Optional<string> cohort;
145 Optional<string> cohorthint;
146 Optional<string> cohortname;
Sen Jiang81259682017-03-30 15:11:30 -0700147
148 struct Package {
149 string name;
150 string size;
151 string hash;
152 };
153 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800154 };
Sen Jiang81259682017-03-30 15:11:30 -0700155 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400156};
157
158namespace {
159
160// Callback function invoked by expat.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800161void ParserHandlerStart(void* user_data,
162 const XML_Char* element,
David Zeuthene8ed8632014-07-24 13:38:10 -0400163 const XML_Char** attr) {
164 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
165
166 if (data->failed)
167 return;
168
169 data->current_path += string("/") + element;
170
171 map<string, string> attrs;
172 if (attr != nullptr) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800173 for (int n = 0; attr[n] != nullptr && attr[n + 1] != nullptr; n += 2) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400174 string key = attr[n];
175 string value = attr[n + 1];
176 attrs[key] = value;
177 }
178 }
179
Alex Deymo8e18f932015-03-27 16:16:59 -0700180 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700181 OmahaParserData::App app;
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700182 if (attrs.find(kAttrAppId) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700183 app.id = attrs[kAttrAppId];
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700184 if (attrs.find(kAttrCohort) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700185 app.cohort = attrs[kAttrCohort];
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700186 if (attrs.find(kAttrCohortHint) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700187 app.cohorthint = attrs[kAttrCohortHint];
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700188 if (attrs.find(kAttrCohortName) != attrs.end())
Amin Hassani6600a562018-09-24 15:17:19 -0700189 app.cohortname = attrs[kAttrCohortName];
Sen Jiangb1e063a2017-09-15 17:44:31 -0700190 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700191 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700192 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700193 data->apps.back().updatecheck_status = attrs[kAttrStatus];
Sen Jiang81259682017-03-30 15:11:30 -0700194 if (data->updatecheck_poll_interval.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700195 data->updatecheck_poll_interval = attrs[kAttrPollInterval];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700196 // Omaha sends arbitrary key-value pairs as extra attributes starting with
197 // an underscore.
198 for (const auto& attr : attrs) {
199 if (!attr.first.empty() && attr.first[0] == '_')
200 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
201 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400202 } else if (data->current_path == "/response/daystart") {
203 // Get the install-date.
Amin Hassani6600a562018-09-24 15:17:19 -0700204 data->daystart_elapsed_days = attrs[kAttrElapsedDays];
205 data->daystart_elapsed_seconds = attrs[kAttrElapsedSeconds];
David Zeuthene8ed8632014-07-24 13:38:10 -0400206 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
207 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700208 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700209 data->apps.back().url_codebase.push_back(attrs[kAttrCodeBase]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800210 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400211 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800212 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700213 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700214 data->apps.back().packages.push_back({.name = attrs[kAttrName],
215 .size = attrs[kAttrSize],
216 .hash = attrs[kAttrHashSha256]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400217 } else if (data->current_path == "/response/app/updatecheck/manifest") {
218 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700219 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700220 data->apps.back().manifest_version = attrs[kAttrVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400221 } else if (data->current_path ==
222 "/response/app/updatecheck/manifest/actions/action") {
223 // We only care about the postinstall action.
Amin Hassani6600a562018-09-24 15:17:19 -0700224 if (attrs[kAttrEvent] == kValPostInstall && !data->apps.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700225 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400226 }
227 }
228}
229
230// Callback function invoked by expat.
231void ParserHandlerEnd(void* user_data, const XML_Char* element) {
232 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
233 if (data->failed)
234 return;
235
236 const string path_suffix = string("/") + element;
237
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800238 if (!base::EndsWith(
239 data->current_path, path_suffix, base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400240 LOG(ERROR) << "Unexpected end element '" << element
241 << "' with current_path='" << data->current_path << "'";
242 data->failed = true;
243 return;
244 }
245 data->current_path.resize(data->current_path.size() - path_suffix.size());
246}
247
David Zeuthenf3e28012014-08-26 18:23:52 -0400248// Callback function invoked by expat.
249//
250// This is called for entity declarations. Since Omaha is guaranteed
251// to never return any XML with entities our course of action is to
252// just stop parsing. This avoids potential resource exhaustion
253// problems AKA the "billion laughs". CVE-2013-0340.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800254void ParserHandlerEntityDecl(void* user_data,
255 const XML_Char* entity_name,
David Zeuthenf3e28012014-08-26 18:23:52 -0400256 int is_parameter_entity,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800257 const XML_Char* value,
David Zeuthenf3e28012014-08-26 18:23:52 -0400258 int value_length,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800259 const XML_Char* base,
260 const XML_Char* system_id,
261 const XML_Char* public_id,
262 const XML_Char* notation_name) {
David Zeuthenf3e28012014-08-26 18:23:52 -0400263 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
264
265 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
266 data->failed = true;
267 data->entity_decl = true;
268 XML_StopParser(data->xml_parser, false);
269}
270
David Zeuthene8ed8632014-07-24 13:38:10 -0400271} // namespace
272
Alex Deymoc1c17b42015-11-23 03:53:15 -0300273OmahaRequestAction::OmahaRequestAction(
274 SystemState* system_state,
275 OmahaEvent* event,
276 std::unique_ptr<HttpFetcher> http_fetcher,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700277 bool ping_only,
278 const string& session_id)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800279 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800280 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700281 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300282 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800283 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700284 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700285 ping_active_days_(0),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700286 ping_roll_call_days_(0),
287 session_id_(session_id) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800288 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700289}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000290
Darin Petkov6a5b3222010-07-13 14:55:28 -0700291OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000292
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700293// Calculates the value to use for the ping days parameter.
294int OmahaRequestAction::CalculatePingDays(const string& key) {
Andrewe045aef2020-01-08 16:29:22 -0800295 int days = kPingNeverPinged;
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700296 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800297 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700298 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
299 if (days < 0) {
300 // If |days| is negative, then the system clock must have jumped
301 // back in time since the ping was sent. Mark the value so that
302 // it doesn't get sent to the server but we still update the
303 // last ping daystart preference. This way the next ping time
304 // will be correct, hopefully.
305 days = kPingTimeJump;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800306 LOG(WARNING)
307 << "System clock jumped back in time. Resetting ping daystarts.";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700308 }
309 }
310 return days;
311}
312
313void OmahaRequestAction::InitPingDays() {
314 // We send pings only along with update checks, not with events.
315 if (IsEvent()) {
316 return;
317 }
318 // TODO(petkov): Figure a way to distinguish active use pings
319 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700320 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700321 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
322 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
323}
324
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700325bool OmahaRequestAction::ShouldPing() const {
Andrewe045aef2020-01-08 16:29:22 -0800326 if (ping_active_days_ == kPingNeverPinged &&
327 ping_roll_call_days_ == kPingNeverPinged) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700328 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
329 if (powerwash_count > 0) {
330 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
331 << "powerwash_count is " << powerwash_count;
332 return false;
333 }
Amin Hassani1677e812017-06-21 13:36:36 -0700334 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
335 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
336 << "the first_active_omaha_ping_sent is true";
337 return false;
338 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700339 return true;
340 }
341 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
342}
343
David Zeuthen639aa362014-02-03 16:23:44 -0800344// static
345int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
346 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700347 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800348 return -1;
349
350 // If we have the value stored on disk, just return it.
351 int64_t stored_value;
352 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
353 // Convert and sanity-check.
354 int install_date_days = static_cast<int>(stored_value);
355 if (install_date_days >= 0)
356 return install_date_days;
357 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
358 << install_date_days << " looks suspicious.";
359 prefs->Delete(kPrefsInstallDateDays);
360 }
361
362 // Otherwise, if OOBE is not complete then do nothing and wait for
363 // ParseResponse() to call ParseInstallDate() and then
364 // PersistInstallDate() to set the kPrefsInstallDateDays state
365 // variable. Once that is done, we'll then report back in future
366 // Omaha requests. This works exactly because OOBE triggers an
367 // update check.
368 //
369 // However, if OOBE is complete and the kPrefsInstallDateDays state
370 // variable is not set, there are two possibilities
371 //
372 // 1. The update check in OOBE failed so we never got a response
373 // from Omaha (no network etc.); or
374 //
375 // 2. OOBE was done on an older version that didn't write to the
376 // kPrefsInstallDateDays state variable.
377 //
378 // In both cases, we approximate the install date by simply
379 // inspecting the timestamp of when OOBE happened.
380
381 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700382 if (!system_state->hardware()->IsOOBEEnabled() ||
383 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800384 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700385 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800386 return -1;
387 }
388
389 int num_days;
390 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
391 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
392 << "as its value '" << utils::ToString(time_of_oobe)
393 << "' looks suspicious.";
394 return -1;
395 }
396
397 // Persist this to disk, for future use.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800398 if (!OmahaRequestAction::PersistInstallDate(
399 system_state, num_days, kProvisionedFromOOBEMarker))
David Zeuthen639aa362014-02-03 16:23:44 -0800400 return -1;
401
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800402 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to " << num_days
403 << " days";
David Zeuthen639aa362014-02-03 16:23:44 -0800404
405 return num_days;
406}
407
Andrewe045aef2020-01-08 16:29:22 -0800408void OmahaRequestAction::StorePingReply(
409 const OmahaParserData& parser_data) const {
410 for (const auto& app : parser_data.apps) {
411 auto it = params_->dlc_apps_params().find(app.id);
412 if (it == params_->dlc_apps_params().end())
413 continue;
414
415 const OmahaRequestParams::AppParams& dlc_params = it->second;
Andrew065d78d2020-04-07 15:43:07 -0700416 const string& dlc_id = dlc_params.name;
Andrewe045aef2020-01-08 16:29:22 -0800417 // Skip if the ping for this DLC was not sent.
418 if (!dlc_params.send_ping)
419 continue;
420
Andrew065d78d2020-04-07 15:43:07 -0700421 PrefsInterface* prefs = system_state_->prefs();
Andrewe045aef2020-01-08 16:29:22 -0800422 // Reset the active metadata value to |kPingInactiveValue|.
Andrew065d78d2020-04-07 15:43:07 -0700423 auto active_key =
424 prefs->CreateSubKey(kDlcPrefsSubDir, dlc_id, kPrefsPingActive);
425 if (!prefs->SetInt64(active_key, kPingInactiveValue))
426 LOG(ERROR) << "Failed to set the value of ping metadata '" << active_key
427 << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800428
Andrew065d78d2020-04-07 15:43:07 -0700429 auto last_rollcall_key =
430 prefs->CreateSubKey(kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall);
431 if (!prefs->SetString(last_rollcall_key, parser_data.daystart_elapsed_days))
Andrewe045aef2020-01-08 16:29:22 -0800432 LOG(ERROR) << "Failed to set the value of ping metadata '"
Andrew065d78d2020-04-07 15:43:07 -0700433 << last_rollcall_key << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800434
435 if (dlc_params.ping_active) {
436 // Write the value of elapsed_days into |kPrefsPingLastActive| only if
437 // the previous ping was an active one.
Andrew065d78d2020-04-07 15:43:07 -0700438 auto last_active_key =
439 prefs->CreateSubKey(kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive);
440 if (!prefs->SetString(last_active_key, parser_data.daystart_elapsed_days))
Andrewe045aef2020-01-08 16:29:22 -0800441 LOG(ERROR) << "Failed to set the value of ping metadata '"
Andrew065d78d2020-04-07 15:43:07 -0700442 << last_active_key << "'.";
Andrewe045aef2020-01-08 16:29:22 -0800443 }
444 }
445}
446
Darin Petkov6a5b3222010-07-13 14:55:28 -0700447void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000448 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700449 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700450 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700451 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700452 return;
453 }
David Zeuthen639aa362014-02-03 16:23:44 -0800454
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700455 OmahaRequestBuilderXml omaha_request(event_.get(),
456 params_,
457 ping_only_,
458 ShouldPing(), // include_ping
459 ping_active_days_,
460 ping_roll_call_days_,
461 GetInstallDate(system_state_),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700462 system_state_->prefs(),
463 session_id_);
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700464 string request_post = omaha_request.GetRequest();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700465
Sen Jiang42fa45e2018-03-12 11:02:14 -0700466 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700467 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
468 params_->interactive() ? "fg" : "bg");
469 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
470 http_fetcher_->SetHeader(
471 kXGoogleUpdateUpdater,
472 base::StringPrintf(
473 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
474
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800475 http_fetcher_->SetPostData(
476 request_post.data(), request_post.size(), kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700477 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700478 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700479 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000480}
481
Darin Petkov6a5b3222010-07-13 14:55:28 -0700482void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000483 http_fetcher_->TerminateTransfer();
484}
485
486// We just store the response in the buffer. Once we've received all bytes,
487// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700488bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800489 const void* bytes,
490 size_t length) {
491 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
492 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700493 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000494}
495
496namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000497
498// Parses a 64 bit base-10 int from a string and returns it. Returns 0
499// on error. If the string contains "0", that's indistinguishable from
500// error.
501off_t ParseInt(const string& str) {
502 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700503 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000504 if (rc < 1) {
505 // failure
506 return 0;
507 }
508 return ret;
509}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700510
David Zeuthene8ed8632014-07-24 13:38:10 -0400511// Parses |str| and returns |true| if, and only if, its value is "true".
512bool ParseBool(const string& str) {
513 return str == "true";
514}
515
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700516// Update the last ping day preferences based on the server daystart
517// response. Returns true on success, false otherwise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800518bool UpdateLastPingDays(OmahaParserData* parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700519 int64_t elapsed_seconds = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800520 TEST_AND_RETURN_FALSE(base::StringToInt64(
521 parser_data->daystart_elapsed_seconds, &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700522 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
523
524 // Remember the local time that matches the server's last midnight
525 // time.
526 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
527 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
528 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
529 return true;
530}
Sen Jiang81259682017-03-30 15:11:30 -0700531
532// Parses the package node in the given XML document and populates
533// |output_object| if valid. Returns true if we should continue the parsing.
534// False otherwise, in which case it sets any error code using |completer|.
535bool ParsePackage(OmahaParserData::App* app,
536 OmahaResponse* output_object,
537 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700538 if (app->updatecheck_status.empty() ||
539 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700540 if (!app->packages.empty()) {
541 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
542 completer->set_code(ErrorCode::kOmahaResponseInvalid);
543 return false;
544 }
545 return true;
546 }
547 if (app->packages.empty()) {
548 LOG(ERROR) << "Omaha Response has no packages";
549 completer->set_code(ErrorCode::kOmahaResponseInvalid);
550 return false;
551 }
552 if (app->url_codebase.empty()) {
553 LOG(ERROR) << "No Omaha Response URLs";
554 completer->set_code(ErrorCode::kOmahaResponseInvalid);
555 return false;
556 }
557 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
558 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700559 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700560 ":",
561 base::TRIM_WHITESPACE,
562 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700563 vector<string> metadata_signatures = base::SplitString(
564 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
565 ":",
566 base::TRIM_WHITESPACE,
567 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700568 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700569 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700570 ":",
571 base::TRIM_WHITESPACE,
572 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700573 for (size_t i = 0; i < app->packages.size(); i++) {
574 const auto& package = app->packages[i];
575 if (package.name.empty()) {
576 LOG(ERROR) << "Omaha Response has empty package name";
577 completer->set_code(ErrorCode::kOmahaResponseInvalid);
578 return false;
579 }
580 LOG(INFO) << "Found package " << package.name;
581
582 OmahaResponse::Package out_package;
583 for (const string& codebase : app->url_codebase) {
584 if (codebase.empty()) {
585 LOG(ERROR) << "Omaha Response URL has empty codebase";
586 completer->set_code(ErrorCode::kOmahaResponseInvalid);
587 return false;
588 }
589 out_package.payload_urls.push_back(codebase + package.name);
590 }
591 // Parse the payload size.
592 base::StringToUint64(package.size, &out_package.size);
593 if (out_package.size <= 0) {
594 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
595 completer->set_code(ErrorCode::kOmahaResponseInvalid);
596 return false;
597 }
598 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
599
600 if (i < metadata_sizes.size())
601 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
602 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
603 << " bytes";
604
605 if (i < metadata_signatures.size())
606 out_package.metadata_signature = metadata_signatures[i];
607 LOG(INFO) << "Payload metadata signature = "
608 << out_package.metadata_signature;
609
610 out_package.hash = package.hash;
611 if (out_package.hash.empty()) {
612 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
613 completer->set_code(ErrorCode::kOmahaResponseInvalid);
614 return false;
615 }
616 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700617
618 if (i < is_delta_payloads.size())
619 out_package.is_delta = ParseBool(is_delta_payloads[i]);
620 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
621
Sen Jiang81259682017-03-30 15:11:30 -0700622 output_object->packages.push_back(std::move(out_package));
623 }
624
625 return true;
626}
627
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700628// Parses the 2 key version strings kernel_version and firmware_version. If the
629// field is not present, or cannot be parsed the values default to 0xffff.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700630void ParseRollbackVersions(int allowed_milestones,
631 OmahaParserData* parser_data,
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700632 OmahaResponse* output_object) {
633 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700634 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700635 &output_object->rollback_key_version.firmware_key,
636 &output_object->rollback_key_version.firmware);
637 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700638 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700639 &output_object->rollback_key_version.kernel_key,
640 &output_object->rollback_key_version.kernel);
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700641
642 // Create the attribute name strings for milestone N - allowed_milestones.
643 const string firmware_max_rollforward_attr =
644 base::StringPrintf("%s_%i", kAttrFirmwareVersion, allowed_milestones);
645 const string kernel_max_rollforward_attr =
646 base::StringPrintf("%s_%i", kAttrKernelVersion, allowed_milestones);
647
648 const bool max_firmware_and_kernel_exist =
649 parser_data->updatecheck_attrs.count(firmware_max_rollforward_attr) > 0 &&
650 parser_data->updatecheck_attrs.count(kernel_max_rollforward_attr) > 0;
651
652 string firmware_version;
653 string kernel_version;
654 if (max_firmware_and_kernel_exist) {
655 firmware_version =
656 parser_data->updatecheck_attrs[firmware_max_rollforward_attr];
657 kernel_version =
658 parser_data->updatecheck_attrs[kernel_max_rollforward_attr];
659 }
660
661 LOG(INFO) << "For milestone N-" << allowed_milestones
662 << " firmware_key_version=" << firmware_version
663 << " kernel_key_version=" << kernel_version;
664
665 OmahaResponse::RollbackKeyVersion version;
666 utils::ParseRollbackKeyVersion(
667 firmware_version, &version.firmware_key, &version.firmware);
668 utils::ParseRollbackKeyVersion(
669 kernel_version, &version.kernel_key, &version.kernel);
670
671 output_object->past_rollback_key_version = std::move(version);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700672}
673
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700674} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000675
David Zeuthene8ed8632014-07-24 13:38:10 -0400676bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700677 OmahaResponse* output_object,
678 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700679 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700680 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700681 return false;
682 }
Sen Jiang81259682017-03-30 15:11:30 -0700683 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700684
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800685 // chromium-os:37289: The PollInterval is not supported by Omaha server
686 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700687 // slow down the request rate from the server-side. Note that the PollInterval
688 // is not persisted, so it has to be sent by the server on every response to
689 // guarantee that the scheduler uses this value (otherwise, if the device got
690 // rebooted after the last server-indicated value, it'll revert to the default
691 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
692 // based on the assumption that we perform an update check every hour so that
693 // the max value of 8 will roughly be equivalent to one work day. If we decide
694 // to use PollInterval permanently, we should update the
695 // max_update_checks_allowed to take PollInterval into account. Note: The
696 // parsing for PollInterval happens even before parsing of the status because
697 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400698 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700699 &output_object->poll_interval);
700
David Zeuthen639aa362014-02-03 16:23:44 -0800701 // Check for the "elapsed_days" attribute in the "daystart"
702 // element. This is the number of days since Jan 1 2007, 0:00
703 // PST. If we don't have a persisted value of the Omaha InstallDate,
704 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400705 if (ParseInstallDate(parser_data, output_object) &&
706 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800707 // Since output_object->install_date_days is never negative, the
708 // elapsed_days -> install-date calculation is reduced to simply
709 // rounding down to the nearest number divisible by 7.
710 int remainder = output_object->install_date_days % 7;
711 int install_date_days_rounded =
712 output_object->install_date_days - remainder;
713 if (PersistInstallDate(system_state_,
714 install_date_days_rounded,
715 kProvisionedFromOmahaResponse)) {
716 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
717 << install_date_days_rounded << " days";
718 }
719 }
720
Alex Deymo00d79ac2015-06-29 15:41:49 -0700721 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700722 for (const auto& app : parser_data->apps) {
723 if (app.id == params_->GetAppId()) {
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700724 if (app.cohort)
725 PersistCohortData(kPrefsOmahaCohort, app.cohort.value());
726 if (app.cohorthint)
727 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint.value());
728 if (app.cohortname)
729 PersistCohortData(kPrefsOmahaCohortName, app.cohortname.value());
Sen Jiangb1e063a2017-09-15 17:44:31 -0700730 break;
731 }
732 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700733
Amin Hassani2cbb0692019-10-30 13:36:17 -0700734 PersistEolInfo(parser_data->updatecheck_attrs);
735
Marton Hunyady199152d2018-05-07 19:08:48 +0200736 // Rollback-related updatecheck attributes.
737 // Defaults to false if attribute is not present.
738 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -0700739 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700740
741 // Parses the rollback versions of the current image. If the fields do not
742 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700743 ParseRollbackVersions(
744 params_->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -0700745
David Zeuthene8ed8632014-07-24 13:38:10 -0400746 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700747 return false;
748
David Zeuthene8ed8632014-07-24 13:38:10 -0400749 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700750 return false;
751
Sen Jiang0affc2c2017-02-10 15:55:05 -0800752 // Package has to be parsed after Params now because ParseParams need to make
753 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -0700754 for (auto& app : parser_data->apps)
755 if (!ParsePackage(&app, output_object, completer))
756 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800757
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700758 return true;
759}
760
David Zeuthene8ed8632014-07-24 13:38:10 -0400761bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700762 OmahaResponse* output_object,
763 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700764 output_object->update_exists = false;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700765 for (const auto& app : parser_data->apps) {
766 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -0700767 if (status == kValNoUpdate) {
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800768 // If the app is a DLC, allow status "noupdate" to support DLC
769 // deprecations.
770 if (params_->IsDlcAppId(app.id)) {
771 LOG(INFO) << "No update for <app> " << app.id
772 << " but update continuing since a DLC.";
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700773 params_->SetDlcNoUpdate(app.id);
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800774 continue;
775 }
Sen Jiang00adf7b2017-06-26 15:57:29 -0700776 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -0700777 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700778 output_object->update_exists = false;
779 break;
Sen Jiang81259682017-03-30 15:11:30 -0700780 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700781 auto const& attr_no_update =
782 app.action_postinstall_attrs.find(kAttrNoUpdate);
783 if (attr_no_update != app.action_postinstall_attrs.end() &&
784 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700785 // noupdate="true" in postinstall attributes means it's an update to
786 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -0700787 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700788 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700789 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700790 output_object->update_exists = true;
791 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700792 } else if (status.empty() && params_->is_install() &&
793 params_->GetAppId() == app.id) {
794 // Skips the platform app for install operation.
795 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -0700796 } else {
797 LOG(ERROR) << "Unknown Omaha response status: " << status;
798 completer->set_code(ErrorCode::kOmahaResponseInvalid);
799 return false;
800 }
801 }
802 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700803 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700804 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700805 }
806
Sen Jiang81259682017-03-30 15:11:30 -0700807 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700808}
809
David Zeuthene8ed8632014-07-24 13:38:10 -0400810bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700811 OmahaResponse* output_object,
812 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700813 map<string, string> attrs;
814 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700815 if (app.id == params_->GetAppId()) {
816 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -0700817 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700818 } else if (!params_->system_app_id().empty() &&
819 app.id == params_->system_app_id()) {
820 // this is the system app (this check is intentionally skipped if there is
821 // no system_app_id set)
822 output_object->system_version = app.manifest_version;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700823 } else if (params_->is_install() &&
824 app.manifest_version != params_->app_version()) {
825 LOG(WARNING) << "An app has a different version (" << app.manifest_version
826 << ") that is different than platform app version ("
827 << params_->app_version() << ")";
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700828 }
829 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700830 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700831 }
Sen Jiang81259682017-03-30 15:11:30 -0700832 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700833 if (params_->is_install()) {
834 LOG(INFO) << "Use request version for Install operation.";
835 output_object->version = params_->app_version();
836 }
Chris Sosa3b748432013-06-20 16:42:59 -0700837 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700838 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700839 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700840 return false;
841 }
842
843 LOG(INFO) << "Received omaha response to update to version "
844 << output_object->version;
845
David Zeuthene8ed8632014-07-24 13:38:10 -0400846 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700847 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700848 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700849 return false;
850 }
851
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800852 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -0700853 output_object->more_info_url = attrs[kAttrMoreInfo];
854 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
855 output_object->deadline = attrs[kAttrDeadline];
856 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700857 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -0700858 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700859 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -0700860 ParseBool(attrs[kAttrDisableP2PForSharing]);
861 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800862
Amin Hassani6600a562018-09-24 15:17:19 -0700863 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800864 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800865 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700866
Jay Srinivasan08262882012-12-28 19:29:43 -0800867 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -0700868 ParseBool(attrs[kAttrDisablePayloadBackoff]);
869 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800870
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700871 return true;
872}
873
David Zeuthene8ed8632014-07-24 13:38:10 -0400874// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000875// and fill in the appropriate fields of the output object. Also, notifies
876// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800877void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -0700878 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000879 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800880 string current_response(response_buffer_.begin(), response_buffer_.end());
881 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700882
Gilad Arnold74b5f552014-10-07 08:17:16 -0700883 PayloadStateInterface* const payload_state = system_state_->payload_state();
884
Zentaro Kavanagh76af2662018-05-15 10:54:53 -0700885 // Set the max kernel key version based on whether rollback is allowed.
886 SetMaxKernelKeyVersionForRollback();
887
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700888 // Events are best effort transactions -- assume they always succeed.
889 if (IsEvent()) {
890 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700891 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700892 return;
893 }
894
Amin Hassanid3d84212019-08-17 00:27:44 -0700895 ErrorCode aux_error_code = fetcher->GetAuxiliaryErrorCode();
896 if (aux_error_code != ErrorCode::kSuccess) {
897 metrics::DownloadErrorCode download_error_code =
898 metrics_utils::GetDownloadErrorCode(aux_error_code);
899 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
900 system_state_,
901 metrics::CheckResult::kUnset,
902 metrics::CheckReaction::kUnset,
903 download_error_code);
904 }
905
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700906 if (!successful) {
Darin Petkovedc522e2010-11-05 09:35:17 -0700907 int code = GetHTTPResponseCode();
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700908 LOG(ERROR) << "Omaha request network transfer failed with HTTPResponseCode="
909 << code;
Darin Petkovedc522e2010-11-05 09:35:17 -0700910 // Makes sure we send sane error values.
911 if (code < 0 || code >= 1000) {
912 code = 999;
Jae Hoon Kimebea3392020-04-27 13:27:35 -0700913 LOG(WARNING) << "Converting to sane HTTPResponseCode=" << code;
Darin Petkovedc522e2010-11-05 09:35:17 -0700914 }
David Zeuthena99981f2013-04-29 13:42:47 -0700915 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700916 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000917 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700918 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000919
David Zeuthene8ed8632014-07-24 13:38:10 -0400920 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400921 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400922 XML_SetUserData(parser, &parser_data);
923 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400924 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800925 XML_Status res =
926 XML_Parse(parser,
927 reinterpret_cast<const char*>(response_buffer_.data()),
928 response_buffer_.size(),
929 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400930
931 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700932 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800933 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
934 << XML_GetCurrentLineNumber(parser) << " col "
935 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -0700936 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400937 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
938 if (response_buffer_.empty()) {
939 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
940 } else if (parser_data.entity_decl) {
941 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
942 }
943 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000944 return;
945 }
Amin Hassani91f48b42018-08-06 17:47:14 -0700946 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000947
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700948 // Update the last ping day preferences based on the server daystart response
949 // even if we didn't send a ping. Omaha always includes the daystart in the
950 // response, but log the error if it didn't.
951 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
952 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700953
Amin Hassani1677e812017-06-21 13:36:36 -0700954 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
955 // we have got a response from omaha and if its value has never been set to
956 // true before. Failure of this function should be ignored. There should be no
957 // need to check if a=-1 has been sent because older devices have already sent
958 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
959 // future checks.
960 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700961 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
962 system_state_->metrics_reporter()->ReportInternalErrorCode(
963 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
964 }
Amin Hassani1677e812017-06-21 13:36:36 -0700965 }
966
Andrewe045aef2020-01-08 16:29:22 -0800967 // Create/update the metadata files for each DLC app received.
968 StorePingReply(parser_data);
969
Thieu Le116fda32011-04-19 11:01:54 -0700970 if (!HasOutputPipe()) {
971 // Just set success to whether or not the http transfer succeeded,
972 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700973 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700974 return;
975 }
976
Darin Petkov6a5b3222010-07-13 14:55:28 -0700977 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400978 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000979 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700980 output_object.update_exists = true;
981 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000982
Toni Barzic61544e62018-10-11 14:37:30 -0700983 LoadOrPersistUpdateFirstSeenAtPref();
984
Weidong Guo421ff332017-04-17 10:08:38 -0700985 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -0700986 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -0700987 // No need to change output_object.update_exists here, since the value
988 // has been output to the pipe.
989 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700990 return;
991 }
992
David Zeuthen8f191b22013-08-06 12:27:50 -0700993 // If Omaha says to disable p2p, respect that
994 if (output_object.disable_p2p_for_downloading) {
995 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
996 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700997 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700998 }
999 if (output_object.disable_p2p_for_sharing) {
1000 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1001 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001002 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001003 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001004
1005 // Update the payload state with the current response. The payload state
1006 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001007 // from what's stored already. We are updating the payload state as late
1008 // as possible in this method so that if a new release gets pushed and then
1009 // got pulled back due to some issues, we don't want to clear our internal
1010 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001011 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001012
David Zeuthen8f191b22013-08-06 12:27:50 -07001013 // It could be we've already exceeded the deadline for when p2p is
1014 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001015 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001016 payload_state->P2PNewAttempt();
1017 if (!payload_state->P2PAttemptAllowed()) {
1018 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1019 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001020 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001021 }
1022 }
1023
1024 // From here on, we'll complete stuff in CompleteProcessing() so
1025 // disable |completer| since we'll create a new one in that
1026 // function.
1027 completer.set_should_complete(false);
1028
1029 // If we're allowed to use p2p for downloading we do not pay
1030 // attention to wall-clock-based waiting if the URL is indeed
1031 // available via p2p. Therefore, check if the file is available via
1032 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001033 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001034 LookupPayloadViaP2P(output_object);
1035 } else {
1036 CompleteProcessing();
1037 }
1038}
1039
1040void OmahaRequestAction::CompleteProcessing() {
1041 ScopedActionCompleter completer(processor_, this);
1042 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1043 PayloadStateInterface* payload_state = system_state_->payload_state();
1044
1045 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001046 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001047 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001048 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001049 return;
1050 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001051
Chris Sosa20f005c2013-09-05 13:53:08 -07001052 if (payload_state->ShouldBackoffDownload()) {
1053 output_object.update_exists = false;
1054 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1055 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001056 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001057 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001058 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001059 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001060}
1061
1062void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1063 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1064 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001065 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001066 } else {
1067 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1068 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001069 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001070 }
1071 CompleteProcessing();
1072}
1073
1074void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001075 // If the device is in the middle of an update, the state variables
1076 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1077 // tracks the offset and length of the operation currently in
1078 // progress. The offset is based from the end of the manifest which
1079 // is kPrefsManifestMetadataSize bytes long.
1080 //
1081 // To make forward progress and avoid deadlocks, we need to find a
1082 // peer that has at least the entire operation we're currently
1083 // working on. Otherwise we may end up in a situation where two
1084 // devices bounce back and forth downloading from each other,
1085 // neither making any forward progress until one of them decides to
1086 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1087 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001088 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001089 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001090 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001091 int64_t next_data_offset = 0;
1092 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001093 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001094 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1095 &manifest_metadata_size) &&
1096 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001097 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1098 &manifest_signature_size) &&
1099 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001100 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001101 &next_data_offset) &&
1102 next_data_offset != -1 &&
1103 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1104 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001105 minimum_size = manifest_metadata_size + manifest_signature_size +
1106 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001107 }
1108
Sen Jiang0affc2c2017-02-10 15:55:05 -08001109 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001110 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001111 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001112 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001113 string file_id =
1114 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001115 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001116 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1117 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001118 system_state_->p2p_manager()->LookupUrlForFile(
1119 file_id,
1120 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001121 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001122 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1123 base::Unretained(this)));
1124 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001125}
1126
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001127bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001128 if (params_->interactive()) {
1129 LOG(INFO) << "Not deferring download because update is interactive.";
1130 return false;
1131 }
1132
David Zeuthen8f191b22013-08-06 12:27:50 -07001133 // If we're using p2p to download _and_ we have a p2p URL, we never
1134 // defer the download. This is because the download will always
1135 // happen from a peer on the LAN and we've been waiting in line for
1136 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001137 const PayloadStateInterface* payload_state = system_state_->payload_state();
1138 if (payload_state->GetUsingP2PForDownloading() &&
1139 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001140 LOG(INFO) << "Download not deferred because download "
1141 << "will happen from a local peer (via p2p).";
1142 return false;
1143 }
1144
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001145 // We should defer the downloads only if we've first satisfied the
1146 // wall-clock-based-waiting period and then the update-check-based waiting
1147 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001148 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001149 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1150 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001151 return false;
1152 }
1153
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001154 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001155 case kWallClockWaitNotSatisfied:
1156 // We haven't even satisfied the first condition, passing the
1157 // wall-clock-based waiting period, so we should defer the downloads
1158 // until that happens.
1159 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1160 return true;
1161
1162 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1163 LOG(INFO) << "wall-clock-based-wait satisfied and "
1164 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001165 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001166
1167 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1168 // Wall-clock-based waiting period is satisfied, and it's determined
1169 // that we do not need the update-check-based wait. so no need to
1170 // defer downloads.
1171 LOG(INFO) << "wall-clock-based-wait satisfied and "
1172 << "update-check-based-wait is not required.";
1173 return false;
1174
1175 default:
1176 // Returning false for this default case so we err on the
1177 // side of downloading updates than deferring in case of any bugs.
1178 NOTREACHED();
1179 return false;
1180 }
1181}
1182
1183OmahaRequestAction::WallClockWaitResult
1184OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001185 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001186 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1187 if (update_first_seen_at == base::Time()) {
1188 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
1189 "persisted";
1190 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001191 }
1192
Sen Jiang7c1171e2016-06-23 11:35:40 -07001193 TimeDelta elapsed_time =
1194 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1195 TimeDelta max_scatter_period =
1196 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001197 int64_t staging_wait_time_in_days = 0;
1198 // Use staging and its default max value if staging is on.
1199 if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1200 &staging_wait_time_in_days) &&
1201 staging_wait_time_in_days > 0)
1202 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001203
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001204 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001205 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001206 << ", Time Elapsed = "
1207 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001208 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001209
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001210 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001211 // The deadline is set for all rules which serve a delta update from a
1212 // previous FSI, which means this update will be applied mostly in OOBE
1213 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1214 // quickly.
1215 LOG(INFO) << "Not scattering as deadline flag is set";
1216 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1217 }
1218
1219 if (max_scatter_period.InDays() == 0) {
1220 // This means the Omaha rule creator decides that this rule
1221 // should not be scattered irrespective of the policy.
1222 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1223 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1224 }
1225
1226 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001227 // This means we've waited more than the upperbound wait in the rule
1228 // from the time we first saw a valid update available to us.
1229 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001230 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1231 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1232 }
1233
1234 // This means we are required to participate in scattering.
1235 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001236 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001237 if (remaining_wait_time.InSeconds() <= 0) {
1238 // Yes, it's our turn now.
1239 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1240
1241 // But we can't download until the update-check-count-based wait is also
1242 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001243 return params_->update_check_count_wait_enabled()
1244 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1245 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001246 }
1247
1248 // Not our turn yet, so we have to wait until our turn to
1249 // help scatter the downloads across all clients of the enterprise.
1250 LOG(INFO) << "Update deferred for another "
1251 << utils::FormatSecs(remaining_wait_time.InSeconds())
1252 << " per policy.";
1253 return kWallClockWaitNotSatisfied;
1254}
1255
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001256bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001257 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001258
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001259 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1260 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1261 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001262 // We are unable to read the update check count from file for some reason.
1263 // So let's proceed anyway so as to not stall the update.
1264 LOG(ERROR) << "Unable to read update check count. "
1265 << "Skipping update-check-count-based-wait.";
1266 return true;
1267 }
1268 } else {
1269 // This file does not exist. This means we haven't started our update
1270 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001271 update_check_count_value =
1272 base::RandInt(params_->min_update_checks_needed(),
1273 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001274
1275 LOG(INFO) << "Randomly picked update check count value = "
1276 << update_check_count_value;
1277
1278 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001279 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1280 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001281 // We weren't able to write the update check count file for some reason.
1282 // So let's proceed anyway so as to not stall the update.
1283 LOG(ERROR) << "Unable to write update check count. "
1284 << "Skipping update-check-count-based-wait.";
1285 return true;
1286 }
1287 }
1288
1289 if (update_check_count_value == 0) {
1290 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1291 return true;
1292 }
1293
1294 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001295 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001296 // We err on the side of skipping scattering logic instead of stalling
1297 // a machine from receiving any updates in case of any unexpected state.
1298 LOG(ERROR) << "Invalid value for update check count detected. "
1299 << "Skipping update-check-count-based-wait.";
1300 return true;
1301 }
1302
1303 // Legal value, we need to wait for more update checks to happen
1304 // until this becomes 0.
1305 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001306 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001307 return false;
1308}
1309
David Zeuthen639aa362014-02-03 16:23:44 -08001310// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001311bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001312 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001313 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001314 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001315 return false;
1316
1317 if (elapsed_days < 0)
1318 return false;
1319
1320 output_object->install_date_days = elapsed_days;
1321 return true;
1322}
1323
1324// static
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001325bool OmahaRequestAction::HasInstallDate(SystemState* system_state) {
David Zeuthen639aa362014-02-03 16:23:44 -08001326 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001327 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001328 return false;
1329
1330 return prefs->Exists(kPrefsInstallDateDays);
1331}
1332
1333// static
1334bool OmahaRequestAction::PersistInstallDate(
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001335 SystemState* system_state,
David Zeuthen639aa362014-02-03 16:23:44 -08001336 int install_date_days,
1337 InstallDateProvisioningSource source) {
1338 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1339
1340 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001341 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001342 return false;
1343
1344 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1345 return false;
1346
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001347 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001348 static_cast<int>(source), // Sample.
1349 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001350 return true;
1351}
1352
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001353bool OmahaRequestAction::PersistCohortData(const string& prefs_key,
1354 const string& new_value) {
Alex Deymo8e18f932015-03-27 16:16:59 -07001355 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1356 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1357 return system_state_->prefs()->Delete(prefs_key);
1358 } else if (!new_value.empty()) {
1359 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1360 return system_state_->prefs()->SetString(prefs_key, new_value);
1361 }
1362 return true;
1363}
1364
Amin Hassani2cbb0692019-10-30 13:36:17 -07001365bool OmahaRequestAction::PersistEolInfo(const map<string, string>& attrs) {
Jae Hoon Kimb3146742019-11-07 13:24:24 -08001366 // If EOL date attribute is not sent, don't delete the old persisted EOL
1367 // date information.
Jae Hoon Kim051627a2019-09-03 12:56:32 -07001368 auto eol_date_attr = attrs.find(kAttrEolDate);
Jae Hoon Kimb3146742019-11-07 13:24:24 -08001369 if (eol_date_attr != attrs.end() &&
1370 !system_state_->prefs()->SetString(kPrefsOmahaEolDate,
1371 eol_date_attr->second)) {
Jae Hoon Kim051627a2019-09-03 12:56:32 -07001372 LOG(ERROR) << "Setting EOL date failed.";
Amin Hassani2cbb0692019-10-30 13:36:17 -07001373 return false;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001374 }
Amin Hassani2cbb0692019-10-30 13:36:17 -07001375 return true;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001376}
1377
David Zeuthen33bae492014-02-25 16:16:18 -08001378void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1379 // We only want to report this on "update check".
1380 if (ping_only_ || event_ != nullptr)
1381 return;
1382
1383 metrics::CheckResult result = metrics::CheckResult::kUnset;
1384 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1385 metrics::DownloadErrorCode download_error_code =
1386 metrics::DownloadErrorCode::kUnset;
1387
1388 // Regular update attempt.
1389 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001390 case ErrorCode::kSuccess:
1391 // OK, we parsed the response successfully but that does
1392 // necessarily mean that an update is available.
1393 if (HasOutputPipe()) {
1394 const OmahaResponse& response = GetOutputObject();
1395 if (response.update_exists) {
1396 result = metrics::CheckResult::kUpdateAvailable;
1397 reaction = metrics::CheckReaction::kUpdating;
1398 } else {
1399 result = metrics::CheckResult::kNoUpdateAvailable;
1400 }
David Zeuthen33bae492014-02-25 16:16:18 -08001401 } else {
1402 result = metrics::CheckResult::kNoUpdateAvailable;
1403 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001404 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001405
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001406 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1407 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1408 result = metrics::CheckResult::kUpdateAvailable;
1409 reaction = metrics::CheckReaction::kIgnored;
1410 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001411
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001412 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1413 result = metrics::CheckResult::kUpdateAvailable;
1414 reaction = metrics::CheckReaction::kDeferring;
1415 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001416
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001417 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1418 result = metrics::CheckResult::kUpdateAvailable;
1419 reaction = metrics::CheckReaction::kBackingOff;
1420 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001421
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001422 default:
1423 // We report two flavors of errors, "Download errors" and "Parsing
1424 // error". Try to convert to the former and if that doesn't work
1425 // we know it's the latter.
1426 metrics::DownloadErrorCode tmp_error =
1427 metrics_utils::GetDownloadErrorCode(code);
1428 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1429 result = metrics::CheckResult::kDownloadError;
1430 download_error_code = tmp_error;
1431 } else {
1432 result = metrics::CheckResult::kParsingError;
1433 }
1434 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001435 }
1436
Amin Hassanid3d84212019-08-17 00:27:44 -07001437 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1438 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001439}
1440
Toni Barzic61544e62018-10-11 14:37:30 -07001441bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1442 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001443 // Note: policy decision to not update to a version we rolled back from.
1444 string rollback_version =
1445 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001446 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001447 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001448 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001449 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001450 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001451 return true;
1452 }
1453 }
1454
Toni Barzic61544e62018-10-11 14:37:30 -07001455 if (system_state_->hardware()->IsOOBEEnabled() &&
1456 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
1457 (response.deadline.empty() ||
1458 system_state_->payload_state()->GetRollbackHappened()) &&
1459 params_->app_version() != "ForcedUpdate") {
1460 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1461 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1462 return true;
1463 }
1464
Weidong Guo421ff332017-04-17 10:08:38 -07001465 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001466 LOG(INFO) << "Update is not allowed over current connection.";
1467 return true;
1468 }
1469
1470 // Note: We could technically delete the UpdateFirstSeenAt state when we
1471 // return true. If we do, it'll mean a device has to restart the
1472 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1473 // turned on again. On the other hand, it also increases the chance of update
1474 // starvation if an admin turns AU on/off more frequently. We choose to err on
1475 // the side of preventing starvation at the cost of not applying scattering in
1476 // those cases.
1477 return false;
1478}
1479
Weidong Guo421ff332017-04-17 10:08:38 -07001480bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1481 const OmahaResponse& response) const {
1482 PrefsInterface* prefs = system_state_->prefs();
1483
1484 if (!prefs) {
1485 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1486 "not available.";
1487 return false;
1488 }
1489
1490 bool is_allowed;
1491
1492 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1493 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1494 is_allowed) {
1495 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1496 "set to true.";
1497 return true;
1498 }
1499
1500 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1501 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1502 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1503 "set to false or does not exist while target does not exist.";
1504 return false;
1505 }
1506
1507 std::string target_version;
1508 int64_t target_size;
1509
1510 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1511 &target_version) ||
1512 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1513 LOG(INFO) << "Disabling updates over cellular as the target version or "
1514 "size is not accessible.";
1515 return false;
1516 }
1517
1518 uint64_t total_packages_size = 0;
1519 for (const auto& package : response.packages) {
1520 total_packages_size += package.size;
1521 }
1522 if (target_version == response.version &&
1523 static_cast<uint64_t>(target_size) == total_packages_size) {
1524 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1525 "omaha response.";
1526 return true;
1527 } else {
1528 LOG(INFO) << "Disabling updates over cellular as the target does not"
1529 "match the omaha response.";
1530 return false;
1531 }
1532}
1533
1534bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1535 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001536 ConnectionType type;
1537 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001538 ConnectionManagerInterface* connection_manager =
1539 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001540 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001541 LOG(INFO) << "We could not determine our connection type. "
1542 << "Defaulting to allow updates.";
1543 return true;
1544 }
Weidong Guo421ff332017-04-17 10:08:38 -07001545
Chris Sosa77f79e82014-06-02 18:16:24 -07001546 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001547 bool is_device_policy_set =
1548 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1549 // Treats tethered connection as if it is cellular connection.
1550 bool is_over_cellular = type == ConnectionType::kCellular ||
1551 tethering == ConnectionTethering::kConfirmed;
1552
1553 if (!is_over_cellular) {
1554 // There's no need to further check user preferences as we are not over
1555 // cellular connection.
1556 if (!is_allowed)
1557 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1558 } else if (is_device_policy_set) {
1559 // There's no need to further check user preferences as the device policy
1560 // is set regarding updates over cellular.
1561 if (!is_allowed)
1562 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1563 } else {
1564 // Deivce policy is not set, so user preferences overwrite whether to
1565 // allow updates over cellular.
1566 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1567 if (!is_allowed)
1568 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1569 }
1570
Chris Sosa77f79e82014-06-02 18:16:24 -07001571 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001572 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001573 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1574 return is_allowed;
1575}
1576
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001577bool OmahaRequestAction::IsRollbackEnabled() const {
1578 if (policy_provider_->IsConsumerDevice()) {
1579 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1580 return false;
1581 }
1582
1583 if (!policy_provider_->device_policy_is_loaded()) {
1584 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1585 return true;
1586 }
1587
1588 int allowed_milestones;
1589 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1590 &allowed_milestones)) {
1591 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1592 "Defaulting to rollback enabled.";
1593 return true;
1594 }
1595
1596 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1597 return allowed_milestones > 0;
1598}
1599
1600void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001601 int max_kernel_rollforward;
1602 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001603 if (IsRollbackEnabled()) {
1604 // If rollback is enabled, set the max kernel key version to the current
1605 // kernel key version. This has the effect of freezing kernel key roll
1606 // forwards.
1607 //
1608 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1609 // key roll forward happens until the server side components of rollback
1610 // are implemented. Future changes will allow the Omaha server to return
1611 // the kernel key version from max_rollback_versions in the past. At that
1612 // point the max kernel key version will be set to that value, creating a
1613 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001614 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001615 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001616 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001617 } else {
1618 // For devices that are not rollback enabled (ie. consumer devices), the
1619 // max kernel key version is set to 0xfffffffe, which is logically
1620 // infinity. This maintains the previous behavior that that kernel key
1621 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001622 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001623 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001624 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001625 }
1626
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001627 bool max_rollforward_set =
1628 system_state_->hardware()->SetMaxKernelKeyRollforward(
1629 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001630 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001631 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001632 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001633 // Report metrics
1634 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1635 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001636}
1637
May Lippert60aa3ca2018-08-15 16:55:29 -07001638base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1639 Time update_first_seen_at;
1640 int64_t update_first_seen_at_int;
1641 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1642 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1643 &update_first_seen_at_int)) {
1644 // Note: This timestamp could be that of ANY update we saw in the past
1645 // (not necessarily this particular update we're considering to apply)
1646 // but never got to apply because of some reason (e.g. stop AU policy,
1647 // updates being pulled out from Omaha, changes in target version prefix,
1648 // new update being rolled out, etc.). But for the purposes of scattering
1649 // it doesn't matter which update the timestamp corresponds to. i.e.
1650 // the clock starts ticking the first time we see an update and we're
1651 // ready to apply when the random wait period is satisfied relative to
1652 // that first seen timestamp.
1653 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1654 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1655 << utils::ToString(update_first_seen_at);
1656 } else {
1657 // This seems like an unexpected error where the persisted value exists
1658 // but it's not readable for some reason.
1659 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1660 return base::Time();
1661 }
1662 } else {
1663 update_first_seen_at = system_state_->clock()->GetWallclockTime();
1664 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
1665 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1666 update_first_seen_at_int)) {
1667 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1668 << utils::ToString(update_first_seen_at);
1669 } else {
1670 // This seems like an unexpected error where the value cannot be
1671 // persisted for some reason.
1672 LOG(INFO) << "UpdateFirstSeenAt value "
1673 << utils::ToString(update_first_seen_at)
1674 << " cannot be persisted";
1675 return base::Time();
1676 }
1677 }
1678 return update_first_seen_at;
1679}
1680
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001681} // namespace chromeos_update_engine