blob: 58e7f4700939bf769652068ca899b58b0817276f [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;
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070062using std::numeric_limits;
rspangler@google.com49fdf182009-10-10 00:57:34 +000063using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040064using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000065
66namespace chromeos_update_engine {
67
Amin Hassani6600a562018-09-24 15:17:19 -070068// List of custom attributes that we interpret in the Omaha response:
69constexpr char kAttrDeadline[] = "deadline";
70constexpr char kAttrDisableP2PForDownloading[] = "DisableP2PForDownloading";
71constexpr char kAttrDisableP2PForSharing[] = "DisableP2PForSharing";
72constexpr char kAttrDisablePayloadBackoff[] = "DisablePayloadBackoff";
73constexpr char kAttrVersion[] = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080074// Deprecated: "IsDelta"
Amin Hassani6600a562018-09-24 15:17:19 -070075constexpr char kAttrIsDeltaPayload[] = "IsDeltaPayload";
76constexpr char kAttrMaxFailureCountPerUrl[] = "MaxFailureCountPerUrl";
77constexpr char kAttrMaxDaysToScatter[] = "MaxDaysToScatter";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080078// Deprecated: "ManifestSignatureRsa"
79// Deprecated: "ManifestSize"
Amin Hassani6600a562018-09-24 15:17:19 -070080constexpr char kAttrMetadataSignatureRsa[] = "MetadataSignatureRsa";
81constexpr char kAttrMetadataSize[] = "MetadataSize";
82constexpr char kAttrMoreInfo[] = "MoreInfo";
83constexpr char kAttrNoUpdate[] = "noupdate";
Don Garrett42bd3aa2013-04-10 18:14:56 -070084// Deprecated: "NeedsAdmin"
Amin Hassani6600a562018-09-24 15:17:19 -070085constexpr char kAttrPollInterval[] = "PollInterval";
86constexpr char kAttrPowerwash[] = "Powerwash";
87constexpr char kAttrPrompt[] = "Prompt";
88constexpr char kAttrPublicKeyRsa[] = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080089
Amin Hassani6600a562018-09-24 15:17:19 -070090// List of attributes that we interpret in the Omaha response:
91constexpr char kAttrAppId[] = "appid";
92constexpr char kAttrCodeBase[] = "codebase";
93constexpr char kAttrCohort[] = "cohort";
94constexpr char kAttrCohortHint[] = "cohorthint";
95constexpr char kAttrCohortName[] = "cohortname";
96constexpr char kAttrElapsedDays[] = "elapsed_days";
97constexpr char kAttrElapsedSeconds[] = "elapsed_seconds";
98constexpr char kAttrEvent[] = "event";
99constexpr char kAttrHashSha256[] = "hash_sha256";
100// Deprecated: "hash"; Although we still need to pass it from the server for
101// backward compatibility.
102constexpr char kAttrName[] = "name";
103// Deprecated: "sha256"; Although we still need to pass it from the server for
104// backward compatibility.
105constexpr char kAttrSize[] = "size";
106constexpr char kAttrStatus[] = "status";
107
108// List of values that we interpret in the Omaha response:
109constexpr char kValPostInstall[] = "postinstall";
110constexpr char kValNoUpdate[] = "noupdate";
111
Alex Deymob3fa53b2016-04-18 19:57:58 -0700112// updatecheck attributes (without the underscore prefix).
Amin Hassani2cbb0692019-10-30 13:36:17 -0700113// Deprecated: "eol"
Jae Hoon Kim051627a2019-09-03 12:56:32 -0700114constexpr char kAttrEolDate[] = "eol_date";
Amin Hassani6600a562018-09-24 15:17:19 -0700115constexpr char kAttrRollback[] = "rollback";
116constexpr char kAttrFirmwareVersion[] = "firmware_version";
117constexpr char kAttrKernelVersion[] = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -0700118
David Zeuthene8ed8632014-07-24 13:38:10 -0400119// Struct used for holding data obtained when parsing the XML.
120struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400121 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
122
123 // Pointer to the expat XML_Parser object.
124 XML_Parser xml_parser;
125
David Zeuthene8ed8632014-07-24 13:38:10 -0400126 // This is the state of the parser as it's processing the XML.
127 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400128 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400129 string current_path;
130
131 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400132 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700133 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400134 string daystart_elapsed_days;
135 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800136
Sen Jiang81259682017-03-30 15:11:30 -0700137 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700138 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700139 vector<string> url_codebase;
140 string manifest_version;
141 map<string, string> action_postinstall_attrs;
142 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700143 string cohort;
144 string cohorthint;
145 string cohortname;
146 bool cohort_set = false;
147 bool cohorthint_set = false;
148 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700149
150 struct Package {
151 string name;
152 string size;
153 string hash;
154 };
155 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800156 };
Sen Jiang81259682017-03-30 15:11:30 -0700157 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400158};
159
160namespace {
161
162// Callback function invoked by expat.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800163void ParserHandlerStart(void* user_data,
164 const XML_Char* element,
David Zeuthene8ed8632014-07-24 13:38:10 -0400165 const XML_Char** attr) {
166 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
167
168 if (data->failed)
169 return;
170
171 data->current_path += string("/") + element;
172
173 map<string, string> attrs;
174 if (attr != nullptr) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800175 for (int n = 0; attr[n] != nullptr && attr[n + 1] != nullptr; n += 2) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400176 string key = attr[n];
177 string value = attr[n + 1];
178 attrs[key] = value;
179 }
180 }
181
Alex Deymo8e18f932015-03-27 16:16:59 -0700182 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700183 OmahaParserData::App app;
Amin Hassani6600a562018-09-24 15:17:19 -0700184 if (attrs.find(kAttrAppId) != attrs.end()) {
185 app.id = attrs[kAttrAppId];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700186 }
Amin Hassani6600a562018-09-24 15:17:19 -0700187 if (attrs.find(kAttrCohort) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700188 app.cohort_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700189 app.cohort = attrs[kAttrCohort];
Alex Deymo8e18f932015-03-27 16:16:59 -0700190 }
Amin Hassani6600a562018-09-24 15:17:19 -0700191 if (attrs.find(kAttrCohortHint) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700192 app.cohorthint_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700193 app.cohorthint = attrs[kAttrCohortHint];
Alex Deymo8e18f932015-03-27 16:16:59 -0700194 }
Amin Hassani6600a562018-09-24 15:17:19 -0700195 if (attrs.find(kAttrCohortName) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700196 app.cohortname_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700197 app.cohortname = attrs[kAttrCohortName];
Alex Deymo8e18f932015-03-27 16:16:59 -0700198 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700199 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700200 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700201 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700202 data->apps.back().updatecheck_status = attrs[kAttrStatus];
Sen Jiang81259682017-03-30 15:11:30 -0700203 if (data->updatecheck_poll_interval.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700204 data->updatecheck_poll_interval = attrs[kAttrPollInterval];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700205 // Omaha sends arbitrary key-value pairs as extra attributes starting with
206 // an underscore.
207 for (const auto& attr : attrs) {
208 if (!attr.first.empty() && attr.first[0] == '_')
209 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
210 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400211 } else if (data->current_path == "/response/daystart") {
212 // Get the install-date.
Amin Hassani6600a562018-09-24 15:17:19 -0700213 data->daystart_elapsed_days = attrs[kAttrElapsedDays];
214 data->daystart_elapsed_seconds = attrs[kAttrElapsedSeconds];
David Zeuthene8ed8632014-07-24 13:38:10 -0400215 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
216 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700217 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700218 data->apps.back().url_codebase.push_back(attrs[kAttrCodeBase]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800219 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400220 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800221 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700222 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700223 data->apps.back().packages.push_back({.name = attrs[kAttrName],
224 .size = attrs[kAttrSize],
225 .hash = attrs[kAttrHashSha256]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400226 } else if (data->current_path == "/response/app/updatecheck/manifest") {
227 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700228 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700229 data->apps.back().manifest_version = attrs[kAttrVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400230 } else if (data->current_path ==
231 "/response/app/updatecheck/manifest/actions/action") {
232 // We only care about the postinstall action.
Amin Hassani6600a562018-09-24 15:17:19 -0700233 if (attrs[kAttrEvent] == kValPostInstall && !data->apps.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700234 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400235 }
236 }
237}
238
239// Callback function invoked by expat.
240void ParserHandlerEnd(void* user_data, const XML_Char* element) {
241 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
242 if (data->failed)
243 return;
244
245 const string path_suffix = string("/") + element;
246
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800247 if (!base::EndsWith(
248 data->current_path, path_suffix, base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400249 LOG(ERROR) << "Unexpected end element '" << element
250 << "' with current_path='" << data->current_path << "'";
251 data->failed = true;
252 return;
253 }
254 data->current_path.resize(data->current_path.size() - path_suffix.size());
255}
256
David Zeuthenf3e28012014-08-26 18:23:52 -0400257// Callback function invoked by expat.
258//
259// This is called for entity declarations. Since Omaha is guaranteed
260// to never return any XML with entities our course of action is to
261// just stop parsing. This avoids potential resource exhaustion
262// problems AKA the "billion laughs". CVE-2013-0340.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800263void ParserHandlerEntityDecl(void* user_data,
264 const XML_Char* entity_name,
David Zeuthenf3e28012014-08-26 18:23:52 -0400265 int is_parameter_entity,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800266 const XML_Char* value,
David Zeuthenf3e28012014-08-26 18:23:52 -0400267 int value_length,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800268 const XML_Char* base,
269 const XML_Char* system_id,
270 const XML_Char* public_id,
271 const XML_Char* notation_name) {
David Zeuthenf3e28012014-08-26 18:23:52 -0400272 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
273
274 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
275 data->failed = true;
276 data->entity_decl = true;
277 XML_StopParser(data->xml_parser, false);
278}
279
David Zeuthene8ed8632014-07-24 13:38:10 -0400280} // namespace
281
Alex Deymoc1c17b42015-11-23 03:53:15 -0300282OmahaRequestAction::OmahaRequestAction(
283 SystemState* system_state,
284 OmahaEvent* event,
285 std::unique_ptr<HttpFetcher> http_fetcher,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700286 bool ping_only,
287 const string& session_id)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800288 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800289 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700290 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300291 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800292 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700293 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700294 ping_active_days_(0),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700295 ping_roll_call_days_(0),
296 session_id_(session_id) {
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) {
Andrewe045aef2020-01-08 16:29:22 -0800304 int days = kPingNeverPinged;
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700305 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 {
Andrewe045aef2020-01-08 16:29:22 -0800335 if (ping_active_days_ == kPingNeverPinged &&
336 ping_roll_call_days_ == kPingNeverPinged) {
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
Andrewe045aef2020-01-08 16:29:22 -0800417// static
418void OmahaRequestAction::StorePingReply(
419 const OmahaParserData& parser_data) const {
420 for (const auto& app : parser_data.apps) {
421 auto it = params_->dlc_apps_params().find(app.id);
422 if (it == params_->dlc_apps_params().end())
423 continue;
424
425 const OmahaRequestParams::AppParams& dlc_params = it->second;
426
427 // Skip if the ping for this DLC was not sent.
428 if (!dlc_params.send_ping)
429 continue;
430
431 base::FilePath metadata_path =
432 base::FilePath(params_->dlc_prefs_root()).Append(dlc_params.name);
433 if (!base::PathExists(metadata_path)) {
434 LOG(ERROR) << "Metadata path (" << metadata_path.value() << ") "
435 << "doesn't exist.";
436 // Skip this DLC if the metadata directory is missing.
437 continue;
438 }
439
440 Prefs prefs;
441 if (!prefs.Init(metadata_path)) {
442 LOG(ERROR) << "Failed to initialize the preferences path:"
443 << metadata_path.value() << ".";
444 continue;
445 }
446 // Reset the active metadata value to |kPingInactiveValue|.
447 // Only write into this file if the file exists, otherwise the file will be
448 // created with different owner/permissions.
449 if (prefs.Exists(kPrefsPingActive) &&
450 !prefs.SetInt64(kPrefsPingActive, kPingInactiveValue))
451 LOG(ERROR) << "Failed to set the value of ping metadata '"
452 << kPrefsPingActive << "'.";
453
454 if (!prefs.SetString(kPrefsPingLastRollcall,
455 parser_data.daystart_elapsed_days))
456 LOG(ERROR) << "Failed to set the value of ping metadata '"
457 << kPrefsPingLastRollcall << "'.";
458
459 if (dlc_params.ping_active) {
460 // Write the value of elapsed_days into |kPrefsPingLastActive| only if
461 // the previous ping was an active one.
462 if (!prefs.SetString(kPrefsPingLastActive,
463 parser_data.daystart_elapsed_days))
464 LOG(ERROR) << "Failed to set the value of ping metadata '"
465 << kPrefsPingLastActive << "'.";
466 }
467 }
468}
469
Darin Petkov6a5b3222010-07-13 14:55:28 -0700470void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000471 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700472 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700473 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700474 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700475 return;
476 }
David Zeuthen639aa362014-02-03 16:23:44 -0800477
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700478 OmahaRequestBuilderXml omaha_request(event_.get(),
479 params_,
480 ping_only_,
481 ShouldPing(), // include_ping
482 ping_active_days_,
483 ping_roll_call_days_,
484 GetInstallDate(system_state_),
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700485 system_state_->prefs(),
486 session_id_);
Jae Hoon Kimb7ee3872019-06-06 14:59:03 -0700487 string request_post = omaha_request.GetRequest();
Jay Srinivasan0a708742012-03-20 11:26:12 -0700488
Sen Jiang42fa45e2018-03-12 11:02:14 -0700489 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700490 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
491 params_->interactive() ? "fg" : "bg");
492 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
493 http_fetcher_->SetHeader(
494 kXGoogleUpdateUpdater,
495 base::StringPrintf(
496 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
497
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800498 http_fetcher_->SetPostData(
499 request_post.data(), request_post.size(), kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700500 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700501 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700502 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000503}
504
Darin Petkov6a5b3222010-07-13 14:55:28 -0700505void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000506 http_fetcher_->TerminateTransfer();
507}
508
509// We just store the response in the buffer. Once we've received all bytes,
510// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700511bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800512 const void* bytes,
513 size_t length) {
514 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
515 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700516 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000517}
518
519namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000520
521// Parses a 64 bit base-10 int from a string and returns it. Returns 0
522// on error. If the string contains "0", that's indistinguishable from
523// error.
524off_t ParseInt(const string& str) {
525 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700526 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000527 if (rc < 1) {
528 // failure
529 return 0;
530 }
531 return ret;
532}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700533
David Zeuthene8ed8632014-07-24 13:38:10 -0400534// Parses |str| and returns |true| if, and only if, its value is "true".
535bool ParseBool(const string& str) {
536 return str == "true";
537}
538
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700539// Update the last ping day preferences based on the server daystart
540// response. Returns true on success, false otherwise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800541bool UpdateLastPingDays(OmahaParserData* parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700542 int64_t elapsed_seconds = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800543 TEST_AND_RETURN_FALSE(base::StringToInt64(
544 parser_data->daystart_elapsed_seconds, &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700545 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
546
547 // Remember the local time that matches the server's last midnight
548 // time.
549 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
550 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
551 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
552 return true;
553}
Sen Jiang81259682017-03-30 15:11:30 -0700554
555// Parses the package node in the given XML document and populates
556// |output_object| if valid. Returns true if we should continue the parsing.
557// False otherwise, in which case it sets any error code using |completer|.
558bool ParsePackage(OmahaParserData::App* app,
559 OmahaResponse* output_object,
560 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700561 if (app->updatecheck_status.empty() ||
562 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700563 if (!app->packages.empty()) {
564 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
565 completer->set_code(ErrorCode::kOmahaResponseInvalid);
566 return false;
567 }
568 return true;
569 }
570 if (app->packages.empty()) {
571 LOG(ERROR) << "Omaha Response has no packages";
572 completer->set_code(ErrorCode::kOmahaResponseInvalid);
573 return false;
574 }
575 if (app->url_codebase.empty()) {
576 LOG(ERROR) << "No Omaha Response URLs";
577 completer->set_code(ErrorCode::kOmahaResponseInvalid);
578 return false;
579 }
580 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
581 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700582 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700583 ":",
584 base::TRIM_WHITESPACE,
585 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700586 vector<string> metadata_signatures = base::SplitString(
587 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
588 ":",
589 base::TRIM_WHITESPACE,
590 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700591 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700592 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700593 ":",
594 base::TRIM_WHITESPACE,
595 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700596 for (size_t i = 0; i < app->packages.size(); i++) {
597 const auto& package = app->packages[i];
598 if (package.name.empty()) {
599 LOG(ERROR) << "Omaha Response has empty package name";
600 completer->set_code(ErrorCode::kOmahaResponseInvalid);
601 return false;
602 }
603 LOG(INFO) << "Found package " << package.name;
604
605 OmahaResponse::Package out_package;
606 for (const string& codebase : app->url_codebase) {
607 if (codebase.empty()) {
608 LOG(ERROR) << "Omaha Response URL has empty codebase";
609 completer->set_code(ErrorCode::kOmahaResponseInvalid);
610 return false;
611 }
612 out_package.payload_urls.push_back(codebase + package.name);
613 }
614 // Parse the payload size.
615 base::StringToUint64(package.size, &out_package.size);
616 if (out_package.size <= 0) {
617 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
618 completer->set_code(ErrorCode::kOmahaResponseInvalid);
619 return false;
620 }
621 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
622
623 if (i < metadata_sizes.size())
624 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
625 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
626 << " bytes";
627
628 if (i < metadata_signatures.size())
629 out_package.metadata_signature = metadata_signatures[i];
630 LOG(INFO) << "Payload metadata signature = "
631 << out_package.metadata_signature;
632
633 out_package.hash = package.hash;
634 if (out_package.hash.empty()) {
635 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
636 completer->set_code(ErrorCode::kOmahaResponseInvalid);
637 return false;
638 }
639 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700640
641 if (i < is_delta_payloads.size())
642 out_package.is_delta = ParseBool(is_delta_payloads[i]);
643 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
644
Sen Jiang81259682017-03-30 15:11:30 -0700645 output_object->packages.push_back(std::move(out_package));
646 }
647
648 return true;
649}
650
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700651// Parses the 2 key version strings kernel_version and firmware_version. If the
652// field is not present, or cannot be parsed the values default to 0xffff.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700653void ParseRollbackVersions(int allowed_milestones,
654 OmahaParserData* parser_data,
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700655 OmahaResponse* output_object) {
656 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700657 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700658 &output_object->rollback_key_version.firmware_key,
659 &output_object->rollback_key_version.firmware);
660 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700661 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700662 &output_object->rollback_key_version.kernel_key,
663 &output_object->rollback_key_version.kernel);
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700664
665 // Create the attribute name strings for milestone N - allowed_milestones.
666 const string firmware_max_rollforward_attr =
667 base::StringPrintf("%s_%i", kAttrFirmwareVersion, allowed_milestones);
668 const string kernel_max_rollforward_attr =
669 base::StringPrintf("%s_%i", kAttrKernelVersion, allowed_milestones);
670
671 const bool max_firmware_and_kernel_exist =
672 parser_data->updatecheck_attrs.count(firmware_max_rollforward_attr) > 0 &&
673 parser_data->updatecheck_attrs.count(kernel_max_rollforward_attr) > 0;
674
675 string firmware_version;
676 string kernel_version;
677 if (max_firmware_and_kernel_exist) {
678 firmware_version =
679 parser_data->updatecheck_attrs[firmware_max_rollforward_attr];
680 kernel_version =
681 parser_data->updatecheck_attrs[kernel_max_rollforward_attr];
682 }
683
684 LOG(INFO) << "For milestone N-" << allowed_milestones
685 << " firmware_key_version=" << firmware_version
686 << " kernel_key_version=" << kernel_version;
687
688 OmahaResponse::RollbackKeyVersion version;
689 utils::ParseRollbackKeyVersion(
690 firmware_version, &version.firmware_key, &version.firmware);
691 utils::ParseRollbackKeyVersion(
692 kernel_version, &version.kernel_key, &version.kernel);
693
694 output_object->past_rollback_key_version = std::move(version);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700695}
696
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700697} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000698
David Zeuthene8ed8632014-07-24 13:38:10 -0400699bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700700 OmahaResponse* output_object,
701 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700702 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700703 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700704 return false;
705 }
Sen Jiang81259682017-03-30 15:11:30 -0700706 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700707
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800708 // chromium-os:37289: The PollInterval is not supported by Omaha server
709 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700710 // slow down the request rate from the server-side. Note that the PollInterval
711 // is not persisted, so it has to be sent by the server on every response to
712 // guarantee that the scheduler uses this value (otherwise, if the device got
713 // rebooted after the last server-indicated value, it'll revert to the default
714 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
715 // based on the assumption that we perform an update check every hour so that
716 // the max value of 8 will roughly be equivalent to one work day. If we decide
717 // to use PollInterval permanently, we should update the
718 // max_update_checks_allowed to take PollInterval into account. Note: The
719 // parsing for PollInterval happens even before parsing of the status because
720 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400721 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700722 &output_object->poll_interval);
723
David Zeuthen639aa362014-02-03 16:23:44 -0800724 // Check for the "elapsed_days" attribute in the "daystart"
725 // element. This is the number of days since Jan 1 2007, 0:00
726 // PST. If we don't have a persisted value of the Omaha InstallDate,
727 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400728 if (ParseInstallDate(parser_data, output_object) &&
729 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800730 // Since output_object->install_date_days is never negative, the
731 // elapsed_days -> install-date calculation is reduced to simply
732 // rounding down to the nearest number divisible by 7.
733 int remainder = output_object->install_date_days % 7;
734 int install_date_days_rounded =
735 output_object->install_date_days - remainder;
736 if (PersistInstallDate(system_state_,
737 install_date_days_rounded,
738 kProvisionedFromOmahaResponse)) {
739 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
740 << install_date_days_rounded << " days";
741 }
742 }
743
Alex Deymo00d79ac2015-06-29 15:41:49 -0700744 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700745 for (const auto& app : parser_data->apps) {
746 if (app.id == params_->GetAppId()) {
747 if (app.cohort_set)
748 PersistCohortData(kPrefsOmahaCohort, app.cohort);
749 if (app.cohorthint_set)
750 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
751 if (app.cohortname_set)
752 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
753 break;
754 }
755 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700756
Amin Hassani2cbb0692019-10-30 13:36:17 -0700757 PersistEolInfo(parser_data->updatecheck_attrs);
758
Marton Hunyady199152d2018-05-07 19:08:48 +0200759 // Rollback-related updatecheck attributes.
760 // Defaults to false if attribute is not present.
761 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -0700762 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700763
764 // Parses the rollback versions of the current image. If the fields do not
765 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700766 ParseRollbackVersions(
767 params_->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -0700768
David Zeuthene8ed8632014-07-24 13:38:10 -0400769 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700770 return false;
771
David Zeuthene8ed8632014-07-24 13:38:10 -0400772 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700773 return false;
774
Sen Jiang0affc2c2017-02-10 15:55:05 -0800775 // Package has to be parsed after Params now because ParseParams need to make
776 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -0700777 for (auto& app : parser_data->apps)
778 if (!ParsePackage(&app, output_object, completer))
779 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800780
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700781 return true;
782}
783
David Zeuthene8ed8632014-07-24 13:38:10 -0400784bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700785 OmahaResponse* output_object,
786 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700787 output_object->update_exists = false;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700788 for (const auto& app : parser_data->apps) {
789 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -0700790 if (status == kValNoUpdate) {
Jae Hoon Kim5e9cd712020-02-12 15:28:28 -0800791 // If the app is a DLC, allow status "noupdate" to support DLC
792 // deprecations.
793 if (params_->IsDlcAppId(app.id)) {
794 LOG(INFO) << "No update for <app> " << app.id
795 << " but update continuing since a DLC.";
796 continue;
797 }
Sen Jiang00adf7b2017-06-26 15:57:29 -0700798 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -0700799 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700800 output_object->update_exists = false;
801 break;
Sen Jiang81259682017-03-30 15:11:30 -0700802 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700803 auto const& attr_no_update =
804 app.action_postinstall_attrs.find(kAttrNoUpdate);
805 if (attr_no_update != app.action_postinstall_attrs.end() &&
806 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -0700807 // noupdate="true" in postinstall attributes means it's an update to
808 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -0700809 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700810 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700811 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -0700812 output_object->update_exists = true;
813 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700814 } else if (status.empty() && params_->is_install() &&
815 params_->GetAppId() == app.id) {
816 // Skips the platform app for install operation.
817 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -0700818 } else {
819 LOG(ERROR) << "Unknown Omaha response status: " << status;
820 completer->set_code(ErrorCode::kOmahaResponseInvalid);
821 return false;
822 }
823 }
824 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700825 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700826 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700827 }
828
Sen Jiang81259682017-03-30 15:11:30 -0700829 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700830}
831
David Zeuthene8ed8632014-07-24 13:38:10 -0400832bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700833 OmahaResponse* output_object,
834 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700835 map<string, string> attrs;
836 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700837 if (app.id == params_->GetAppId()) {
838 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -0700839 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700840 } else if (!params_->system_app_id().empty() &&
841 app.id == params_->system_app_id()) {
842 // this is the system app (this check is intentionally skipped if there is
843 // no system_app_id set)
844 output_object->system_version = app.manifest_version;
Xiaochu Liu6310be62018-10-11 15:09:03 -0700845 } else if (params_->is_install() &&
846 app.manifest_version != params_->app_version()) {
847 LOG(WARNING) << "An app has a different version (" << app.manifest_version
848 << ") that is different than platform app version ("
849 << params_->app_version() << ")";
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700850 }
851 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700852 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700853 }
Sen Jiang81259682017-03-30 15:11:30 -0700854 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700855 if (params_->is_install()) {
856 LOG(INFO) << "Use request version for Install operation.";
857 output_object->version = params_->app_version();
858 }
Chris Sosa3b748432013-06-20 16:42:59 -0700859 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700860 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700861 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700862 return false;
863 }
864
865 LOG(INFO) << "Received omaha response to update to version "
866 << output_object->version;
867
David Zeuthene8ed8632014-07-24 13:38:10 -0400868 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700869 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700870 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700871 return false;
872 }
873
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800874 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -0700875 output_object->more_info_url = attrs[kAttrMoreInfo];
876 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
877 output_object->deadline = attrs[kAttrDeadline];
878 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700879 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -0700880 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700881 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -0700882 ParseBool(attrs[kAttrDisableP2PForSharing]);
883 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800884
Amin Hassani6600a562018-09-24 15:17:19 -0700885 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800886 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800887 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700888
Jay Srinivasan08262882012-12-28 19:29:43 -0800889 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -0700890 ParseBool(attrs[kAttrDisablePayloadBackoff]);
891 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800892
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700893 return true;
894}
895
David Zeuthene8ed8632014-07-24 13:38:10 -0400896// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000897// and fill in the appropriate fields of the output object. Also, notifies
898// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800899void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -0700900 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000901 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800902 string current_response(response_buffer_.begin(), response_buffer_.end());
903 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700904
Gilad Arnold74b5f552014-10-07 08:17:16 -0700905 PayloadStateInterface* const payload_state = system_state_->payload_state();
906
Zentaro Kavanagh76af2662018-05-15 10:54:53 -0700907 // Set the max kernel key version based on whether rollback is allowed.
908 SetMaxKernelKeyVersionForRollback();
909
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700910 // Events are best effort transactions -- assume they always succeed.
911 if (IsEvent()) {
912 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700913 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700914 return;
915 }
916
Amin Hassanid3d84212019-08-17 00:27:44 -0700917 ErrorCode aux_error_code = fetcher->GetAuxiliaryErrorCode();
918 if (aux_error_code != ErrorCode::kSuccess) {
919 metrics::DownloadErrorCode download_error_code =
920 metrics_utils::GetDownloadErrorCode(aux_error_code);
921 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
922 system_state_,
923 metrics::CheckResult::kUnset,
924 metrics::CheckReaction::kUnset,
925 download_error_code);
926 }
927
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700928 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700929 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700930 int code = GetHTTPResponseCode();
931 // Makes sure we send sane error values.
932 if (code < 0 || code >= 1000) {
933 code = 999;
934 }
David Zeuthena99981f2013-04-29 13:42:47 -0700935 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700936 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000937 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700938 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000939
David Zeuthene8ed8632014-07-24 13:38:10 -0400940 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400941 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400942 XML_SetUserData(parser, &parser_data);
943 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400944 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800945 XML_Status res =
946 XML_Parse(parser,
947 reinterpret_cast<const char*>(response_buffer_.data()),
948 response_buffer_.size(),
949 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400950
951 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700952 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800953 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
954 << XML_GetCurrentLineNumber(parser) << " col "
955 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -0700956 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400957 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
958 if (response_buffer_.empty()) {
959 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
960 } else if (parser_data.entity_decl) {
961 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
962 }
963 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000964 return;
965 }
Amin Hassani91f48b42018-08-06 17:47:14 -0700966 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000967
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700968 // Update the last ping day preferences based on the server daystart response
969 // even if we didn't send a ping. Omaha always includes the daystart in the
970 // response, but log the error if it didn't.
971 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
972 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700973
Amin Hassani1677e812017-06-21 13:36:36 -0700974 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
975 // we have got a response from omaha and if its value has never been set to
976 // true before. Failure of this function should be ignored. There should be no
977 // need to check if a=-1 has been sent because older devices have already sent
978 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
979 // future checks.
980 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -0700981 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
982 system_state_->metrics_reporter()->ReportInternalErrorCode(
983 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
984 }
Amin Hassani1677e812017-06-21 13:36:36 -0700985 }
986
Andrewe045aef2020-01-08 16:29:22 -0800987 // Create/update the metadata files for each DLC app received.
988 StorePingReply(parser_data);
989
Thieu Le116fda32011-04-19 11:01:54 -0700990 if (!HasOutputPipe()) {
991 // Just set success to whether or not the http transfer succeeded,
992 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700993 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700994 return;
995 }
996
Darin Petkov6a5b3222010-07-13 14:55:28 -0700997 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400998 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000999 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001000 output_object.update_exists = true;
1001 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001002
Toni Barzic61544e62018-10-11 14:37:30 -07001003 LoadOrPersistUpdateFirstSeenAtPref();
1004
Weidong Guo421ff332017-04-17 10:08:38 -07001005 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -07001006 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -07001007 // No need to change output_object.update_exists here, since the value
1008 // has been output to the pipe.
1009 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001010 return;
1011 }
1012
David Zeuthen8f191b22013-08-06 12:27:50 -07001013 // If Omaha says to disable p2p, respect that
1014 if (output_object.disable_p2p_for_downloading) {
1015 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1016 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001017 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001018 }
1019 if (output_object.disable_p2p_for_sharing) {
1020 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1021 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001022 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001023 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001024
1025 // Update the payload state with the current response. The payload state
1026 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001027 // from what's stored already. We are updating the payload state as late
1028 // as possible in this method so that if a new release gets pushed and then
1029 // got pulled back due to some issues, we don't want to clear our internal
1030 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001031 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001032
David Zeuthen8f191b22013-08-06 12:27:50 -07001033 // It could be we've already exceeded the deadline for when p2p is
1034 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001035 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001036 payload_state->P2PNewAttempt();
1037 if (!payload_state->P2PAttemptAllowed()) {
1038 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1039 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001040 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001041 }
1042 }
1043
1044 // From here on, we'll complete stuff in CompleteProcessing() so
1045 // disable |completer| since we'll create a new one in that
1046 // function.
1047 completer.set_should_complete(false);
1048
1049 // If we're allowed to use p2p for downloading we do not pay
1050 // attention to wall-clock-based waiting if the URL is indeed
1051 // available via p2p. Therefore, check if the file is available via
1052 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001053 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001054 LookupPayloadViaP2P(output_object);
1055 } else {
1056 CompleteProcessing();
1057 }
1058}
1059
1060void OmahaRequestAction::CompleteProcessing() {
1061 ScopedActionCompleter completer(processor_, this);
1062 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1063 PayloadStateInterface* payload_state = system_state_->payload_state();
1064
1065 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001066 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001067 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001068 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001069 return;
1070 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001071
Chris Sosa20f005c2013-09-05 13:53:08 -07001072 if (payload_state->ShouldBackoffDownload()) {
1073 output_object.update_exists = false;
1074 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1075 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001076 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001077 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001078 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001079 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001080}
1081
1082void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1083 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1084 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001085 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001086 } else {
1087 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1088 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001089 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001090 }
1091 CompleteProcessing();
1092}
1093
1094void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001095 // If the device is in the middle of an update, the state variables
1096 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1097 // tracks the offset and length of the operation currently in
1098 // progress. The offset is based from the end of the manifest which
1099 // is kPrefsManifestMetadataSize bytes long.
1100 //
1101 // To make forward progress and avoid deadlocks, we need to find a
1102 // peer that has at least the entire operation we're currently
1103 // working on. Otherwise we may end up in a situation where two
1104 // devices bounce back and forth downloading from each other,
1105 // neither making any forward progress until one of them decides to
1106 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1107 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001108 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001109 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001110 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001111 int64_t next_data_offset = 0;
1112 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001113 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001114 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1115 &manifest_metadata_size) &&
1116 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001117 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1118 &manifest_signature_size) &&
1119 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001120 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001121 &next_data_offset) &&
1122 next_data_offset != -1 &&
1123 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1124 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001125 minimum_size = manifest_metadata_size + manifest_signature_size +
1126 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001127 }
1128
Sen Jiang0affc2c2017-02-10 15:55:05 -08001129 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001130 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001131 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001132 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001133 string file_id =
1134 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001135 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001136 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1137 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001138 system_state_->p2p_manager()->LookupUrlForFile(
1139 file_id,
1140 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001141 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001142 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1143 base::Unretained(this)));
1144 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001145}
1146
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001147bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001148 if (params_->interactive()) {
1149 LOG(INFO) << "Not deferring download because update is interactive.";
1150 return false;
1151 }
1152
David Zeuthen8f191b22013-08-06 12:27:50 -07001153 // If we're using p2p to download _and_ we have a p2p URL, we never
1154 // defer the download. This is because the download will always
1155 // happen from a peer on the LAN and we've been waiting in line for
1156 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001157 const PayloadStateInterface* payload_state = system_state_->payload_state();
1158 if (payload_state->GetUsingP2PForDownloading() &&
1159 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001160 LOG(INFO) << "Download not deferred because download "
1161 << "will happen from a local peer (via p2p).";
1162 return false;
1163 }
1164
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001165 // We should defer the downloads only if we've first satisfied the
1166 // wall-clock-based-waiting period and then the update-check-based waiting
1167 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001168 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001169 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1170 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001171 return false;
1172 }
1173
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001174 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001175 case kWallClockWaitNotSatisfied:
1176 // We haven't even satisfied the first condition, passing the
1177 // wall-clock-based waiting period, so we should defer the downloads
1178 // until that happens.
1179 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1180 return true;
1181
1182 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1183 LOG(INFO) << "wall-clock-based-wait satisfied and "
1184 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001185 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001186
1187 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1188 // Wall-clock-based waiting period is satisfied, and it's determined
1189 // that we do not need the update-check-based wait. so no need to
1190 // defer downloads.
1191 LOG(INFO) << "wall-clock-based-wait satisfied and "
1192 << "update-check-based-wait is not required.";
1193 return false;
1194
1195 default:
1196 // Returning false for this default case so we err on the
1197 // side of downloading updates than deferring in case of any bugs.
1198 NOTREACHED();
1199 return false;
1200 }
1201}
1202
1203OmahaRequestAction::WallClockWaitResult
1204OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001205 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001206 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1207 if (update_first_seen_at == base::Time()) {
1208 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
1209 "persisted";
1210 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001211 }
1212
Sen Jiang7c1171e2016-06-23 11:35:40 -07001213 TimeDelta elapsed_time =
1214 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1215 TimeDelta max_scatter_period =
1216 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001217 int64_t staging_wait_time_in_days = 0;
1218 // Use staging and its default max value if staging is on.
1219 if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1220 &staging_wait_time_in_days) &&
1221 staging_wait_time_in_days > 0)
1222 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001223
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001224 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001225 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001226 << ", Time Elapsed = "
1227 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001228 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001229
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001230 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001231 // The deadline is set for all rules which serve a delta update from a
1232 // previous FSI, which means this update will be applied mostly in OOBE
1233 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1234 // quickly.
1235 LOG(INFO) << "Not scattering as deadline flag is set";
1236 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1237 }
1238
1239 if (max_scatter_period.InDays() == 0) {
1240 // This means the Omaha rule creator decides that this rule
1241 // should not be scattered irrespective of the policy.
1242 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1243 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1244 }
1245
1246 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001247 // This means we've waited more than the upperbound wait in the rule
1248 // from the time we first saw a valid update available to us.
1249 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001250 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1251 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1252 }
1253
1254 // This means we are required to participate in scattering.
1255 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001256 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001257 if (remaining_wait_time.InSeconds() <= 0) {
1258 // Yes, it's our turn now.
1259 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1260
1261 // But we can't download until the update-check-count-based wait is also
1262 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001263 return params_->update_check_count_wait_enabled()
1264 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1265 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001266 }
1267
1268 // Not our turn yet, so we have to wait until our turn to
1269 // help scatter the downloads across all clients of the enterprise.
1270 LOG(INFO) << "Update deferred for another "
1271 << utils::FormatSecs(remaining_wait_time.InSeconds())
1272 << " per policy.";
1273 return kWallClockWaitNotSatisfied;
1274}
1275
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001276bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001277 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001278
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001279 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1280 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1281 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001282 // We are unable to read the update check count from file for some reason.
1283 // So let's proceed anyway so as to not stall the update.
1284 LOG(ERROR) << "Unable to read update check count. "
1285 << "Skipping update-check-count-based-wait.";
1286 return true;
1287 }
1288 } else {
1289 // This file does not exist. This means we haven't started our update
1290 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001291 update_check_count_value =
1292 base::RandInt(params_->min_update_checks_needed(),
1293 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001294
1295 LOG(INFO) << "Randomly picked update check count value = "
1296 << update_check_count_value;
1297
1298 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001299 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1300 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001301 // We weren't able to write the update check count file for some reason.
1302 // So let's proceed anyway so as to not stall the update.
1303 LOG(ERROR) << "Unable to write update check count. "
1304 << "Skipping update-check-count-based-wait.";
1305 return true;
1306 }
1307 }
1308
1309 if (update_check_count_value == 0) {
1310 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1311 return true;
1312 }
1313
1314 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001315 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001316 // We err on the side of skipping scattering logic instead of stalling
1317 // a machine from receiving any updates in case of any unexpected state.
1318 LOG(ERROR) << "Invalid value for update check count detected. "
1319 << "Skipping update-check-count-based-wait.";
1320 return true;
1321 }
1322
1323 // Legal value, we need to wait for more update checks to happen
1324 // until this becomes 0.
1325 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001326 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001327 return false;
1328}
1329
David Zeuthen639aa362014-02-03 16:23:44 -08001330// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001331bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001332 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001333 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001334 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001335 return false;
1336
1337 if (elapsed_days < 0)
1338 return false;
1339
1340 output_object->install_date_days = elapsed_days;
1341 return true;
1342}
1343
1344// static
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001345bool OmahaRequestAction::HasInstallDate(SystemState* system_state) {
David Zeuthen639aa362014-02-03 16:23:44 -08001346 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001347 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001348 return false;
1349
1350 return prefs->Exists(kPrefsInstallDateDays);
1351}
1352
1353// static
1354bool OmahaRequestAction::PersistInstallDate(
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001355 SystemState* system_state,
David Zeuthen639aa362014-02-03 16:23:44 -08001356 int install_date_days,
1357 InstallDateProvisioningSource source) {
1358 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1359
1360 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001361 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001362 return false;
1363
1364 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1365 return false;
1366
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001367 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001368 static_cast<int>(source), // Sample.
1369 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001370 return true;
1371}
1372
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001373bool OmahaRequestAction::PersistCohortData(const string& prefs_key,
1374 const string& new_value) {
Alex Deymo8e18f932015-03-27 16:16:59 -07001375 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1376 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1377 return system_state_->prefs()->Delete(prefs_key);
1378 } else if (!new_value.empty()) {
1379 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1380 return system_state_->prefs()->SetString(prefs_key, new_value);
1381 }
1382 return true;
1383}
1384
Amin Hassani2cbb0692019-10-30 13:36:17 -07001385bool OmahaRequestAction::PersistEolInfo(const map<string, string>& attrs) {
Jae Hoon Kimb3146742019-11-07 13:24:24 -08001386 // If EOL date attribute is not sent, don't delete the old persisted EOL
1387 // date information.
Jae Hoon Kim051627a2019-09-03 12:56:32 -07001388 auto eol_date_attr = attrs.find(kAttrEolDate);
Jae Hoon Kimb3146742019-11-07 13:24:24 -08001389 if (eol_date_attr != attrs.end() &&
1390 !system_state_->prefs()->SetString(kPrefsOmahaEolDate,
1391 eol_date_attr->second)) {
Jae Hoon Kim051627a2019-09-03 12:56:32 -07001392 LOG(ERROR) << "Setting EOL date failed.";
Amin Hassani2cbb0692019-10-30 13:36:17 -07001393 return false;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001394 }
Amin Hassani2cbb0692019-10-30 13:36:17 -07001395 return true;
Alex Deymob3fa53b2016-04-18 19:57:58 -07001396}
1397
David Zeuthen33bae492014-02-25 16:16:18 -08001398void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1399 // We only want to report this on "update check".
1400 if (ping_only_ || event_ != nullptr)
1401 return;
1402
1403 metrics::CheckResult result = metrics::CheckResult::kUnset;
1404 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1405 metrics::DownloadErrorCode download_error_code =
1406 metrics::DownloadErrorCode::kUnset;
1407
1408 // Regular update attempt.
1409 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001410 case ErrorCode::kSuccess:
1411 // OK, we parsed the response successfully but that does
1412 // necessarily mean that an update is available.
1413 if (HasOutputPipe()) {
1414 const OmahaResponse& response = GetOutputObject();
1415 if (response.update_exists) {
1416 result = metrics::CheckResult::kUpdateAvailable;
1417 reaction = metrics::CheckReaction::kUpdating;
1418 } else {
1419 result = metrics::CheckResult::kNoUpdateAvailable;
1420 }
David Zeuthen33bae492014-02-25 16:16:18 -08001421 } else {
1422 result = metrics::CheckResult::kNoUpdateAvailable;
1423 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001424 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001425
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001426 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1427 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1428 result = metrics::CheckResult::kUpdateAvailable;
1429 reaction = metrics::CheckReaction::kIgnored;
1430 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001431
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001432 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1433 result = metrics::CheckResult::kUpdateAvailable;
1434 reaction = metrics::CheckReaction::kDeferring;
1435 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001436
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001437 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1438 result = metrics::CheckResult::kUpdateAvailable;
1439 reaction = metrics::CheckReaction::kBackingOff;
1440 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001441
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001442 default:
1443 // We report two flavors of errors, "Download errors" and "Parsing
1444 // error". Try to convert to the former and if that doesn't work
1445 // we know it's the latter.
1446 metrics::DownloadErrorCode tmp_error =
1447 metrics_utils::GetDownloadErrorCode(code);
1448 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1449 result = metrics::CheckResult::kDownloadError;
1450 download_error_code = tmp_error;
1451 } else {
1452 result = metrics::CheckResult::kParsingError;
1453 }
1454 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001455 }
1456
Amin Hassanid3d84212019-08-17 00:27:44 -07001457 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1458 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001459}
1460
Toni Barzic61544e62018-10-11 14:37:30 -07001461bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1462 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001463 // Note: policy decision to not update to a version we rolled back from.
1464 string rollback_version =
1465 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001466 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001467 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001468 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001469 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001470 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001471 return true;
1472 }
1473 }
1474
Toni Barzic61544e62018-10-11 14:37:30 -07001475 if (system_state_->hardware()->IsOOBEEnabled() &&
1476 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
1477 (response.deadline.empty() ||
1478 system_state_->payload_state()->GetRollbackHappened()) &&
1479 params_->app_version() != "ForcedUpdate") {
1480 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1481 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1482 return true;
1483 }
1484
Weidong Guo421ff332017-04-17 10:08:38 -07001485 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001486 LOG(INFO) << "Update is not allowed over current connection.";
1487 return true;
1488 }
1489
1490 // Note: We could technically delete the UpdateFirstSeenAt state when we
1491 // return true. If we do, it'll mean a device has to restart the
1492 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1493 // turned on again. On the other hand, it also increases the chance of update
1494 // starvation if an admin turns AU on/off more frequently. We choose to err on
1495 // the side of preventing starvation at the cost of not applying scattering in
1496 // those cases.
1497 return false;
1498}
1499
Weidong Guo421ff332017-04-17 10:08:38 -07001500bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1501 const OmahaResponse& response) const {
1502 PrefsInterface* prefs = system_state_->prefs();
1503
1504 if (!prefs) {
1505 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1506 "not available.";
1507 return false;
1508 }
1509
1510 bool is_allowed;
1511
1512 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1513 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1514 is_allowed) {
1515 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1516 "set to true.";
1517 return true;
1518 }
1519
1520 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1521 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1522 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1523 "set to false or does not exist while target does not exist.";
1524 return false;
1525 }
1526
1527 std::string target_version;
1528 int64_t target_size;
1529
1530 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1531 &target_version) ||
1532 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1533 LOG(INFO) << "Disabling updates over cellular as the target version or "
1534 "size is not accessible.";
1535 return false;
1536 }
1537
1538 uint64_t total_packages_size = 0;
1539 for (const auto& package : response.packages) {
1540 total_packages_size += package.size;
1541 }
1542 if (target_version == response.version &&
1543 static_cast<uint64_t>(target_size) == total_packages_size) {
1544 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1545 "omaha response.";
1546 return true;
1547 } else {
1548 LOG(INFO) << "Disabling updates over cellular as the target does not"
1549 "match the omaha response.";
1550 return false;
1551 }
1552}
1553
1554bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1555 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001556 ConnectionType type;
1557 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001558 ConnectionManagerInterface* connection_manager =
1559 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001560 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001561 LOG(INFO) << "We could not determine our connection type. "
1562 << "Defaulting to allow updates.";
1563 return true;
1564 }
Weidong Guo421ff332017-04-17 10:08:38 -07001565
Chris Sosa77f79e82014-06-02 18:16:24 -07001566 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001567 bool is_device_policy_set =
1568 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1569 // Treats tethered connection as if it is cellular connection.
1570 bool is_over_cellular = type == ConnectionType::kCellular ||
1571 tethering == ConnectionTethering::kConfirmed;
1572
1573 if (!is_over_cellular) {
1574 // There's no need to further check user preferences as we are not over
1575 // cellular connection.
1576 if (!is_allowed)
1577 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1578 } else if (is_device_policy_set) {
1579 // There's no need to further check user preferences as the device policy
1580 // is set regarding updates over cellular.
1581 if (!is_allowed)
1582 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1583 } else {
1584 // Deivce policy is not set, so user preferences overwrite whether to
1585 // allow updates over cellular.
1586 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1587 if (!is_allowed)
1588 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1589 }
1590
Chris Sosa77f79e82014-06-02 18:16:24 -07001591 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001592 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001593 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1594 return is_allowed;
1595}
1596
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001597bool OmahaRequestAction::IsRollbackEnabled() const {
1598 if (policy_provider_->IsConsumerDevice()) {
1599 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1600 return false;
1601 }
1602
1603 if (!policy_provider_->device_policy_is_loaded()) {
1604 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1605 return true;
1606 }
1607
1608 int allowed_milestones;
1609 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1610 &allowed_milestones)) {
1611 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1612 "Defaulting to rollback enabled.";
1613 return true;
1614 }
1615
1616 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1617 return allowed_milestones > 0;
1618}
1619
1620void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001621 int max_kernel_rollforward;
1622 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001623 if (IsRollbackEnabled()) {
1624 // If rollback is enabled, set the max kernel key version to the current
1625 // kernel key version. This has the effect of freezing kernel key roll
1626 // forwards.
1627 //
1628 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1629 // key roll forward happens until the server side components of rollback
1630 // are implemented. Future changes will allow the Omaha server to return
1631 // the kernel key version from max_rollback_versions in the past. At that
1632 // point the max kernel key version will be set to that value, creating a
1633 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001634 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001635 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001636 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001637 } else {
1638 // For devices that are not rollback enabled (ie. consumer devices), the
1639 // max kernel key version is set to 0xfffffffe, which is logically
1640 // infinity. This maintains the previous behavior that that kernel key
1641 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001642 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001643 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001644 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001645 }
1646
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001647 bool max_rollforward_set =
1648 system_state_->hardware()->SetMaxKernelKeyRollforward(
1649 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001650 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001651 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001652 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001653 // Report metrics
1654 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1655 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001656}
1657
May Lippert60aa3ca2018-08-15 16:55:29 -07001658base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1659 Time update_first_seen_at;
1660 int64_t update_first_seen_at_int;
1661 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1662 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1663 &update_first_seen_at_int)) {
1664 // Note: This timestamp could be that of ANY update we saw in the past
1665 // (not necessarily this particular update we're considering to apply)
1666 // but never got to apply because of some reason (e.g. stop AU policy,
1667 // updates being pulled out from Omaha, changes in target version prefix,
1668 // new update being rolled out, etc.). But for the purposes of scattering
1669 // it doesn't matter which update the timestamp corresponds to. i.e.
1670 // the clock starts ticking the first time we see an update and we're
1671 // ready to apply when the random wait period is satisfied relative to
1672 // that first seen timestamp.
1673 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1674 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1675 << utils::ToString(update_first_seen_at);
1676 } else {
1677 // This seems like an unexpected error where the persisted value exists
1678 // but it's not readable for some reason.
1679 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1680 return base::Time();
1681 }
1682 } else {
1683 update_first_seen_at = system_state_->clock()->GetWallclockTime();
1684 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
1685 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1686 update_first_seen_at_int)) {
1687 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1688 << utils::ToString(update_first_seen_at);
1689 } else {
1690 // This seems like an unexpected error where the value cannot be
1691 // persisted for some reason.
1692 LOG(INFO) << "UpdateFirstSeenAt value "
1693 << utils::ToString(update_first_seen_at)
1694 << " cannot be persisted";
1695 return base::Time();
1696 }
1697 }
1698 return update_first_seen_at;
1699}
1700
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001701} // namespace chromeos_update_engine