blob: 5b69ec8727d6421b1eac0d105121d3d282d2beec [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>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070029#include <base/logging.h>
30#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070031#include <base/strings/string_number_conversions.h>
Sen Jiang0affc2c2017-02-10 15:55:05 -080032#include <base/strings/string_split.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070033#include <base/strings/string_util.h>
34#include <base/strings/stringprintf.h>
35#include <base/time/time.h>
Sen Jiang684c9cd2017-10-17 16:26:45 -070036#include <brillo/key_value_store.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040037#include <expat.h>
Alex Deymoa2591792015-11-17 00:39:40 -030038#include <metrics/metrics_library.h>
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080039#include <policy/libpolicy.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000040
Alex Deymo39910dc2015-11-09 17:04:30 -080041#include "update_engine/common/action_pipe.h"
42#include "update_engine/common/constants.h"
43#include "update_engine/common/hardware_interface.h"
44#include "update_engine/common/hash_calculator.h"
45#include "update_engine/common/platform_constants.h"
46#include "update_engine/common/prefs_interface.h"
47#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070048#include "update_engine/connection_manager_interface.h"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070049#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080050#include "update_engine/metrics_utils.h"
Amin Hassani7fca2862019-03-28 16:09:22 -070051#include "update_engine/omaha_request_builder_xml.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070052#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070053#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080054#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000055
Darin Petkov1cbd78f2010-07-29 12:38:34 -070056using base::Time;
57using base::TimeDelta;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080058using chromeos_update_manager::kRollforwardInfinity;
David Zeuthene8ed8632014-07-24 13:38:10 -040059using std::map;
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070060using std::numeric_limits;
rspangler@google.com49fdf182009-10-10 00:57:34 +000061using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040062using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000063
64namespace chromeos_update_engine {
65
Amin Hassani6600a562018-09-24 15:17:19 -070066// List of custom attributes that we interpret in the Omaha response:
67constexpr char kAttrDeadline[] = "deadline";
68constexpr char kAttrDisableP2PForDownloading[] = "DisableP2PForDownloading";
69constexpr char kAttrDisableP2PForSharing[] = "DisableP2PForSharing";
70constexpr char kAttrDisablePayloadBackoff[] = "DisablePayloadBackoff";
71constexpr char kAttrVersion[] = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080072// Deprecated: "IsDelta"
Amin Hassani6600a562018-09-24 15:17:19 -070073constexpr char kAttrIsDeltaPayload[] = "IsDeltaPayload";
74constexpr char kAttrMaxFailureCountPerUrl[] = "MaxFailureCountPerUrl";
75constexpr char kAttrMaxDaysToScatter[] = "MaxDaysToScatter";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080076// Deprecated: "ManifestSignatureRsa"
77// Deprecated: "ManifestSize"
Amin Hassani6600a562018-09-24 15:17:19 -070078constexpr char kAttrMetadataSignatureRsa[] = "MetadataSignatureRsa";
79constexpr char kAttrMetadataSize[] = "MetadataSize";
80constexpr char kAttrMoreInfo[] = "MoreInfo";
81constexpr char kAttrNoUpdate[] = "noupdate";
Don Garrett42bd3aa2013-04-10 18:14:56 -070082// Deprecated: "NeedsAdmin"
Amin Hassani6600a562018-09-24 15:17:19 -070083constexpr char kAttrPollInterval[] = "PollInterval";
84constexpr char kAttrPowerwash[] = "Powerwash";
85constexpr char kAttrPrompt[] = "Prompt";
86constexpr char kAttrPublicKeyRsa[] = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080087
Amin Hassani6600a562018-09-24 15:17:19 -070088// List of attributes that we interpret in the Omaha response:
89constexpr char kAttrAppId[] = "appid";
90constexpr char kAttrCodeBase[] = "codebase";
91constexpr char kAttrCohort[] = "cohort";
92constexpr char kAttrCohortHint[] = "cohorthint";
93constexpr char kAttrCohortName[] = "cohortname";
94constexpr char kAttrElapsedDays[] = "elapsed_days";
95constexpr char kAttrElapsedSeconds[] = "elapsed_seconds";
96constexpr char kAttrEvent[] = "event";
97constexpr char kAttrHashSha256[] = "hash_sha256";
98// Deprecated: "hash"; Although we still need to pass it from the server for
99// backward compatibility.
100constexpr char kAttrName[] = "name";
101// Deprecated: "sha256"; Although we still need to pass it from the server for
102// backward compatibility.
103constexpr char kAttrSize[] = "size";
104constexpr char kAttrStatus[] = "status";
105
106// List of values that we interpret in the Omaha response:
107constexpr char kValPostInstall[] = "postinstall";
108constexpr char kValNoUpdate[] = "noupdate";
109
Sen Jiang42fa45e2018-03-12 11:02:14 -0700110// X-Goog-Update headers.
Amin Hassani6600a562018-09-24 15:17:19 -0700111constexpr char kXGoogleUpdateInteractivity[] = "X-Goog-Update-Interactivity";
112constexpr char kXGoogleUpdateAppId[] = "X-Goog-Update-AppId";
113constexpr char kXGoogleUpdateUpdater[] = "X-Goog-Update-Updater";
Alex Deymo14ad88e2016-06-29 12:30:14 -0700114
Alex Deymob3fa53b2016-04-18 19:57:58 -0700115// updatecheck attributes (without the underscore prefix).
Amin Hassani6600a562018-09-24 15:17:19 -0700116constexpr char kAttrEol[] = "eol";
117constexpr char kAttrRollback[] = "rollback";
118constexpr char kAttrFirmwareVersion[] = "firmware_version";
119constexpr char kAttrKernelVersion[] = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -0700120
David Zeuthene8ed8632014-07-24 13:38:10 -0400121// Struct used for holding data obtained when parsing the XML.
122struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400123 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
124
125 // Pointer to the expat XML_Parser object.
126 XML_Parser xml_parser;
127
David Zeuthene8ed8632014-07-24 13:38:10 -0400128 // This is the state of the parser as it's processing the XML.
129 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400130 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400131 string current_path;
132
133 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400134 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700135 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400136 string daystart_elapsed_days;
137 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800138
Sen Jiang81259682017-03-30 15:11:30 -0700139 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700140 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700141 vector<string> url_codebase;
142 string manifest_version;
143 map<string, string> action_postinstall_attrs;
144 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700145 string cohort;
146 string cohorthint;
147 string cohortname;
148 bool cohort_set = false;
149 bool cohorthint_set = false;
150 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700151
152 struct Package {
153 string name;
154 string size;
155 string hash;
156 };
157 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800158 };
Sen Jiang81259682017-03-30 15:11:30 -0700159 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400160};
161
162namespace {
163
164// Callback function invoked by expat.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800165void ParserHandlerStart(void* user_data,
166 const XML_Char* element,
David Zeuthene8ed8632014-07-24 13:38:10 -0400167 const XML_Char** attr) {
168 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
169
170 if (data->failed)
171 return;
172
173 data->current_path += string("/") + element;
174
175 map<string, string> attrs;
176 if (attr != nullptr) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800177 for (int n = 0; attr[n] != nullptr && attr[n + 1] != nullptr; n += 2) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400178 string key = attr[n];
179 string value = attr[n + 1];
180 attrs[key] = value;
181 }
182 }
183
Alex Deymo8e18f932015-03-27 16:16:59 -0700184 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700185 OmahaParserData::App app;
Amin Hassani6600a562018-09-24 15:17:19 -0700186 if (attrs.find(kAttrAppId) != attrs.end()) {
187 app.id = attrs[kAttrAppId];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700188 }
Amin Hassani6600a562018-09-24 15:17:19 -0700189 if (attrs.find(kAttrCohort) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700190 app.cohort_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700191 app.cohort = attrs[kAttrCohort];
Alex Deymo8e18f932015-03-27 16:16:59 -0700192 }
Amin Hassani6600a562018-09-24 15:17:19 -0700193 if (attrs.find(kAttrCohortHint) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700194 app.cohorthint_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700195 app.cohorthint = attrs[kAttrCohortHint];
Alex Deymo8e18f932015-03-27 16:16:59 -0700196 }
Amin Hassani6600a562018-09-24 15:17:19 -0700197 if (attrs.find(kAttrCohortName) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700198 app.cohortname_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700199 app.cohortname = attrs[kAttrCohortName];
Alex Deymo8e18f932015-03-27 16:16:59 -0700200 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700201 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700202 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700203 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700204 data->apps.back().updatecheck_status = attrs[kAttrStatus];
Sen Jiang81259682017-03-30 15:11:30 -0700205 if (data->updatecheck_poll_interval.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700206 data->updatecheck_poll_interval = attrs[kAttrPollInterval];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700207 // Omaha sends arbitrary key-value pairs as extra attributes starting with
208 // an underscore.
209 for (const auto& attr : attrs) {
210 if (!attr.first.empty() && attr.first[0] == '_')
211 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
212 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400213 } else if (data->current_path == "/response/daystart") {
214 // Get the install-date.
Amin Hassani6600a562018-09-24 15:17:19 -0700215 data->daystart_elapsed_days = attrs[kAttrElapsedDays];
216 data->daystart_elapsed_seconds = attrs[kAttrElapsedSeconds];
David Zeuthene8ed8632014-07-24 13:38:10 -0400217 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
218 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700219 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700220 data->apps.back().url_codebase.push_back(attrs[kAttrCodeBase]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800221 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400222 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800223 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700224 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700225 data->apps.back().packages.push_back({.name = attrs[kAttrName],
226 .size = attrs[kAttrSize],
227 .hash = attrs[kAttrHashSha256]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400228 } else if (data->current_path == "/response/app/updatecheck/manifest") {
229 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700230 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700231 data->apps.back().manifest_version = attrs[kAttrVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400232 } else if (data->current_path ==
233 "/response/app/updatecheck/manifest/actions/action") {
234 // We only care about the postinstall action.
Amin Hassani6600a562018-09-24 15:17:19 -0700235 if (attrs[kAttrEvent] == kValPostInstall && !data->apps.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700236 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400237 }
238 }
239}
240
241// Callback function invoked by expat.
242void ParserHandlerEnd(void* user_data, const XML_Char* element) {
243 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
244 if (data->failed)
245 return;
246
247 const string path_suffix = string("/") + element;
248
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800249 if (!base::EndsWith(
250 data->current_path, path_suffix, base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400251 LOG(ERROR) << "Unexpected end element '" << element
252 << "' with current_path='" << data->current_path << "'";
253 data->failed = true;
254 return;
255 }
256 data->current_path.resize(data->current_path.size() - path_suffix.size());
257}
258
David Zeuthenf3e28012014-08-26 18:23:52 -0400259// Callback function invoked by expat.
260//
261// This is called for entity declarations. Since Omaha is guaranteed
262// to never return any XML with entities our course of action is to
263// just stop parsing. This avoids potential resource exhaustion
264// problems AKA the "billion laughs". CVE-2013-0340.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800265void ParserHandlerEntityDecl(void* user_data,
266 const XML_Char* entity_name,
David Zeuthenf3e28012014-08-26 18:23:52 -0400267 int is_parameter_entity,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800268 const XML_Char* value,
David Zeuthenf3e28012014-08-26 18:23:52 -0400269 int value_length,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800270 const XML_Char* base,
271 const XML_Char* system_id,
272 const XML_Char* public_id,
273 const XML_Char* notation_name) {
David Zeuthenf3e28012014-08-26 18:23:52 -0400274 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
275
276 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
277 data->failed = true;
278 data->entity_decl = true;
279 XML_StopParser(data->xml_parser, false);
280}
281
David Zeuthene8ed8632014-07-24 13:38:10 -0400282} // namespace
283
Alex Deymoc1c17b42015-11-23 03:53:15 -0300284OmahaRequestAction::OmahaRequestAction(
285 SystemState* system_state,
286 OmahaEvent* event,
287 std::unique_ptr<HttpFetcher> http_fetcher,
288 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800289 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800290 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700291 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300292 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800293 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700294 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700295 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700296 ping_roll_call_days_(0) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800297 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700298}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000299
Darin Petkov6a5b3222010-07-13 14:55:28 -0700300OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000301
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700302// Calculates the value to use for the ping days parameter.
303int OmahaRequestAction::CalculatePingDays(const string& key) {
304 int days = kNeverPinged;
305 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800306 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700307 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
308 if (days < 0) {
309 // If |days| is negative, then the system clock must have jumped
310 // back in time since the ping was sent. Mark the value so that
311 // it doesn't get sent to the server but we still update the
312 // last ping daystart preference. This way the next ping time
313 // will be correct, hopefully.
314 days = kPingTimeJump;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800315 LOG(WARNING)
316 << "System clock jumped back in time. Resetting ping daystarts.";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700317 }
318 }
319 return days;
320}
321
322void OmahaRequestAction::InitPingDays() {
323 // We send pings only along with update checks, not with events.
324 if (IsEvent()) {
325 return;
326 }
327 // TODO(petkov): Figure a way to distinguish active use pings
328 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700329 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700330 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
331 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
332}
333
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700334bool OmahaRequestAction::ShouldPing() const {
Amin Hassani7fca2862019-03-28 16:09:22 -0700335 if (ping_active_days_ == kNeverPinged &&
336 ping_roll_call_days_ == kNeverPinged) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700337 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
338 if (powerwash_count > 0) {
339 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
340 << "powerwash_count is " << powerwash_count;
341 return false;
342 }
Amin Hassani1677e812017-06-21 13:36:36 -0700343 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
344 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
345 << "the first_active_omaha_ping_sent is true";
346 return false;
347 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700348 return true;
349 }
350 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
351}
352
David Zeuthen639aa362014-02-03 16:23:44 -0800353// static
354int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
355 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700356 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800357 return -1;
358
359 // If we have the value stored on disk, just return it.
360 int64_t stored_value;
361 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
362 // Convert and sanity-check.
363 int install_date_days = static_cast<int>(stored_value);
364 if (install_date_days >= 0)
365 return install_date_days;
366 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
367 << install_date_days << " looks suspicious.";
368 prefs->Delete(kPrefsInstallDateDays);
369 }
370
371 // Otherwise, if OOBE is not complete then do nothing and wait for
372 // ParseResponse() to call ParseInstallDate() and then
373 // PersistInstallDate() to set the kPrefsInstallDateDays state
374 // variable. Once that is done, we'll then report back in future
375 // Omaha requests. This works exactly because OOBE triggers an
376 // update check.
377 //
378 // However, if OOBE is complete and the kPrefsInstallDateDays state
379 // variable is not set, there are two possibilities
380 //
381 // 1. The update check in OOBE failed so we never got a response
382 // from Omaha (no network etc.); or
383 //
384 // 2. OOBE was done on an older version that didn't write to the
385 // kPrefsInstallDateDays state variable.
386 //
387 // In both cases, we approximate the install date by simply
388 // inspecting the timestamp of when OOBE happened.
389
390 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700391 if (!system_state->hardware()->IsOOBEEnabled() ||
392 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800393 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700394 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800395 return -1;
396 }
397
398 int num_days;
399 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
400 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
401 << "as its value '" << utils::ToString(time_of_oobe)
402 << "' looks suspicious.";
403 return -1;
404 }
405
406 // Persist this to disk, for future use.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800407 if (!OmahaRequestAction::PersistInstallDate(
408 system_state, num_days, kProvisionedFromOOBEMarker))
David Zeuthen639aa362014-02-03 16:23:44 -0800409 return -1;
410
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800411 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to " << num_days
412 << " days";
David Zeuthen639aa362014-02-03 16:23:44 -0800413
414 return num_days;
415}
416
Darin Petkov6a5b3222010-07-13 14:55:28 -0700417void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000418 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700419 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700420 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700421 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700422 return;
423 }
David Zeuthen639aa362014-02-03 16:23:44 -0800424
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700425 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700426 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700427 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700428 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700429 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800430 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800431 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700432 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700433
Sen Jiang42fa45e2018-03-12 11:02:14 -0700434 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700435 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
436 params_->interactive() ? "fg" : "bg");
437 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
438 http_fetcher_->SetHeader(
439 kXGoogleUpdateUpdater,
440 base::StringPrintf(
441 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
442
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800443 http_fetcher_->SetPostData(
444 request_post.data(), request_post.size(), kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700445 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700446 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700447 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000448}
449
Darin Petkov6a5b3222010-07-13 14:55:28 -0700450void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000451 http_fetcher_->TerminateTransfer();
452}
453
454// We just store the response in the buffer. Once we've received all bytes,
455// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700456bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800457 const void* bytes,
458 size_t length) {
459 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
460 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700461 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000462}
463
464namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000465
466// Parses a 64 bit base-10 int from a string and returns it. Returns 0
467// on error. If the string contains "0", that's indistinguishable from
468// error.
469off_t ParseInt(const string& str) {
470 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700471 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000472 if (rc < 1) {
473 // failure
474 return 0;
475 }
476 return ret;
477}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700478
David Zeuthene8ed8632014-07-24 13:38:10 -0400479// Parses |str| and returns |true| if, and only if, its value is "true".
480bool ParseBool(const string& str) {
481 return str == "true";
482}
483
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700484// Update the last ping day preferences based on the server daystart
485// response. Returns true on success, false otherwise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800486bool UpdateLastPingDays(OmahaParserData* parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700487 int64_t elapsed_seconds = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800488 TEST_AND_RETURN_FALSE(base::StringToInt64(
489 parser_data->daystart_elapsed_seconds, &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700490 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
491
492 // Remember the local time that matches the server's last midnight
493 // time.
494 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
495 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
496 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
497 return true;
498}
Sen Jiang81259682017-03-30 15:11:30 -0700499
500// Parses the package node in the given XML document and populates
501// |output_object| if valid. Returns true if we should continue the parsing.
502// False otherwise, in which case it sets any error code using |completer|.
503bool ParsePackage(OmahaParserData::App* app,
504 OmahaResponse* output_object,
505 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700506 if (app->updatecheck_status.empty() ||
507 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700508 if (!app->packages.empty()) {
509 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
510 completer->set_code(ErrorCode::kOmahaResponseInvalid);
511 return false;
512 }
513 return true;
514 }
515 if (app->packages.empty()) {
516 LOG(ERROR) << "Omaha Response has no packages";
517 completer->set_code(ErrorCode::kOmahaResponseInvalid);
518 return false;
519 }
520 if (app->url_codebase.empty()) {
521 LOG(ERROR) << "No Omaha Response URLs";
522 completer->set_code(ErrorCode::kOmahaResponseInvalid);
523 return false;
524 }
525 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
526 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700527 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700528 ":",
529 base::TRIM_WHITESPACE,
530 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700531 vector<string> metadata_signatures = base::SplitString(
532 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
533 ":",
534 base::TRIM_WHITESPACE,
535 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700536 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700537 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700538 ":",
539 base::TRIM_WHITESPACE,
540 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700541 for (size_t i = 0; i < app->packages.size(); i++) {
542 const auto& package = app->packages[i];
543 if (package.name.empty()) {
544 LOG(ERROR) << "Omaha Response has empty package name";
545 completer->set_code(ErrorCode::kOmahaResponseInvalid);
546 return false;
547 }
548 LOG(INFO) << "Found package " << package.name;
549
550 OmahaResponse::Package out_package;
551 for (const string& codebase : app->url_codebase) {
552 if (codebase.empty()) {
553 LOG(ERROR) << "Omaha Response URL has empty codebase";
554 completer->set_code(ErrorCode::kOmahaResponseInvalid);
555 return false;
556 }
557 out_package.payload_urls.push_back(codebase + package.name);
558 }
559 // Parse the payload size.
560 base::StringToUint64(package.size, &out_package.size);
561 if (out_package.size <= 0) {
562 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
563 completer->set_code(ErrorCode::kOmahaResponseInvalid);
564 return false;
565 }
566 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
567
568 if (i < metadata_sizes.size())
569 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
570 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
571 << " bytes";
572
573 if (i < metadata_signatures.size())
574 out_package.metadata_signature = metadata_signatures[i];
575 LOG(INFO) << "Payload metadata signature = "
576 << out_package.metadata_signature;
577
578 out_package.hash = package.hash;
579 if (out_package.hash.empty()) {
580 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
581 completer->set_code(ErrorCode::kOmahaResponseInvalid);
582 return false;
583 }
584 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700585
586 if (i < is_delta_payloads.size())
587 out_package.is_delta = ParseBool(is_delta_payloads[i]);
588 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
589
Sen Jiang81259682017-03-30 15:11:30 -0700590 output_object->packages.push_back(std::move(out_package));
591 }
592
593 return true;
594}
595
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700596// Parses the 2 key version strings kernel_version and firmware_version. If the
597// field is not present, or cannot be parsed the values default to 0xffff.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700598void ParseRollbackVersions(int allowed_milestones,
599 OmahaParserData* parser_data,
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700600 OmahaResponse* output_object) {
601 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700602 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700603 &output_object->rollback_key_version.firmware_key,
604 &output_object->rollback_key_version.firmware);
605 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700606 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700607 &output_object->rollback_key_version.kernel_key,
608 &output_object->rollback_key_version.kernel);
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700609
610 // Create the attribute name strings for milestone N - allowed_milestones.
611 const string firmware_max_rollforward_attr =
612 base::StringPrintf("%s_%i", kAttrFirmwareVersion, allowed_milestones);
613 const string kernel_max_rollforward_attr =
614 base::StringPrintf("%s_%i", kAttrKernelVersion, allowed_milestones);
615
616 const bool max_firmware_and_kernel_exist =
617 parser_data->updatecheck_attrs.count(firmware_max_rollforward_attr) > 0 &&
618 parser_data->updatecheck_attrs.count(kernel_max_rollforward_attr) > 0;
619
620 string firmware_version;
621 string kernel_version;
622 if (max_firmware_and_kernel_exist) {
623 firmware_version =
624 parser_data->updatecheck_attrs[firmware_max_rollforward_attr];
625 kernel_version =
626 parser_data->updatecheck_attrs[kernel_max_rollforward_attr];
627 }
628
629 LOG(INFO) << "For milestone N-" << allowed_milestones
630 << " firmware_key_version=" << firmware_version
631 << " kernel_key_version=" << kernel_version;
632
633 OmahaResponse::RollbackKeyVersion version;
634 utils::ParseRollbackKeyVersion(
635 firmware_version, &version.firmware_key, &version.firmware);
636 utils::ParseRollbackKeyVersion(
637 kernel_version, &version.kernel_key, &version.kernel);
638
639 output_object->past_rollback_key_version = std::move(version);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700640}
641
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700642} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000643
David Zeuthene8ed8632014-07-24 13:38:10 -0400644bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700645 OmahaResponse* output_object,
646 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700647 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700648 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700649 return false;
650 }
Sen Jiang81259682017-03-30 15:11:30 -0700651 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700652
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800653 // chromium-os:37289: The PollInterval is not supported by Omaha server
654 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700655 // slow down the request rate from the server-side. Note that the PollInterval
656 // is not persisted, so it has to be sent by the server on every response to
657 // guarantee that the scheduler uses this value (otherwise, if the device got
658 // rebooted after the last server-indicated value, it'll revert to the default
659 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
660 // based on the assumption that we perform an update check every hour so that
661 // the max value of 8 will roughly be equivalent to one work day. If we decide
662 // to use PollInterval permanently, we should update the
663 // max_update_checks_allowed to take PollInterval into account. Note: The
664 // parsing for PollInterval happens even before parsing of the status because
665 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400666 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700667 &output_object->poll_interval);
668
David Zeuthen639aa362014-02-03 16:23:44 -0800669 // Check for the "elapsed_days" attribute in the "daystart"
670 // element. This is the number of days since Jan 1 2007, 0:00
671 // PST. If we don't have a persisted value of the Omaha InstallDate,
672 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400673 if (ParseInstallDate(parser_data, output_object) &&
674 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800675 // Since output_object->install_date_days is never negative, the
676 // elapsed_days -> install-date calculation is reduced to simply
677 // rounding down to the nearest number divisible by 7.
678 int remainder = output_object->install_date_days % 7;
679 int install_date_days_rounded =
680 output_object->install_date_days - remainder;
681 if (PersistInstallDate(system_state_,
682 install_date_days_rounded,
683 kProvisionedFromOmahaResponse)) {
684 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
685 << install_date_days_rounded << " days";
686 }
687 }
688
Alex Deymo00d79ac2015-06-29 15:41:49 -0700689 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700690 for (const auto& app : parser_data->apps) {
691 if (app.id == params_->GetAppId()) {
692 if (app.cohort_set)
693 PersistCohortData(kPrefsOmahaCohort, app.cohort);
694 if (app.cohorthint_set)
695 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
696 if (app.cohortname_set)
697 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
698 break;
699 }
700 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700701
Alex Deymob3fa53b2016-04-18 19:57:58 -0700702 // Parse the updatecheck attributes.
703 PersistEolStatus(parser_data->updatecheck_attrs);
Marton Hunyady199152d2018-05-07 19:08:48 +0200704 // Rollback-related updatecheck attributes.
705 // Defaults to false if attribute is not present.
706 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -0700707 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700708
709 // Parses the rollback versions of the current image. If the fields do not
710 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700711 ParseRollbackVersions(
712 params_->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -0700713
David Zeuthene8ed8632014-07-24 13:38:10 -0400714 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700715 return false;
716
David Zeuthene8ed8632014-07-24 13:38:10 -0400717 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700718 return false;
719
Sen Jiang0affc2c2017-02-10 15:55:05 -0800720 // Package has to be parsed after Params now because ParseParams need to make
721 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -0700722 for (auto& app : parser_data->apps)
723 if (!ParsePackage(&app, output_object, completer))
724 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800725
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700726 return true;
727}
728
David Zeuthene8ed8632014-07-24 13:38:10 -0400729bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700730 OmahaResponse* output_object,
731 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700732 output_object->update_exists = false;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700733 for (const auto& app : parser_data->apps) {
734 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -0700735 if (status == kValNoUpdate) {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700736 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -0700737 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700738 output_object->update_exists = false;
739 break;
Sen Jiang81259682017-03-30 15:11:30 -0700740 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700741 auto const& attr_no_update =
742 app.action_postinstall_attrs.find(kAttrNoUpdate);
743 if (attr_no_update != app.action_postinstall_attrs.end() &&
744 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700745 // noupdate="true" in postinstall attributes means it's an update to
746 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -0700747 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700748 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700749 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700750 output_object->update_exists = true;
751 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700752 } else if (status.empty() && params_->is_install() &&
753 params_->GetAppId() == app.id) {
754 // Skips the platform app for install operation.
755 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -0700756 } else {
757 LOG(ERROR) << "Unknown Omaha response status: " << status;
758 completer->set_code(ErrorCode::kOmahaResponseInvalid);
759 return false;
760 }
761 }
762 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700763 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700764 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700765 }
766
Sen Jiang81259682017-03-30 15:11:30 -0700767 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700768}
769
David Zeuthene8ed8632014-07-24 13:38:10 -0400770bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700771 OmahaResponse* output_object,
772 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700773 map<string, string> attrs;
774 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700775 if (app.id == params_->GetAppId()) {
776 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -0700777 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700778 } else if (!params_->system_app_id().empty() &&
779 app.id == params_->system_app_id()) {
780 // this is the system app (this check is intentionally skipped if there is
781 // no system_app_id set)
782 output_object->system_version = app.manifest_version;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700783 } else if (params_->is_install() &&
784 app.manifest_version != params_->app_version()) {
785 LOG(WARNING) << "An app has a different version (" << app.manifest_version
786 << ") that is different than platform app version ("
787 << params_->app_version() << ")";
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700788 }
789 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700790 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700791 }
Sen Jiang81259682017-03-30 15:11:30 -0700792 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700793 if (params_->is_install()) {
794 LOG(INFO) << "Use request version for Install operation.";
795 output_object->version = params_->app_version();
796 }
Chris Sosa3b748432013-06-20 16:42:59 -0700797 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700798 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700799 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700800 return false;
801 }
802
803 LOG(INFO) << "Received omaha response to update to version "
804 << output_object->version;
805
David Zeuthene8ed8632014-07-24 13:38:10 -0400806 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700807 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700808 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700809 return false;
810 }
811
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800812 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -0700813 output_object->more_info_url = attrs[kAttrMoreInfo];
814 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
815 output_object->deadline = attrs[kAttrDeadline];
816 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700817 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -0700818 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700819 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -0700820 ParseBool(attrs[kAttrDisableP2PForSharing]);
821 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800822
Amin Hassani6600a562018-09-24 15:17:19 -0700823 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800824 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800825 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700826
Jay Srinivasan08262882012-12-28 19:29:43 -0800827 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -0700828 ParseBool(attrs[kAttrDisablePayloadBackoff]);
829 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800830
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700831 return true;
832}
833
David Zeuthene8ed8632014-07-24 13:38:10 -0400834// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000835// and fill in the appropriate fields of the output object. Also, notifies
836// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800837void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -0700838 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000839 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800840 string current_response(response_buffer_.begin(), response_buffer_.end());
841 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700842
Gilad Arnold74b5f552014-10-07 08:17:16 -0700843 PayloadStateInterface* const payload_state = system_state_->payload_state();
844
Zentaro Kavanagh76af2662018-05-15 10:54:53 -0700845 // Set the max kernel key version based on whether rollback is allowed.
846 SetMaxKernelKeyVersionForRollback();
847
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700848 // Events are best effort transactions -- assume they always succeed.
849 if (IsEvent()) {
850 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700851 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700852 return;
853 }
854
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700855 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700856 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700857 int code = GetHTTPResponseCode();
858 // Makes sure we send sane error values.
859 if (code < 0 || code >= 1000) {
860 code = 999;
861 }
David Zeuthena99981f2013-04-29 13:42:47 -0700862 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700863 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000864 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700865 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000866
David Zeuthene8ed8632014-07-24 13:38:10 -0400867 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400868 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400869 XML_SetUserData(parser, &parser_data);
870 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400871 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800872 XML_Status res =
873 XML_Parse(parser,
874 reinterpret_cast<const char*>(response_buffer_.data()),
875 response_buffer_.size(),
876 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400877
878 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700879 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800880 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
881 << XML_GetCurrentLineNumber(parser) << " col "
882 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -0700883 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400884 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
885 if (response_buffer_.empty()) {
886 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
887 } else if (parser_data.entity_decl) {
888 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
889 }
890 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000891 return;
892 }
Amin Hassani91f48b42018-08-06 17:47:14 -0700893 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000894
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700895 // Update the last ping day preferences based on the server daystart response
896 // even if we didn't send a ping. Omaha always includes the daystart in the
897 // response, but log the error if it didn't.
898 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
899 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700900
Amin Hassani1677e812017-06-21 13:36:36 -0700901 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
902 // we have got a response from omaha and if its value has never been set to
903 // true before. Failure of this function should be ignored. There should be no
904 // need to check if a=-1 has been sent because older devices have already sent
905 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
906 // future checks.
907 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700908 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
909 system_state_->metrics_reporter()->ReportInternalErrorCode(
910 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
911 }
Amin Hassani1677e812017-06-21 13:36:36 -0700912 }
913
Thieu Le116fda32011-04-19 11:01:54 -0700914 if (!HasOutputPipe()) {
915 // Just set success to whether or not the http transfer succeeded,
916 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700917 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700918 return;
919 }
920
Darin Petkov6a5b3222010-07-13 14:55:28 -0700921 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400922 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000923 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700924 output_object.update_exists = true;
925 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000926
Toni Barzic61544e62018-10-11 14:37:30 -0700927 LoadOrPersistUpdateFirstSeenAtPref();
928
Weidong Guo421ff332017-04-17 10:08:38 -0700929 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -0700930 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -0700931 // No need to change output_object.update_exists here, since the value
932 // has been output to the pipe.
933 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700934 return;
935 }
936
David Zeuthen8f191b22013-08-06 12:27:50 -0700937 // If Omaha says to disable p2p, respect that
938 if (output_object.disable_p2p_for_downloading) {
939 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
940 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700941 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700942 }
943 if (output_object.disable_p2p_for_sharing) {
944 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
945 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700946 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700947 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800948
949 // Update the payload state with the current response. The payload state
950 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800951 // from what's stored already. We are updating the payload state as late
952 // as possible in this method so that if a new release gets pushed and then
953 // got pulled back due to some issues, we don't want to clear our internal
954 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800955 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800956
David Zeuthen8f191b22013-08-06 12:27:50 -0700957 // It could be we've already exceeded the deadline for when p2p is
958 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700959 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700960 payload_state->P2PNewAttempt();
961 if (!payload_state->P2PAttemptAllowed()) {
962 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
963 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700964 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700965 }
966 }
967
968 // From here on, we'll complete stuff in CompleteProcessing() so
969 // disable |completer| since we'll create a new one in that
970 // function.
971 completer.set_should_complete(false);
972
973 // If we're allowed to use p2p for downloading we do not pay
974 // attention to wall-clock-based waiting if the URL is indeed
975 // available via p2p. Therefore, check if the file is available via
976 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -0700977 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700978 LookupPayloadViaP2P(output_object);
979 } else {
980 CompleteProcessing();
981 }
982}
983
984void OmahaRequestAction::CompleteProcessing() {
985 ScopedActionCompleter completer(processor_, this);
986 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
987 PayloadStateInterface* payload_state = system_state_->payload_state();
988
989 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -0800990 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -0700991 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700992 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -0800993 return;
994 }
David Zeuthen8f191b22013-08-06 12:27:50 -0700995
Chris Sosa20f005c2013-09-05 13:53:08 -0700996 if (payload_state->ShouldBackoffDownload()) {
997 output_object.update_exists = false;
998 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
999 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001000 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001001 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001002 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001003 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001004}
1005
1006void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1007 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1008 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001009 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001010 } else {
1011 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1012 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001013 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001014 }
1015 CompleteProcessing();
1016}
1017
1018void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001019 // If the device is in the middle of an update, the state variables
1020 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1021 // tracks the offset and length of the operation currently in
1022 // progress. The offset is based from the end of the manifest which
1023 // is kPrefsManifestMetadataSize bytes long.
1024 //
1025 // To make forward progress and avoid deadlocks, we need to find a
1026 // peer that has at least the entire operation we're currently
1027 // working on. Otherwise we may end up in a situation where two
1028 // devices bounce back and forth downloading from each other,
1029 // neither making any forward progress until one of them decides to
1030 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1031 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001032 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001033 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001034 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001035 int64_t next_data_offset = 0;
1036 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001037 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001038 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1039 &manifest_metadata_size) &&
1040 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001041 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1042 &manifest_signature_size) &&
1043 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001044 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001045 &next_data_offset) &&
1046 next_data_offset != -1 &&
1047 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1048 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001049 minimum_size = manifest_metadata_size + manifest_signature_size +
1050 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001051 }
1052
Sen Jiang0affc2c2017-02-10 15:55:05 -08001053 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001054 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001055 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001056 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001057 string file_id =
1058 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001059 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001060 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1061 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001062 system_state_->p2p_manager()->LookupUrlForFile(
1063 file_id,
1064 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001065 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001066 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1067 base::Unretained(this)));
1068 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001069}
1070
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001071bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001072 if (params_->interactive()) {
1073 LOG(INFO) << "Not deferring download because update is interactive.";
1074 return false;
1075 }
1076
David Zeuthen8f191b22013-08-06 12:27:50 -07001077 // If we're using p2p to download _and_ we have a p2p URL, we never
1078 // defer the download. This is because the download will always
1079 // happen from a peer on the LAN and we've been waiting in line for
1080 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001081 const PayloadStateInterface* payload_state = system_state_->payload_state();
1082 if (payload_state->GetUsingP2PForDownloading() &&
1083 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001084 LOG(INFO) << "Download not deferred because download "
1085 << "will happen from a local peer (via p2p).";
1086 return false;
1087 }
1088
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001089 // We should defer the downloads only if we've first satisfied the
1090 // wall-clock-based-waiting period and then the update-check-based waiting
1091 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001092 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001093 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1094 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001095 return false;
1096 }
1097
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001098 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001099 case kWallClockWaitNotSatisfied:
1100 // We haven't even satisfied the first condition, passing the
1101 // wall-clock-based waiting period, so we should defer the downloads
1102 // until that happens.
1103 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1104 return true;
1105
1106 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1107 LOG(INFO) << "wall-clock-based-wait satisfied and "
1108 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001109 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001110
1111 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1112 // Wall-clock-based waiting period is satisfied, and it's determined
1113 // that we do not need the update-check-based wait. so no need to
1114 // defer downloads.
1115 LOG(INFO) << "wall-clock-based-wait satisfied and "
1116 << "update-check-based-wait is not required.";
1117 return false;
1118
1119 default:
1120 // Returning false for this default case so we err on the
1121 // side of downloading updates than deferring in case of any bugs.
1122 NOTREACHED();
1123 return false;
1124 }
1125}
1126
1127OmahaRequestAction::WallClockWaitResult
1128OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001129 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001130 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1131 if (update_first_seen_at == base::Time()) {
1132 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
1133 "persisted";
1134 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001135 }
1136
Sen Jiang7c1171e2016-06-23 11:35:40 -07001137 TimeDelta elapsed_time =
1138 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1139 TimeDelta max_scatter_period =
1140 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001141 int64_t staging_wait_time_in_days = 0;
1142 // Use staging and its default max value if staging is on.
1143 if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1144 &staging_wait_time_in_days) &&
1145 staging_wait_time_in_days > 0)
1146 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001147
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001148 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001149 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001150 << ", Time Elapsed = "
1151 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001152 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001153
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001154 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001155 // The deadline is set for all rules which serve a delta update from a
1156 // previous FSI, which means this update will be applied mostly in OOBE
1157 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1158 // quickly.
1159 LOG(INFO) << "Not scattering as deadline flag is set";
1160 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1161 }
1162
1163 if (max_scatter_period.InDays() == 0) {
1164 // This means the Omaha rule creator decides that this rule
1165 // should not be scattered irrespective of the policy.
1166 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1167 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1168 }
1169
1170 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001171 // This means we've waited more than the upperbound wait in the rule
1172 // from the time we first saw a valid update available to us.
1173 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001174 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1175 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1176 }
1177
1178 // This means we are required to participate in scattering.
1179 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001180 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001181 if (remaining_wait_time.InSeconds() <= 0) {
1182 // Yes, it's our turn now.
1183 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1184
1185 // But we can't download until the update-check-count-based wait is also
1186 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001187 return params_->update_check_count_wait_enabled()
1188 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1189 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001190 }
1191
1192 // Not our turn yet, so we have to wait until our turn to
1193 // help scatter the downloads across all clients of the enterprise.
1194 LOG(INFO) << "Update deferred for another "
1195 << utils::FormatSecs(remaining_wait_time.InSeconds())
1196 << " per policy.";
1197 return kWallClockWaitNotSatisfied;
1198}
1199
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001200bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001201 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001202
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001203 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1204 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1205 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001206 // We are unable to read the update check count from file for some reason.
1207 // So let's proceed anyway so as to not stall the update.
1208 LOG(ERROR) << "Unable to read update check count. "
1209 << "Skipping update-check-count-based-wait.";
1210 return true;
1211 }
1212 } else {
1213 // This file does not exist. This means we haven't started our update
1214 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001215 update_check_count_value =
1216 base::RandInt(params_->min_update_checks_needed(),
1217 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001218
1219 LOG(INFO) << "Randomly picked update check count value = "
1220 << update_check_count_value;
1221
1222 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001223 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1224 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001225 // We weren't able to write the update check count file for some reason.
1226 // So let's proceed anyway so as to not stall the update.
1227 LOG(ERROR) << "Unable to write update check count. "
1228 << "Skipping update-check-count-based-wait.";
1229 return true;
1230 }
1231 }
1232
1233 if (update_check_count_value == 0) {
1234 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1235 return true;
1236 }
1237
1238 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001239 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001240 // We err on the side of skipping scattering logic instead of stalling
1241 // a machine from receiving any updates in case of any unexpected state.
1242 LOG(ERROR) << "Invalid value for update check count detected. "
1243 << "Skipping update-check-count-based-wait.";
1244 return true;
1245 }
1246
1247 // Legal value, we need to wait for more update checks to happen
1248 // until this becomes 0.
1249 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001250 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001251 return false;
1252}
1253
David Zeuthen639aa362014-02-03 16:23:44 -08001254// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001255bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001256 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001257 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001258 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001259 return false;
1260
1261 if (elapsed_days < 0)
1262 return false;
1263
1264 output_object->install_date_days = elapsed_days;
1265 return true;
1266}
1267
1268// static
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001269bool OmahaRequestAction::HasInstallDate(SystemState* system_state) {
David Zeuthen639aa362014-02-03 16:23:44 -08001270 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001271 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001272 return false;
1273
1274 return prefs->Exists(kPrefsInstallDateDays);
1275}
1276
1277// static
1278bool OmahaRequestAction::PersistInstallDate(
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001279 SystemState* system_state,
David Zeuthen639aa362014-02-03 16:23:44 -08001280 int install_date_days,
1281 InstallDateProvisioningSource source) {
1282 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1283
1284 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001285 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001286 return false;
1287
1288 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1289 return false;
1290
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001291 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001292 static_cast<int>(source), // Sample.
1293 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001294 return true;
1295}
1296
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001297bool OmahaRequestAction::PersistCohortData(const string& prefs_key,
1298 const string& new_value) {
Alex Deymo8e18f932015-03-27 16:16:59 -07001299 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1300 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1301 return system_state_->prefs()->Delete(prefs_key);
1302 } else if (!new_value.empty()) {
1303 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1304 return system_state_->prefs()->SetString(prefs_key, new_value);
1305 }
1306 return true;
1307}
1308
Alex Deymob3fa53b2016-04-18 19:57:58 -07001309bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
Amin Hassani6600a562018-09-24 15:17:19 -07001310 auto eol_attr = attrs.find(kAttrEol);
Alex Deymob3fa53b2016-04-18 19:57:58 -07001311 if (eol_attr != attrs.end()) {
1312 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1313 eol_attr->second);
1314 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1315 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1316 }
1317 return true;
1318}
1319
David Zeuthen33bae492014-02-25 16:16:18 -08001320void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1321 // We only want to report this on "update check".
1322 if (ping_only_ || event_ != nullptr)
1323 return;
1324
1325 metrics::CheckResult result = metrics::CheckResult::kUnset;
1326 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1327 metrics::DownloadErrorCode download_error_code =
1328 metrics::DownloadErrorCode::kUnset;
1329
1330 // Regular update attempt.
1331 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001332 case ErrorCode::kSuccess:
1333 // OK, we parsed the response successfully but that does
1334 // necessarily mean that an update is available.
1335 if (HasOutputPipe()) {
1336 const OmahaResponse& response = GetOutputObject();
1337 if (response.update_exists) {
1338 result = metrics::CheckResult::kUpdateAvailable;
1339 reaction = metrics::CheckReaction::kUpdating;
1340 } else {
1341 result = metrics::CheckResult::kNoUpdateAvailable;
1342 }
David Zeuthen33bae492014-02-25 16:16:18 -08001343 } else {
1344 result = metrics::CheckResult::kNoUpdateAvailable;
1345 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001346 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001347
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001348 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1349 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1350 result = metrics::CheckResult::kUpdateAvailable;
1351 reaction = metrics::CheckReaction::kIgnored;
1352 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001353
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001354 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1355 result = metrics::CheckResult::kUpdateAvailable;
1356 reaction = metrics::CheckReaction::kDeferring;
1357 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001358
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001359 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1360 result = metrics::CheckResult::kUpdateAvailable;
1361 reaction = metrics::CheckReaction::kBackingOff;
1362 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001363
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001364 default:
1365 // We report two flavors of errors, "Download errors" and "Parsing
1366 // error". Try to convert to the former and if that doesn't work
1367 // we know it's the latter.
1368 metrics::DownloadErrorCode tmp_error =
1369 metrics_utils::GetDownloadErrorCode(code);
1370 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1371 result = metrics::CheckResult::kDownloadError;
1372 download_error_code = tmp_error;
1373 } else {
1374 result = metrics::CheckResult::kParsingError;
1375 }
1376 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001377 }
1378
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001379 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1380 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001381}
1382
Toni Barzic61544e62018-10-11 14:37:30 -07001383bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1384 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001385 // Note: policy decision to not update to a version we rolled back from.
1386 string rollback_version =
1387 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001388 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001389 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001390 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001391 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001392 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001393 return true;
1394 }
1395 }
1396
Toni Barzic61544e62018-10-11 14:37:30 -07001397 if (system_state_->hardware()->IsOOBEEnabled() &&
1398 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
1399 (response.deadline.empty() ||
1400 system_state_->payload_state()->GetRollbackHappened()) &&
1401 params_->app_version() != "ForcedUpdate") {
1402 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1403 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1404 return true;
1405 }
1406
Weidong Guo421ff332017-04-17 10:08:38 -07001407 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001408 LOG(INFO) << "Update is not allowed over current connection.";
1409 return true;
1410 }
1411
1412 // Note: We could technically delete the UpdateFirstSeenAt state when we
1413 // return true. If we do, it'll mean a device has to restart the
1414 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1415 // turned on again. On the other hand, it also increases the chance of update
1416 // starvation if an admin turns AU on/off more frequently. We choose to err on
1417 // the side of preventing starvation at the cost of not applying scattering in
1418 // those cases.
1419 return false;
1420}
1421
Weidong Guo421ff332017-04-17 10:08:38 -07001422bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1423 const OmahaResponse& response) const {
1424 PrefsInterface* prefs = system_state_->prefs();
1425
1426 if (!prefs) {
1427 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1428 "not available.";
1429 return false;
1430 }
1431
1432 bool is_allowed;
1433
1434 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1435 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1436 is_allowed) {
1437 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1438 "set to true.";
1439 return true;
1440 }
1441
1442 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1443 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1444 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1445 "set to false or does not exist while target does not exist.";
1446 return false;
1447 }
1448
1449 std::string target_version;
1450 int64_t target_size;
1451
1452 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1453 &target_version) ||
1454 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1455 LOG(INFO) << "Disabling updates over cellular as the target version or "
1456 "size is not accessible.";
1457 return false;
1458 }
1459
1460 uint64_t total_packages_size = 0;
1461 for (const auto& package : response.packages) {
1462 total_packages_size += package.size;
1463 }
1464 if (target_version == response.version &&
1465 static_cast<uint64_t>(target_size) == total_packages_size) {
1466 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1467 "omaha response.";
1468 return true;
1469 } else {
1470 LOG(INFO) << "Disabling updates over cellular as the target does not"
1471 "match the omaha response.";
1472 return false;
1473 }
1474}
1475
1476bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1477 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001478 ConnectionType type;
1479 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001480 ConnectionManagerInterface* connection_manager =
1481 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001482 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001483 LOG(INFO) << "We could not determine our connection type. "
1484 << "Defaulting to allow updates.";
1485 return true;
1486 }
Weidong Guo421ff332017-04-17 10:08:38 -07001487
Chris Sosa77f79e82014-06-02 18:16:24 -07001488 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001489 bool is_device_policy_set =
1490 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1491 // Treats tethered connection as if it is cellular connection.
1492 bool is_over_cellular = type == ConnectionType::kCellular ||
1493 tethering == ConnectionTethering::kConfirmed;
1494
1495 if (!is_over_cellular) {
1496 // There's no need to further check user preferences as we are not over
1497 // cellular connection.
1498 if (!is_allowed)
1499 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1500 } else if (is_device_policy_set) {
1501 // There's no need to further check user preferences as the device policy
1502 // is set regarding updates over cellular.
1503 if (!is_allowed)
1504 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1505 } else {
1506 // Deivce policy is not set, so user preferences overwrite whether to
1507 // allow updates over cellular.
1508 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1509 if (!is_allowed)
1510 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1511 }
1512
Chris Sosa77f79e82014-06-02 18:16:24 -07001513 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001514 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001515 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1516 return is_allowed;
1517}
1518
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001519bool OmahaRequestAction::IsRollbackEnabled() const {
1520 if (policy_provider_->IsConsumerDevice()) {
1521 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1522 return false;
1523 }
1524
1525 if (!policy_provider_->device_policy_is_loaded()) {
1526 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1527 return true;
1528 }
1529
1530 int allowed_milestones;
1531 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1532 &allowed_milestones)) {
1533 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1534 "Defaulting to rollback enabled.";
1535 return true;
1536 }
1537
1538 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1539 return allowed_milestones > 0;
1540}
1541
1542void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001543 int max_kernel_rollforward;
1544 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001545 if (IsRollbackEnabled()) {
1546 // If rollback is enabled, set the max kernel key version to the current
1547 // kernel key version. This has the effect of freezing kernel key roll
1548 // forwards.
1549 //
1550 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1551 // key roll forward happens until the server side components of rollback
1552 // are implemented. Future changes will allow the Omaha server to return
1553 // the kernel key version from max_rollback_versions in the past. At that
1554 // point the max kernel key version will be set to that value, creating a
1555 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001556 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001557 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001558 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001559 } else {
1560 // For devices that are not rollback enabled (ie. consumer devices), the
1561 // max kernel key version is set to 0xfffffffe, which is logically
1562 // infinity. This maintains the previous behavior that that kernel key
1563 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001564 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001565 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001566 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001567 }
1568
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001569 bool max_rollforward_set =
1570 system_state_->hardware()->SetMaxKernelKeyRollforward(
1571 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001572 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001573 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001574 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001575 // Report metrics
1576 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1577 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001578}
1579
May Lippert60aa3ca2018-08-15 16:55:29 -07001580base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1581 Time update_first_seen_at;
1582 int64_t update_first_seen_at_int;
1583 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1584 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1585 &update_first_seen_at_int)) {
1586 // Note: This timestamp could be that of ANY update we saw in the past
1587 // (not necessarily this particular update we're considering to apply)
1588 // but never got to apply because of some reason (e.g. stop AU policy,
1589 // updates being pulled out from Omaha, changes in target version prefix,
1590 // new update being rolled out, etc.). But for the purposes of scattering
1591 // it doesn't matter which update the timestamp corresponds to. i.e.
1592 // the clock starts ticking the first time we see an update and we're
1593 // ready to apply when the random wait period is satisfied relative to
1594 // that first seen timestamp.
1595 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1596 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1597 << utils::ToString(update_first_seen_at);
1598 } else {
1599 // This seems like an unexpected error where the persisted value exists
1600 // but it's not readable for some reason.
1601 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1602 return base::Time();
1603 }
1604 } else {
1605 update_first_seen_at = system_state_->clock()->GetWallclockTime();
1606 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
1607 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1608 update_first_seen_at_int)) {
1609 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1610 << utils::ToString(update_first_seen_at);
1611 } else {
1612 // This seems like an unexpected error where the value cannot be
1613 // persisted for some reason.
1614 LOG(INFO) << "UpdateFirstSeenAt value "
1615 << utils::ToString(update_first_seen_at)
1616 << " cannot be persisted";
1617 return base::Time();
1618 }
1619 }
1620 return update_first_seen_at;
1621}
1622
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001623} // namespace chromeos_update_engine