blob: 85699d8ea1b9b739aac06aef98feab52f8f3e2cb [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>
31#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070032#include <base/strings/string_number_conversions.h>
Sen Jiang0affc2c2017-02-10 15:55:05 -080033#include <base/strings/string_split.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070034#include <base/strings/string_util.h>
35#include <base/strings/stringprintf.h>
36#include <base/time/time.h>
Sen Jiang684c9cd2017-10-17 16:26:45 -070037#include <brillo/key_value_store.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040038#include <expat.h>
Alex Deymoa2591792015-11-17 00:39:40 -030039#include <metrics/metrics_library.h>
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080040#include <policy/libpolicy.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000041
Alex Deymo39910dc2015-11-09 17:04:30 -080042#include "update_engine/common/action_pipe.h"
43#include "update_engine/common/constants.h"
44#include "update_engine/common/hardware_interface.h"
45#include "update_engine/common/hash_calculator.h"
46#include "update_engine/common/platform_constants.h"
Andrewe045aef2020-01-08 16:29:22 -080047#include "update_engine/common/prefs.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080048#include "update_engine/common/prefs_interface.h"
49#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070050#include "update_engine/connection_manager_interface.h"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070051#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080052#include "update_engine/metrics_utils.h"
Amin Hassani7fca2862019-03-28 16:09:22 -070053#include "update_engine/omaha_request_builder_xml.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070054#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070055#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080056#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000057
Darin Petkov1cbd78f2010-07-29 12:38:34 -070058using base::Time;
59using base::TimeDelta;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080060using chromeos_update_manager::kRollforwardInfinity;
David Zeuthene8ed8632014-07-24 13:38:10 -040061using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000062using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040063using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000064
65namespace chromeos_update_engine {
66
Amin Hassani6600a562018-09-24 15:17:19 -070067// List of custom attributes that we interpret in the Omaha response:
68constexpr char kAttrDeadline[] = "deadline";
69constexpr char kAttrDisableP2PForDownloading[] = "DisableP2PForDownloading";
70constexpr char kAttrDisableP2PForSharing[] = "DisableP2PForSharing";
71constexpr char kAttrDisablePayloadBackoff[] = "DisablePayloadBackoff";
72constexpr char kAttrVersion[] = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080073// Deprecated: "IsDelta"
Amin Hassani6600a562018-09-24 15:17:19 -070074constexpr char kAttrIsDeltaPayload[] = "IsDeltaPayload";
75constexpr char kAttrMaxFailureCountPerUrl[] = "MaxFailureCountPerUrl";
76constexpr char kAttrMaxDaysToScatter[] = "MaxDaysToScatter";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080077// Deprecated: "ManifestSignatureRsa"
78// Deprecated: "ManifestSize"
Amin Hassani6600a562018-09-24 15:17:19 -070079constexpr char kAttrMetadataSignatureRsa[] = "MetadataSignatureRsa";
80constexpr char kAttrMetadataSize[] = "MetadataSize";
81constexpr char kAttrMoreInfo[] = "MoreInfo";
82constexpr char kAttrNoUpdate[] = "noupdate";
Don Garrett42bd3aa2013-04-10 18:14:56 -070083// Deprecated: "NeedsAdmin"
Amin Hassani6600a562018-09-24 15:17:19 -070084constexpr char kAttrPollInterval[] = "PollInterval";
85constexpr char kAttrPowerwash[] = "Powerwash";
86constexpr char kAttrPrompt[] = "Prompt";
87constexpr char kAttrPublicKeyRsa[] = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080088
Amin Hassani6600a562018-09-24 15:17:19 -070089// List of attributes that we interpret in the Omaha response:
90constexpr char kAttrAppId[] = "appid";
91constexpr char kAttrCodeBase[] = "codebase";
92constexpr char kAttrCohort[] = "cohort";
93constexpr char kAttrCohortHint[] = "cohorthint";
94constexpr char kAttrCohortName[] = "cohortname";
95constexpr char kAttrElapsedDays[] = "elapsed_days";
96constexpr char kAttrElapsedSeconds[] = "elapsed_seconds";
97constexpr char kAttrEvent[] = "event";
98constexpr char kAttrHashSha256[] = "hash_sha256";
99// Deprecated: "hash"; Although we still need to pass it from the server for
100// backward compatibility.
101constexpr char kAttrName[] = "name";
102// Deprecated: "sha256"; Although we still need to pass it from the server for
103// backward compatibility.
104constexpr char kAttrSize[] = "size";
105constexpr char kAttrStatus[] = "status";
106
107// List of values that we interpret in the Omaha response:
108constexpr char kValPostInstall[] = "postinstall";
109constexpr char kValNoUpdate[] = "noupdate";
110
Alex Deymob3fa53b2016-04-18 19:57:58 -0700111// updatecheck attributes (without the underscore prefix).
Amin Hassani2cbb0692019-10-30 13:36:17 -0700112// Deprecated: "eol"
Jae Hoon Kim051627a2019-09-03 12:56:32 -0700113constexpr char kAttrEolDate[] = "eol_date";
Amin Hassani6600a562018-09-24 15:17:19 -0700114constexpr char kAttrRollback[] = "rollback";
115constexpr char kAttrFirmwareVersion[] = "firmware_version";
116constexpr char kAttrKernelVersion[] = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -0700117
David Zeuthene8ed8632014-07-24 13:38:10 -0400118// Struct used for holding data obtained when parsing the XML.
119struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400120 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
121
122 // Pointer to the expat XML_Parser object.
123 XML_Parser xml_parser;
124
David Zeuthene8ed8632014-07-24 13:38:10 -0400125 // This is the state of the parser as it's processing the XML.
126 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400127 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400128 string current_path;
129
130 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400131 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700132 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400133 string daystart_elapsed_days;
134 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800135
Sen Jiang81259682017-03-30 15:11:30 -0700136 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700137 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700138 vector<string> url_codebase;
139 string manifest_version;
140 map<string, string> action_postinstall_attrs;
141 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700142 string cohort;
143 string cohorthint;
144 string cohortname;
145 bool cohort_set = false;
146 bool cohorthint_set = false;
147 bool cohortname_set = false;
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;
Amin Hassani6600a562018-09-24 15:17:19 -0700183 if (attrs.find(kAttrAppId) != attrs.end()) {
184 app.id = attrs[kAttrAppId];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700185 }
Amin Hassani6600a562018-09-24 15:17:19 -0700186 if (attrs.find(kAttrCohort) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700187 app.cohort_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700188 app.cohort = attrs[kAttrCohort];
Alex Deymo8e18f932015-03-27 16:16:59 -0700189 }
Amin Hassani6600a562018-09-24 15:17:19 -0700190 if (attrs.find(kAttrCohortHint) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700191 app.cohorthint_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700192 app.cohorthint = attrs[kAttrCohortHint];
Alex Deymo8e18f932015-03-27 16:16:59 -0700193 }
Amin Hassani6600a562018-09-24 15:17:19 -0700194 if (attrs.find(kAttrCohortName) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700195 app.cohortname_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700196 app.cohortname = attrs[kAttrCohortName];
Alex Deymo8e18f932015-03-27 16:16:59 -0700197 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700198 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700199 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700200 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700201 data->apps.back().updatecheck_status = attrs[kAttrStatus];
Sen Jiang81259682017-03-30 15:11:30 -0700202 if (data->updatecheck_poll_interval.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700203 data->updatecheck_poll_interval = attrs[kAttrPollInterval];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700204 // Omaha sends arbitrary key-value pairs as extra attributes starting with
205 // an underscore.
206 for (const auto& attr : attrs) {
207 if (!attr.first.empty() && attr.first[0] == '_')
208 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
209 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400210 } else if (data->current_path == "/response/daystart") {
211 // Get the install-date.
Amin Hassani6600a562018-09-24 15:17:19 -0700212 data->daystart_elapsed_days = attrs[kAttrElapsedDays];
213 data->daystart_elapsed_seconds = attrs[kAttrElapsedSeconds];
David Zeuthene8ed8632014-07-24 13:38:10 -0400214 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
215 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700216 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700217 data->apps.back().url_codebase.push_back(attrs[kAttrCodeBase]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800218 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400219 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800220 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700221 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700222 data->apps.back().packages.push_back({.name = attrs[kAttrName],
223 .size = attrs[kAttrSize],
224 .hash = attrs[kAttrHashSha256]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400225 } else if (data->current_path == "/response/app/updatecheck/manifest") {
226 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700227 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700228 data->apps.back().manifest_version = attrs[kAttrVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400229 } else if (data->current_path ==
230 "/response/app/updatecheck/manifest/actions/action") {
231 // We only care about the postinstall action.
Amin Hassani6600a562018-09-24 15:17:19 -0700232 if (attrs[kAttrEvent] == kValPostInstall && !data->apps.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700233 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400234 }
235 }
236}
237
238// Callback function invoked by expat.
239void ParserHandlerEnd(void* user_data, const XML_Char* element) {
240 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
241 if (data->failed)
242 return;
243
244 const string path_suffix = string("/") + element;
245
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800246 if (!base::EndsWith(
247 data->current_path, path_suffix, base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400248 LOG(ERROR) << "Unexpected end element '" << element
249 << "' with current_path='" << data->current_path << "'";
250 data->failed = true;
251 return;
252 }
253 data->current_path.resize(data->current_path.size() - path_suffix.size());
254}
255
David Zeuthenf3e28012014-08-26 18:23:52 -0400256// Callback function invoked by expat.
257//
258// This is called for entity declarations. Since Omaha is guaranteed
259// to never return any XML with entities our course of action is to
260// just stop parsing. This avoids potential resource exhaustion
261// problems AKA the "billion laughs". CVE-2013-0340.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800262void ParserHandlerEntityDecl(void* user_data,
263 const XML_Char* entity_name,
David Zeuthenf3e28012014-08-26 18:23:52 -0400264 int is_parameter_entity,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800265 const XML_Char* value,
David Zeuthenf3e28012014-08-26 18:23:52 -0400266 int value_length,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800267 const XML_Char* base,
268 const XML_Char* system_id,
269 const XML_Char* public_id,
270 const XML_Char* notation_name) {
David Zeuthenf3e28012014-08-26 18:23:52 -0400271 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
272
273 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
274 data->failed = true;
275 data->entity_decl = true;
276 XML_StopParser(data->xml_parser, false);
277}
278
David Zeuthene8ed8632014-07-24 13:38:10 -0400279} // namespace
280
Alex Deymoc1c17b42015-11-23 03:53:15 -0300281OmahaRequestAction::OmahaRequestAction(
282 SystemState* system_state,
283 OmahaEvent* event,
284 std::unique_ptr<HttpFetcher> http_fetcher,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700285 bool ping_only,
286 const string& session_id)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800287 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800288 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700289 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300290 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800291 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700292 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700293 ping_active_days_(0),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700294 ping_roll_call_days_(0),
295 session_id_(session_id) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800296 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700297}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000298
Darin Petkov6a5b3222010-07-13 14:55:28 -0700299OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000300
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700301// Calculates the value to use for the ping days parameter.
302int OmahaRequestAction::CalculatePingDays(const string& key) {
Andrewe045aef2020-01-08 16:29:22 -0800303 int days = kPingNeverPinged;
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700304 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800305 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700306 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
307 if (days < 0) {
308 // If |days| is negative, then the system clock must have jumped
309 // back in time since the ping was sent. Mark the value so that
310 // it doesn't get sent to the server but we still update the
311 // last ping daystart preference. This way the next ping time
312 // will be correct, hopefully.
313 days = kPingTimeJump;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800314 LOG(WARNING)
315 << "System clock jumped back in time. Resetting ping daystarts.";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700316 }
317 }
318 return days;
319}
320
321void OmahaRequestAction::InitPingDays() {
322 // We send pings only along with update checks, not with events.
323 if (IsEvent()) {
324 return;
325 }
326 // TODO(petkov): Figure a way to distinguish active use pings
327 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700328 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700329 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
330 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
331}
332
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700333bool OmahaRequestAction::ShouldPing() const {
Andrewe045aef2020-01-08 16:29:22 -0800334 if (ping_active_days_ == kPingNeverPinged &&
335 ping_roll_call_days_ == kPingNeverPinged) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700336 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
337 if (powerwash_count > 0) {
338 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
339 << "powerwash_count is " << powerwash_count;
340 return false;
341 }
Amin Hassani1677e812017-06-21 13:36:36 -0700342 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
343 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
344 << "the first_active_omaha_ping_sent is true";
345 return false;
346 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700347 return true;
348 }
349 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
350}
351
David Zeuthen639aa362014-02-03 16:23:44 -0800352// static
353int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
354 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700355 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800356 return -1;
357
358 // If we have the value stored on disk, just return it.
359 int64_t stored_value;
360 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
361 // Convert and sanity-check.
362 int install_date_days = static_cast<int>(stored_value);
363 if (install_date_days >= 0)
364 return install_date_days;
365 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
366 << install_date_days << " looks suspicious.";
367 prefs->Delete(kPrefsInstallDateDays);
368 }
369
370 // Otherwise, if OOBE is not complete then do nothing and wait for
371 // ParseResponse() to call ParseInstallDate() and then
372 // PersistInstallDate() to set the kPrefsInstallDateDays state
373 // variable. Once that is done, we'll then report back in future
374 // Omaha requests. This works exactly because OOBE triggers an
375 // update check.
376 //
377 // However, if OOBE is complete and the kPrefsInstallDateDays state
378 // variable is not set, there are two possibilities
379 //
380 // 1. The update check in OOBE failed so we never got a response
381 // from Omaha (no network etc.); or
382 //
383 // 2. OOBE was done on an older version that didn't write to the
384 // kPrefsInstallDateDays state variable.
385 //
386 // In both cases, we approximate the install date by simply
387 // inspecting the timestamp of when OOBE happened.
388
389 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700390 if (!system_state->hardware()->IsOOBEEnabled() ||
391 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800392 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700393 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800394 return -1;
395 }
396
397 int num_days;
398 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
399 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
400 << "as its value '" << utils::ToString(time_of_oobe)
401 << "' looks suspicious.";
402 return -1;
403 }
404
405 // Persist this to disk, for future use.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800406 if (!OmahaRequestAction::PersistInstallDate(
407 system_state, num_days, kProvisionedFromOOBEMarker))
David Zeuthen639aa362014-02-03 16:23:44 -0800408 return -1;
409
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800410 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to " << num_days
411 << " days";
David Zeuthen639aa362014-02-03 16:23:44 -0800412
413 return num_days;
414}
415
Andrewe045aef2020-01-08 16:29:22 -0800416void OmahaRequestAction::StorePingReply(
417 const OmahaParserData& parser_data) const {
418 for (const auto& app : parser_data.apps) {
419 auto it = params_->dlc_apps_params().find(app.id);
420 if (it == params_->dlc_apps_params().end())
421 continue;
422
423 const OmahaRequestParams::AppParams& dlc_params = it->second;
424
425 // Skip if the ping for this DLC was not sent.
426 if (!dlc_params.send_ping)
427 continue;
428
429 base::FilePath metadata_path =
430 base::FilePath(params_->dlc_prefs_root()).Append(dlc_params.name);
Andrewe045aef2020-01-08 16:29:22 -0800431
432 Prefs prefs;
Andrewa8d7df32020-03-15 20:10:01 -0700433 if (!base::CreateDirectory(metadata_path) || !prefs.Init(metadata_path)) {
Andrewe045aef2020-01-08 16:29:22 -0800434 LOG(ERROR) << "Failed to initialize the preferences path:"
435 << metadata_path.value() << ".";
436 continue;
437 }
438 // Reset the active metadata value to |kPingInactiveValue|.
Andrewa8d7df32020-03-15 20:10:01 -0700439 if (!prefs.SetInt64(kPrefsPingActive, kPingInactiveValue))
Andrewe045aef2020-01-08 16:29:22 -0800440 LOG(ERROR) << "Failed to set the value of ping metadata '"
441 << kPrefsPingActive << "'.";
442
443 if (!prefs.SetString(kPrefsPingLastRollcall,
444 parser_data.daystart_elapsed_days))
445 LOG(ERROR) << "Failed to set the value of ping metadata '"
446 << kPrefsPingLastRollcall << "'.";
447
448 if (dlc_params.ping_active) {
449 // Write the value of elapsed_days into |kPrefsPingLastActive| only if
450 // the previous ping was an active one.
451 if (!prefs.SetString(kPrefsPingLastActive,
452 parser_data.daystart_elapsed_days))
453 LOG(ERROR) << "Failed to set the value of ping metadata '"
454 << kPrefsPingLastActive << "'.";
455 }
456 }
457}
458
Darin Petkov6a5b3222010-07-13 14:55:28 -0700459void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000460 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700461 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700462 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700463 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700464 return;
465 }
David Zeuthen639aa362014-02-03 16:23:44 -0800466
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700467 OmahaRequestBuilderXml omaha_request(event_.get(),
468 params_,
469 ping_only_,
470 ShouldPing(), // include_ping
471 ping_active_days_,
472 ping_roll_call_days_,
473 GetInstallDate(system_state_),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700474 system_state_->prefs(),
475 session_id_);
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700476 string request_post = omaha_request.GetRequest();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700477
Sen Jiang42fa45e2018-03-12 11:02:14 -0700478 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700479 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
480 params_->interactive() ? "fg" : "bg");
481 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
482 http_fetcher_->SetHeader(
483 kXGoogleUpdateUpdater,
484 base::StringPrintf(
485 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
486
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800487 http_fetcher_->SetPostData(
488 request_post.data(), request_post.size(), kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700489 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700490 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700491 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000492}
493
Darin Petkov6a5b3222010-07-13 14:55:28 -0700494void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000495 http_fetcher_->TerminateTransfer();
496}
497
498// We just store the response in the buffer. Once we've received all bytes,
499// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700500bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800501 const void* bytes,
502 size_t length) {
503 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
504 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700505 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000506}
507
508namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000509
510// Parses a 64 bit base-10 int from a string and returns it. Returns 0
511// on error. If the string contains "0", that's indistinguishable from
512// error.
513off_t ParseInt(const string& str) {
514 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700515 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000516 if (rc < 1) {
517 // failure
518 return 0;
519 }
520 return ret;
521}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700522
David Zeuthene8ed8632014-07-24 13:38:10 -0400523// Parses |str| and returns |true| if, and only if, its value is "true".
524bool ParseBool(const string& str) {
525 return str == "true";
526}
527
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700528// Update the last ping day preferences based on the server daystart
529// response. Returns true on success, false otherwise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800530bool UpdateLastPingDays(OmahaParserData* parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700531 int64_t elapsed_seconds = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800532 TEST_AND_RETURN_FALSE(base::StringToInt64(
533 parser_data->daystart_elapsed_seconds, &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700534 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
535
536 // Remember the local time that matches the server's last midnight
537 // time.
538 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
539 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
540 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
541 return true;
542}
Sen Jiang81259682017-03-30 15:11:30 -0700543
544// Parses the package node in the given XML document and populates
545// |output_object| if valid. Returns true if we should continue the parsing.
546// False otherwise, in which case it sets any error code using |completer|.
547bool ParsePackage(OmahaParserData::App* app,
548 OmahaResponse* output_object,
549 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700550 if (app->updatecheck_status.empty() ||
551 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700552 if (!app->packages.empty()) {
553 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
554 completer->set_code(ErrorCode::kOmahaResponseInvalid);
555 return false;
556 }
557 return true;
558 }
559 if (app->packages.empty()) {
560 LOG(ERROR) << "Omaha Response has no packages";
561 completer->set_code(ErrorCode::kOmahaResponseInvalid);
562 return false;
563 }
564 if (app->url_codebase.empty()) {
565 LOG(ERROR) << "No Omaha Response URLs";
566 completer->set_code(ErrorCode::kOmahaResponseInvalid);
567 return false;
568 }
569 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
570 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700571 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700572 ":",
573 base::TRIM_WHITESPACE,
574 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700575 vector<string> metadata_signatures = base::SplitString(
576 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
577 ":",
578 base::TRIM_WHITESPACE,
579 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700580 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700581 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700582 ":",
583 base::TRIM_WHITESPACE,
584 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700585 for (size_t i = 0; i < app->packages.size(); i++) {
586 const auto& package = app->packages[i];
587 if (package.name.empty()) {
588 LOG(ERROR) << "Omaha Response has empty package name";
589 completer->set_code(ErrorCode::kOmahaResponseInvalid);
590 return false;
591 }
592 LOG(INFO) << "Found package " << package.name;
593
594 OmahaResponse::Package out_package;
595 for (const string& codebase : app->url_codebase) {
596 if (codebase.empty()) {
597 LOG(ERROR) << "Omaha Response URL has empty codebase";
598 completer->set_code(ErrorCode::kOmahaResponseInvalid);
599 return false;
600 }
601 out_package.payload_urls.push_back(codebase + package.name);
602 }
603 // Parse the payload size.
604 base::StringToUint64(package.size, &out_package.size);
605 if (out_package.size <= 0) {
606 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
607 completer->set_code(ErrorCode::kOmahaResponseInvalid);
608 return false;
609 }
610 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
611
612 if (i < metadata_sizes.size())
613 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
614 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
615 << " bytes";
616
617 if (i < metadata_signatures.size())
618 out_package.metadata_signature = metadata_signatures[i];
619 LOG(INFO) << "Payload metadata signature = "
620 << out_package.metadata_signature;
621
622 out_package.hash = package.hash;
623 if (out_package.hash.empty()) {
624 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
625 completer->set_code(ErrorCode::kOmahaResponseInvalid);
626 return false;
627 }
628 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700629
630 if (i < is_delta_payloads.size())
631 out_package.is_delta = ParseBool(is_delta_payloads[i]);
632 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
633
Sen Jiang81259682017-03-30 15:11:30 -0700634 output_object->packages.push_back(std::move(out_package));
635 }
636
637 return true;
638}
639
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700640// Parses the 2 key version strings kernel_version and firmware_version. If the
641// field is not present, or cannot be parsed the values default to 0xffff.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700642void ParseRollbackVersions(int allowed_milestones,
643 OmahaParserData* parser_data,
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700644 OmahaResponse* output_object) {
645 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700646 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700647 &output_object->rollback_key_version.firmware_key,
648 &output_object->rollback_key_version.firmware);
649 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700650 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700651 &output_object->rollback_key_version.kernel_key,
652 &output_object->rollback_key_version.kernel);
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700653
654 // Create the attribute name strings for milestone N - allowed_milestones.
655 const string firmware_max_rollforward_attr =
656 base::StringPrintf("%s_%i", kAttrFirmwareVersion, allowed_milestones);
657 const string kernel_max_rollforward_attr =
658 base::StringPrintf("%s_%i", kAttrKernelVersion, allowed_milestones);
659
660 const bool max_firmware_and_kernel_exist =
661 parser_data->updatecheck_attrs.count(firmware_max_rollforward_attr) > 0 &&
662 parser_data->updatecheck_attrs.count(kernel_max_rollforward_attr) > 0;
663
664 string firmware_version;
665 string kernel_version;
666 if (max_firmware_and_kernel_exist) {
667 firmware_version =
668 parser_data->updatecheck_attrs[firmware_max_rollforward_attr];
669 kernel_version =
670 parser_data->updatecheck_attrs[kernel_max_rollforward_attr];
671 }
672
673 LOG(INFO) << "For milestone N-" << allowed_milestones
674 << " firmware_key_version=" << firmware_version
675 << " kernel_key_version=" << kernel_version;
676
677 OmahaResponse::RollbackKeyVersion version;
678 utils::ParseRollbackKeyVersion(
679 firmware_version, &version.firmware_key, &version.firmware);
680 utils::ParseRollbackKeyVersion(
681 kernel_version, &version.kernel_key, &version.kernel);
682
683 output_object->past_rollback_key_version = std::move(version);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700684}
685
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700686} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000687
David Zeuthene8ed8632014-07-24 13:38:10 -0400688bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700689 OmahaResponse* output_object,
690 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700691 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700692 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700693 return false;
694 }
Sen Jiang81259682017-03-30 15:11:30 -0700695 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700696
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800697 // chromium-os:37289: The PollInterval is not supported by Omaha server
698 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700699 // slow down the request rate from the server-side. Note that the PollInterval
700 // is not persisted, so it has to be sent by the server on every response to
701 // guarantee that the scheduler uses this value (otherwise, if the device got
702 // rebooted after the last server-indicated value, it'll revert to the default
703 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
704 // based on the assumption that we perform an update check every hour so that
705 // the max value of 8 will roughly be equivalent to one work day. If we decide
706 // to use PollInterval permanently, we should update the
707 // max_update_checks_allowed to take PollInterval into account. Note: The
708 // parsing for PollInterval happens even before parsing of the status because
709 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400710 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700711 &output_object->poll_interval);
712
David Zeuthen639aa362014-02-03 16:23:44 -0800713 // Check for the "elapsed_days" attribute in the "daystart"
714 // element. This is the number of days since Jan 1 2007, 0:00
715 // PST. If we don't have a persisted value of the Omaha InstallDate,
716 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400717 if (ParseInstallDate(parser_data, output_object) &&
718 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800719 // Since output_object->install_date_days is never negative, the
720 // elapsed_days -> install-date calculation is reduced to simply
721 // rounding down to the nearest number divisible by 7.
722 int remainder = output_object->install_date_days % 7;
723 int install_date_days_rounded =
724 output_object->install_date_days - remainder;
725 if (PersistInstallDate(system_state_,
726 install_date_days_rounded,
727 kProvisionedFromOmahaResponse)) {
728 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
729 << install_date_days_rounded << " days";
730 }
731 }
732
Alex Deymo00d79ac2015-06-29 15:41:49 -0700733 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700734 for (const auto& app : parser_data->apps) {
735 if (app.id == params_->GetAppId()) {
736 if (app.cohort_set)
737 PersistCohortData(kPrefsOmahaCohort, app.cohort);
738 if (app.cohorthint_set)
739 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
740 if (app.cohortname_set)
741 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
742 break;
743 }
744 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700745
Amin Hassani2cbb0692019-10-30 13:36:17 -0700746 PersistEolInfo(parser_data->updatecheck_attrs);
747
Marton Hunyady199152d2018-05-07 19:08:48 +0200748 // Rollback-related updatecheck attributes.
749 // Defaults to false if attribute is not present.
750 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -0700751 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700752
753 // Parses the rollback versions of the current image. If the fields do not
754 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700755 ParseRollbackVersions(
756 params_->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -0700757
David Zeuthene8ed8632014-07-24 13:38:10 -0400758 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700759 return false;
760
David Zeuthene8ed8632014-07-24 13:38:10 -0400761 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700762 return false;
763
Sen Jiang0affc2c2017-02-10 15:55:05 -0800764 // Package has to be parsed after Params now because ParseParams need to make
765 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -0700766 for (auto& app : parser_data->apps)
767 if (!ParsePackage(&app, output_object, completer))
768 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800769
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700770 return true;
771}
772
David Zeuthene8ed8632014-07-24 13:38:10 -0400773bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700774 OmahaResponse* output_object,
775 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700776 output_object->update_exists = false;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700777 for (const auto& app : parser_data->apps) {
778 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -0700779 if (status == kValNoUpdate) {
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800780 // If the app is a DLC, allow status "noupdate" to support DLC
781 // deprecations.
782 if (params_->IsDlcAppId(app.id)) {
783 LOG(INFO) << "No update for <app> " << app.id
784 << " but update continuing since a DLC.";
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700785 params_->SetDlcNoUpdate(app.id);
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800786 continue;
787 }
Sen Jiang00adf7b2017-06-26 15:57:29 -0700788 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -0700789 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700790 output_object->update_exists = false;
791 break;
Sen Jiang81259682017-03-30 15:11:30 -0700792 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700793 auto const& attr_no_update =
794 app.action_postinstall_attrs.find(kAttrNoUpdate);
795 if (attr_no_update != app.action_postinstall_attrs.end() &&
796 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700797 // noupdate="true" in postinstall attributes means it's an update to
798 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -0700799 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700800 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700801 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700802 output_object->update_exists = true;
803 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700804 } else if (status.empty() && params_->is_install() &&
805 params_->GetAppId() == app.id) {
806 // Skips the platform app for install operation.
807 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -0700808 } else {
809 LOG(ERROR) << "Unknown Omaha response status: " << status;
810 completer->set_code(ErrorCode::kOmahaResponseInvalid);
811 return false;
812 }
813 }
814 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700815 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700816 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700817 }
818
Sen Jiang81259682017-03-30 15:11:30 -0700819 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700820}
821
David Zeuthene8ed8632014-07-24 13:38:10 -0400822bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700823 OmahaResponse* output_object,
824 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700825 map<string, string> attrs;
826 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700827 if (app.id == params_->GetAppId()) {
828 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -0700829 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700830 } else if (!params_->system_app_id().empty() &&
831 app.id == params_->system_app_id()) {
832 // this is the system app (this check is intentionally skipped if there is
833 // no system_app_id set)
834 output_object->system_version = app.manifest_version;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700835 } else if (params_->is_install() &&
836 app.manifest_version != params_->app_version()) {
837 LOG(WARNING) << "An app has a different version (" << app.manifest_version
838 << ") that is different than platform app version ("
839 << params_->app_version() << ")";
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700840 }
841 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700842 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700843 }
Sen Jiang81259682017-03-30 15:11:30 -0700844 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700845 if (params_->is_install()) {
846 LOG(INFO) << "Use request version for Install operation.";
847 output_object->version = params_->app_version();
848 }
Chris Sosa3b748432013-06-20 16:42:59 -0700849 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700850 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700851 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700852 return false;
853 }
854
855 LOG(INFO) << "Received omaha response to update to version "
856 << output_object->version;
857
David Zeuthene8ed8632014-07-24 13:38:10 -0400858 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700859 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700860 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700861 return false;
862 }
863
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800864 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -0700865 output_object->more_info_url = attrs[kAttrMoreInfo];
866 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
867 output_object->deadline = attrs[kAttrDeadline];
868 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700869 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -0700870 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700871 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -0700872 ParseBool(attrs[kAttrDisableP2PForSharing]);
873 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800874
Amin Hassani6600a562018-09-24 15:17:19 -0700875 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800876 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800877 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700878
Jay Srinivasan08262882012-12-28 19:29:43 -0800879 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -0700880 ParseBool(attrs[kAttrDisablePayloadBackoff]);
881 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800882
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700883 return true;
884}
885
David Zeuthene8ed8632014-07-24 13:38:10 -0400886// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000887// and fill in the appropriate fields of the output object. Also, notifies
888// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800889void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -0700890 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000891 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800892 string current_response(response_buffer_.begin(), response_buffer_.end());
893 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700894
Gilad Arnold74b5f552014-10-07 08:17:16 -0700895 PayloadStateInterface* const payload_state = system_state_->payload_state();
896
Zentaro Kavanagh76af2662018-05-15 10:54:53 -0700897 // Set the max kernel key version based on whether rollback is allowed.
898 SetMaxKernelKeyVersionForRollback();
899
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700900 // Events are best effort transactions -- assume they always succeed.
901 if (IsEvent()) {
902 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700903 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700904 return;
905 }
906
Amin Hassanid3d84212019-08-17 00:27:44 -0700907 ErrorCode aux_error_code = fetcher->GetAuxiliaryErrorCode();
908 if (aux_error_code != ErrorCode::kSuccess) {
909 metrics::DownloadErrorCode download_error_code =
910 metrics_utils::GetDownloadErrorCode(aux_error_code);
911 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
912 system_state_,
913 metrics::CheckResult::kUnset,
914 metrics::CheckReaction::kUnset,
915 download_error_code);
916 }
917
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700918 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700919 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700920 int code = GetHTTPResponseCode();
921 // Makes sure we send sane error values.
922 if (code < 0 || code >= 1000) {
923 code = 999;
924 }
David Zeuthena99981f2013-04-29 13:42:47 -0700925 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700926 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000927 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700928 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000929
David Zeuthene8ed8632014-07-24 13:38:10 -0400930 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400931 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400932 XML_SetUserData(parser, &parser_data);
933 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400934 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800935 XML_Status res =
936 XML_Parse(parser,
937 reinterpret_cast<const char*>(response_buffer_.data()),
938 response_buffer_.size(),
939 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400940
941 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700942 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800943 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
944 << XML_GetCurrentLineNumber(parser) << " col "
945 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -0700946 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400947 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
948 if (response_buffer_.empty()) {
949 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
950 } else if (parser_data.entity_decl) {
951 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
952 }
953 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000954 return;
955 }
Amin Hassani91f48b42018-08-06 17:47:14 -0700956 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000957
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700958 // Update the last ping day preferences based on the server daystart response
959 // even if we didn't send a ping. Omaha always includes the daystart in the
960 // response, but log the error if it didn't.
961 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
962 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700963
Amin Hassani1677e812017-06-21 13:36:36 -0700964 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
965 // we have got a response from omaha and if its value has never been set to
966 // true before. Failure of this function should be ignored. There should be no
967 // need to check if a=-1 has been sent because older devices have already sent
968 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
969 // future checks.
970 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700971 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
972 system_state_->metrics_reporter()->ReportInternalErrorCode(
973 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
974 }
Amin Hassani1677e812017-06-21 13:36:36 -0700975 }
976
Andrewe045aef2020-01-08 16:29:22 -0800977 // Create/update the metadata files for each DLC app received.
978 StorePingReply(parser_data);
979
Thieu Le116fda32011-04-19 11:01:54 -0700980 if (!HasOutputPipe()) {
981 // Just set success to whether or not the http transfer succeeded,
982 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700983 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700984 return;
985 }
986
Darin Petkov6a5b3222010-07-13 14:55:28 -0700987 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400988 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000989 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700990 output_object.update_exists = true;
991 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000992
Toni Barzic61544e62018-10-11 14:37:30 -0700993 LoadOrPersistUpdateFirstSeenAtPref();
994
Weidong Guo421ff332017-04-17 10:08:38 -0700995 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -0700996 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -0700997 // No need to change output_object.update_exists here, since the value
998 // has been output to the pipe.
999 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001000 return;
1001 }
1002
David Zeuthen8f191b22013-08-06 12:27:50 -07001003 // If Omaha says to disable p2p, respect that
1004 if (output_object.disable_p2p_for_downloading) {
1005 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1006 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001007 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001008 }
1009 if (output_object.disable_p2p_for_sharing) {
1010 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1011 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001012 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001013 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001014
1015 // Update the payload state with the current response. The payload state
1016 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001017 // from what's stored already. We are updating the payload state as late
1018 // as possible in this method so that if a new release gets pushed and then
1019 // got pulled back due to some issues, we don't want to clear our internal
1020 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001021 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001022
David Zeuthen8f191b22013-08-06 12:27:50 -07001023 // It could be we've already exceeded the deadline for when p2p is
1024 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001025 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001026 payload_state->P2PNewAttempt();
1027 if (!payload_state->P2PAttemptAllowed()) {
1028 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1029 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001030 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001031 }
1032 }
1033
1034 // From here on, we'll complete stuff in CompleteProcessing() so
1035 // disable |completer| since we'll create a new one in that
1036 // function.
1037 completer.set_should_complete(false);
1038
1039 // If we're allowed to use p2p for downloading we do not pay
1040 // attention to wall-clock-based waiting if the URL is indeed
1041 // available via p2p. Therefore, check if the file is available via
1042 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001043 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001044 LookupPayloadViaP2P(output_object);
1045 } else {
1046 CompleteProcessing();
1047 }
1048}
1049
1050void OmahaRequestAction::CompleteProcessing() {
1051 ScopedActionCompleter completer(processor_, this);
1052 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1053 PayloadStateInterface* payload_state = system_state_->payload_state();
1054
1055 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001056 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001057 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001058 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001059 return;
1060 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001061
Chris Sosa20f005c2013-09-05 13:53:08 -07001062 if (payload_state->ShouldBackoffDownload()) {
1063 output_object.update_exists = false;
1064 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1065 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001066 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001067 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001068 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001069 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001070}
1071
1072void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1073 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1074 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001075 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001076 } else {
1077 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1078 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001079 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001080 }
1081 CompleteProcessing();
1082}
1083
1084void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001085 // If the device is in the middle of an update, the state variables
1086 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1087 // tracks the offset and length of the operation currently in
1088 // progress. The offset is based from the end of the manifest which
1089 // is kPrefsManifestMetadataSize bytes long.
1090 //
1091 // To make forward progress and avoid deadlocks, we need to find a
1092 // peer that has at least the entire operation we're currently
1093 // working on. Otherwise we may end up in a situation where two
1094 // devices bounce back and forth downloading from each other,
1095 // neither making any forward progress until one of them decides to
1096 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1097 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001098 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001099 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001100 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001101 int64_t next_data_offset = 0;
1102 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001103 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001104 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1105 &manifest_metadata_size) &&
1106 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001107 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1108 &manifest_signature_size) &&
1109 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001110 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001111 &next_data_offset) &&
1112 next_data_offset != -1 &&
1113 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1114 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001115 minimum_size = manifest_metadata_size + manifest_signature_size +
1116 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001117 }
1118
Sen Jiang0affc2c2017-02-10 15:55:05 -08001119 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001120 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001121 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001122 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001123 string file_id =
1124 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001125 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001126 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1127 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001128 system_state_->p2p_manager()->LookupUrlForFile(
1129 file_id,
1130 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001131 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001132 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1133 base::Unretained(this)));
1134 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001135}
1136
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001137bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001138 if (params_->interactive()) {
1139 LOG(INFO) << "Not deferring download because update is interactive.";
1140 return false;
1141 }
1142
David Zeuthen8f191b22013-08-06 12:27:50 -07001143 // If we're using p2p to download _and_ we have a p2p URL, we never
1144 // defer the download. This is because the download will always
1145 // happen from a peer on the LAN and we've been waiting in line for
1146 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001147 const PayloadStateInterface* payload_state = system_state_->payload_state();
1148 if (payload_state->GetUsingP2PForDownloading() &&
1149 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001150 LOG(INFO) << "Download not deferred because download "
1151 << "will happen from a local peer (via p2p).";
1152 return false;
1153 }
1154
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001155 // We should defer the downloads only if we've first satisfied the
1156 // wall-clock-based-waiting period and then the update-check-based waiting
1157 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001158 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001159 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1160 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001161 return false;
1162 }
1163
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001164 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001165 case kWallClockWaitNotSatisfied:
1166 // We haven't even satisfied the first condition, passing the
1167 // wall-clock-based waiting period, so we should defer the downloads
1168 // until that happens.
1169 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1170 return true;
1171
1172 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1173 LOG(INFO) << "wall-clock-based-wait satisfied and "
1174 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001175 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001176
1177 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1178 // Wall-clock-based waiting period is satisfied, and it's determined
1179 // that we do not need the update-check-based wait. so no need to
1180 // defer downloads.
1181 LOG(INFO) << "wall-clock-based-wait satisfied and "
1182 << "update-check-based-wait is not required.";
1183 return false;
1184
1185 default:
1186 // Returning false for this default case so we err on the
1187 // side of downloading updates than deferring in case of any bugs.
1188 NOTREACHED();
1189 return false;
1190 }
1191}
1192
1193OmahaRequestAction::WallClockWaitResult
1194OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001195 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001196 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1197 if (update_first_seen_at == base::Time()) {
1198 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
1199 "persisted";
1200 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001201 }
1202
Sen Jiang7c1171e2016-06-23 11:35:40 -07001203 TimeDelta elapsed_time =
1204 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1205 TimeDelta max_scatter_period =
1206 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001207 int64_t staging_wait_time_in_days = 0;
1208 // Use staging and its default max value if staging is on.
1209 if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1210 &staging_wait_time_in_days) &&
1211 staging_wait_time_in_days > 0)
1212 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001213
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001214 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001215 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001216 << ", Time Elapsed = "
1217 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001218 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001219
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001220 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001221 // The deadline is set for all rules which serve a delta update from a
1222 // previous FSI, which means this update will be applied mostly in OOBE
1223 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1224 // quickly.
1225 LOG(INFO) << "Not scattering as deadline flag is set";
1226 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1227 }
1228
1229 if (max_scatter_period.InDays() == 0) {
1230 // This means the Omaha rule creator decides that this rule
1231 // should not be scattered irrespective of the policy.
1232 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1233 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1234 }
1235
1236 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001237 // This means we've waited more than the upperbound wait in the rule
1238 // from the time we first saw a valid update available to us.
1239 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001240 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1241 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1242 }
1243
1244 // This means we are required to participate in scattering.
1245 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001246 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001247 if (remaining_wait_time.InSeconds() <= 0) {
1248 // Yes, it's our turn now.
1249 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1250
1251 // But we can't download until the update-check-count-based wait is also
1252 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001253 return params_->update_check_count_wait_enabled()
1254 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1255 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001256 }
1257
1258 // Not our turn yet, so we have to wait until our turn to
1259 // help scatter the downloads across all clients of the enterprise.
1260 LOG(INFO) << "Update deferred for another "
1261 << utils::FormatSecs(remaining_wait_time.InSeconds())
1262 << " per policy.";
1263 return kWallClockWaitNotSatisfied;
1264}
1265
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001266bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001267 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001268
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001269 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1270 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1271 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001272 // We are unable to read the update check count from file for some reason.
1273 // So let's proceed anyway so as to not stall the update.
1274 LOG(ERROR) << "Unable to read update check count. "
1275 << "Skipping update-check-count-based-wait.";
1276 return true;
1277 }
1278 } else {
1279 // This file does not exist. This means we haven't started our update
1280 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001281 update_check_count_value =
1282 base::RandInt(params_->min_update_checks_needed(),
1283 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001284
1285 LOG(INFO) << "Randomly picked update check count value = "
1286 << update_check_count_value;
1287
1288 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001289 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1290 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001291 // We weren't able to write the update check count file for some reason.
1292 // So let's proceed anyway so as to not stall the update.
1293 LOG(ERROR) << "Unable to write update check count. "
1294 << "Skipping update-check-count-based-wait.";
1295 return true;
1296 }
1297 }
1298
1299 if (update_check_count_value == 0) {
1300 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1301 return true;
1302 }
1303
1304 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001305 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001306 // We err on the side of skipping scattering logic instead of stalling
1307 // a machine from receiving any updates in case of any unexpected state.
1308 LOG(ERROR) << "Invalid value for update check count detected. "
1309 << "Skipping update-check-count-based-wait.";
1310 return true;
1311 }
1312
1313 // Legal value, we need to wait for more update checks to happen
1314 // until this becomes 0.
1315 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001316 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001317 return false;
1318}
1319
David Zeuthen639aa362014-02-03 16:23:44 -08001320// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001321bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001322 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001323 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001324 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001325 return false;
1326
1327 if (elapsed_days < 0)
1328 return false;
1329
1330 output_object->install_date_days = elapsed_days;
1331 return true;
1332}
1333
1334// static
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001335bool OmahaRequestAction::HasInstallDate(SystemState* system_state) {
David Zeuthen639aa362014-02-03 16:23:44 -08001336 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001337 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001338 return false;
1339
1340 return prefs->Exists(kPrefsInstallDateDays);
1341}
1342
1343// static
1344bool OmahaRequestAction::PersistInstallDate(
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001345 SystemState* system_state,
David Zeuthen639aa362014-02-03 16:23:44 -08001346 int install_date_days,
1347 InstallDateProvisioningSource source) {
1348 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1349
1350 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001351 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001352 return false;
1353
1354 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1355 return false;
1356
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001357 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001358 static_cast<int>(source), // Sample.
1359 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001360 return true;
1361}
1362
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001363bool OmahaRequestAction::PersistCohortData(const string& prefs_key,
1364 const string& new_value) {
Alex Deymo8e18f932015-03-27 16:16:59 -07001365 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1366 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1367 return system_state_->prefs()->Delete(prefs_key);
1368 } else if (!new_value.empty()) {
1369 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1370 return system_state_->prefs()->SetString(prefs_key, new_value);
1371 }
1372 return true;
1373}
1374
Amin Hassani2cbb0692019-10-30 13:36:17 -07001375bool OmahaRequestAction::PersistEolInfo(const map<string, string>& attrs) {
Jae Hoon Kimb3146742019-11-07 13:24:24 -08001376 // If EOL date attribute is not sent, don't delete the old persisted EOL
1377 // date information.
Jae Hoon Kim051627a2019-09-03 12:56:32 -07001378 auto eol_date_attr = attrs.find(kAttrEolDate);
Jae Hoon Kimb3146742019-11-07 13:24:24 -08001379 if (eol_date_attr != attrs.end() &&
1380 !system_state_->prefs()->SetString(kPrefsOmahaEolDate,
1381 eol_date_attr->second)) {
Jae Hoon Kim051627a2019-09-03 12:56:32 -07001382 LOG(ERROR) << "Setting EOL date failed.";
Amin Hassani2cbb0692019-10-30 13:36:17 -07001383 return false;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001384 }
Amin Hassani2cbb0692019-10-30 13:36:17 -07001385 return true;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001386}
1387
David Zeuthen33bae492014-02-25 16:16:18 -08001388void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1389 // We only want to report this on "update check".
1390 if (ping_only_ || event_ != nullptr)
1391 return;
1392
1393 metrics::CheckResult result = metrics::CheckResult::kUnset;
1394 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1395 metrics::DownloadErrorCode download_error_code =
1396 metrics::DownloadErrorCode::kUnset;
1397
1398 // Regular update attempt.
1399 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001400 case ErrorCode::kSuccess:
1401 // OK, we parsed the response successfully but that does
1402 // necessarily mean that an update is available.
1403 if (HasOutputPipe()) {
1404 const OmahaResponse& response = GetOutputObject();
1405 if (response.update_exists) {
1406 result = metrics::CheckResult::kUpdateAvailable;
1407 reaction = metrics::CheckReaction::kUpdating;
1408 } else {
1409 result = metrics::CheckResult::kNoUpdateAvailable;
1410 }
David Zeuthen33bae492014-02-25 16:16:18 -08001411 } else {
1412 result = metrics::CheckResult::kNoUpdateAvailable;
1413 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001414 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001415
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001416 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1417 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1418 result = metrics::CheckResult::kUpdateAvailable;
1419 reaction = metrics::CheckReaction::kIgnored;
1420 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001421
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001422 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1423 result = metrics::CheckResult::kUpdateAvailable;
1424 reaction = metrics::CheckReaction::kDeferring;
1425 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001426
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001427 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1428 result = metrics::CheckResult::kUpdateAvailable;
1429 reaction = metrics::CheckReaction::kBackingOff;
1430 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001431
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001432 default:
1433 // We report two flavors of errors, "Download errors" and "Parsing
1434 // error". Try to convert to the former and if that doesn't work
1435 // we know it's the latter.
1436 metrics::DownloadErrorCode tmp_error =
1437 metrics_utils::GetDownloadErrorCode(code);
1438 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1439 result = metrics::CheckResult::kDownloadError;
1440 download_error_code = tmp_error;
1441 } else {
1442 result = metrics::CheckResult::kParsingError;
1443 }
1444 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001445 }
1446
Amin Hassanid3d84212019-08-17 00:27:44 -07001447 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1448 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001449}
1450
Toni Barzic61544e62018-10-11 14:37:30 -07001451bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1452 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001453 // Note: policy decision to not update to a version we rolled back from.
1454 string rollback_version =
1455 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001456 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001457 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001458 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001459 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001460 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001461 return true;
1462 }
1463 }
1464
Toni Barzic61544e62018-10-11 14:37:30 -07001465 if (system_state_->hardware()->IsOOBEEnabled() &&
1466 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
1467 (response.deadline.empty() ||
1468 system_state_->payload_state()->GetRollbackHappened()) &&
1469 params_->app_version() != "ForcedUpdate") {
1470 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1471 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1472 return true;
1473 }
1474
Weidong Guo421ff332017-04-17 10:08:38 -07001475 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001476 LOG(INFO) << "Update is not allowed over current connection.";
1477 return true;
1478 }
1479
1480 // Note: We could technically delete the UpdateFirstSeenAt state when we
1481 // return true. If we do, it'll mean a device has to restart the
1482 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1483 // turned on again. On the other hand, it also increases the chance of update
1484 // starvation if an admin turns AU on/off more frequently. We choose to err on
1485 // the side of preventing starvation at the cost of not applying scattering in
1486 // those cases.
1487 return false;
1488}
1489
Weidong Guo421ff332017-04-17 10:08:38 -07001490bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1491 const OmahaResponse& response) const {
1492 PrefsInterface* prefs = system_state_->prefs();
1493
1494 if (!prefs) {
1495 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1496 "not available.";
1497 return false;
1498 }
1499
1500 bool is_allowed;
1501
1502 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1503 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1504 is_allowed) {
1505 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1506 "set to true.";
1507 return true;
1508 }
1509
1510 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1511 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1512 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1513 "set to false or does not exist while target does not exist.";
1514 return false;
1515 }
1516
1517 std::string target_version;
1518 int64_t target_size;
1519
1520 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1521 &target_version) ||
1522 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1523 LOG(INFO) << "Disabling updates over cellular as the target version or "
1524 "size is not accessible.";
1525 return false;
1526 }
1527
1528 uint64_t total_packages_size = 0;
1529 for (const auto& package : response.packages) {
1530 total_packages_size += package.size;
1531 }
1532 if (target_version == response.version &&
1533 static_cast<uint64_t>(target_size) == total_packages_size) {
1534 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1535 "omaha response.";
1536 return true;
1537 } else {
1538 LOG(INFO) << "Disabling updates over cellular as the target does not"
1539 "match the omaha response.";
1540 return false;
1541 }
1542}
1543
1544bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1545 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001546 ConnectionType type;
1547 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001548 ConnectionManagerInterface* connection_manager =
1549 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001550 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001551 LOG(INFO) << "We could not determine our connection type. "
1552 << "Defaulting to allow updates.";
1553 return true;
1554 }
Weidong Guo421ff332017-04-17 10:08:38 -07001555
Chris Sosa77f79e82014-06-02 18:16:24 -07001556 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001557 bool is_device_policy_set =
1558 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1559 // Treats tethered connection as if it is cellular connection.
1560 bool is_over_cellular = type == ConnectionType::kCellular ||
1561 tethering == ConnectionTethering::kConfirmed;
1562
1563 if (!is_over_cellular) {
1564 // There's no need to further check user preferences as we are not over
1565 // cellular connection.
1566 if (!is_allowed)
1567 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1568 } else if (is_device_policy_set) {
1569 // There's no need to further check user preferences as the device policy
1570 // is set regarding updates over cellular.
1571 if (!is_allowed)
1572 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1573 } else {
1574 // Deivce policy is not set, so user preferences overwrite whether to
1575 // allow updates over cellular.
1576 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1577 if (!is_allowed)
1578 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1579 }
1580
Chris Sosa77f79e82014-06-02 18:16:24 -07001581 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001582 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001583 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1584 return is_allowed;
1585}
1586
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001587bool OmahaRequestAction::IsRollbackEnabled() const {
1588 if (policy_provider_->IsConsumerDevice()) {
1589 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1590 return false;
1591 }
1592
1593 if (!policy_provider_->device_policy_is_loaded()) {
1594 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1595 return true;
1596 }
1597
1598 int allowed_milestones;
1599 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1600 &allowed_milestones)) {
1601 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1602 "Defaulting to rollback enabled.";
1603 return true;
1604 }
1605
1606 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1607 return allowed_milestones > 0;
1608}
1609
1610void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001611 int max_kernel_rollforward;
1612 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001613 if (IsRollbackEnabled()) {
1614 // If rollback is enabled, set the max kernel key version to the current
1615 // kernel key version. This has the effect of freezing kernel key roll
1616 // forwards.
1617 //
1618 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1619 // key roll forward happens until the server side components of rollback
1620 // are implemented. Future changes will allow the Omaha server to return
1621 // the kernel key version from max_rollback_versions in the past. At that
1622 // point the max kernel key version will be set to that value, creating a
1623 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001624 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001625 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001626 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001627 } else {
1628 // For devices that are not rollback enabled (ie. consumer devices), the
1629 // max kernel key version is set to 0xfffffffe, which is logically
1630 // infinity. This maintains the previous behavior that that kernel key
1631 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001632 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001633 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001634 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001635 }
1636
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001637 bool max_rollforward_set =
1638 system_state_->hardware()->SetMaxKernelKeyRollforward(
1639 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001640 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001641 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001642 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001643 // Report metrics
1644 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1645 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001646}
1647
May Lippert60aa3ca2018-08-15 16:55:29 -07001648base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1649 Time update_first_seen_at;
1650 int64_t update_first_seen_at_int;
1651 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1652 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1653 &update_first_seen_at_int)) {
1654 // Note: This timestamp could be that of ANY update we saw in the past
1655 // (not necessarily this particular update we're considering to apply)
1656 // but never got to apply because of some reason (e.g. stop AU policy,
1657 // updates being pulled out from Omaha, changes in target version prefix,
1658 // new update being rolled out, etc.). But for the purposes of scattering
1659 // it doesn't matter which update the timestamp corresponds to. i.e.
1660 // the clock starts ticking the first time we see an update and we're
1661 // ready to apply when the random wait period is satisfied relative to
1662 // that first seen timestamp.
1663 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1664 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1665 << utils::ToString(update_first_seen_at);
1666 } else {
1667 // This seems like an unexpected error where the persisted value exists
1668 // but it's not readable for some reason.
1669 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1670 return base::Time();
1671 }
1672 } else {
1673 update_first_seen_at = system_state_->clock()->GetWallclockTime();
1674 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
1675 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1676 update_first_seen_at_int)) {
1677 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1678 << utils::ToString(update_first_seen_at);
1679 } else {
1680 // This seems like an unexpected error where the value cannot be
1681 // persisted for some reason.
1682 LOG(INFO) << "UpdateFirstSeenAt value "
1683 << utils::ToString(update_first_seen_at)
1684 << " cannot be persisted";
1685 return base::Time();
1686 }
1687 }
1688 return update_first_seen_at;
1689}
1690
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001691} // namespace chromeos_update_engine