blob: f1678eefd56a45ebb6874dd8e5fcb8ccee789727 [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"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070051#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070052#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080053#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000054
Darin Petkov1cbd78f2010-07-29 12:38:34 -070055using base::Time;
56using base::TimeDelta;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -080057using chromeos_update_manager::kRollforwardInfinity;
David Zeuthene8ed8632014-07-24 13:38:10 -040058using std::map;
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -070059using std::numeric_limits;
rspangler@google.com49fdf182009-10-10 00:57:34 +000060using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040061using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000062
63namespace chromeos_update_engine {
64
Amin Hassani6600a562018-09-24 15:17:19 -070065// List of custom attributes that we interpret in the Omaha response:
66constexpr char kAttrDeadline[] = "deadline";
67constexpr char kAttrDisableP2PForDownloading[] = "DisableP2PForDownloading";
68constexpr char kAttrDisableP2PForSharing[] = "DisableP2PForSharing";
69constexpr char kAttrDisablePayloadBackoff[] = "DisablePayloadBackoff";
70constexpr char kAttrVersion[] = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080071// Deprecated: "IsDelta"
Amin Hassani6600a562018-09-24 15:17:19 -070072constexpr char kAttrIsDeltaPayload[] = "IsDeltaPayload";
73constexpr char kAttrMaxFailureCountPerUrl[] = "MaxFailureCountPerUrl";
74constexpr char kAttrMaxDaysToScatter[] = "MaxDaysToScatter";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080075// Deprecated: "ManifestSignatureRsa"
76// Deprecated: "ManifestSize"
Amin Hassani6600a562018-09-24 15:17:19 -070077constexpr char kAttrMetadataSignatureRsa[] = "MetadataSignatureRsa";
78constexpr char kAttrMetadataSize[] = "MetadataSize";
79constexpr char kAttrMoreInfo[] = "MoreInfo";
80constexpr char kAttrNoUpdate[] = "noupdate";
Don Garrett42bd3aa2013-04-10 18:14:56 -070081// Deprecated: "NeedsAdmin"
Amin Hassani6600a562018-09-24 15:17:19 -070082constexpr char kAttrPollInterval[] = "PollInterval";
83constexpr char kAttrPowerwash[] = "Powerwash";
84constexpr char kAttrPrompt[] = "Prompt";
85constexpr char kAttrPublicKeyRsa[] = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080086
Amin Hassani6600a562018-09-24 15:17:19 -070087// List of attributes that we interpret in the Omaha response:
88constexpr char kAttrAppId[] = "appid";
89constexpr char kAttrCodeBase[] = "codebase";
90constexpr char kAttrCohort[] = "cohort";
91constexpr char kAttrCohortHint[] = "cohorthint";
92constexpr char kAttrCohortName[] = "cohortname";
93constexpr char kAttrElapsedDays[] = "elapsed_days";
94constexpr char kAttrElapsedSeconds[] = "elapsed_seconds";
95constexpr char kAttrEvent[] = "event";
96constexpr char kAttrHashSha256[] = "hash_sha256";
97// Deprecated: "hash"; Although we still need to pass it from the server for
98// backward compatibility.
99constexpr char kAttrName[] = "name";
100// Deprecated: "sha256"; Although we still need to pass it from the server for
101// backward compatibility.
102constexpr char kAttrSize[] = "size";
103constexpr char kAttrStatus[] = "status";
104
105// List of values that we interpret in the Omaha response:
106constexpr char kValPostInstall[] = "postinstall";
107constexpr char kValNoUpdate[] = "noupdate";
108
109constexpr char kOmahaUpdaterVersion[] = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +0000110
Sen Jiang42fa45e2018-03-12 11:02:14 -0700111// X-Goog-Update headers.
Amin Hassani6600a562018-09-24 15:17:19 -0700112constexpr char kXGoogleUpdateInteractivity[] = "X-Goog-Update-Interactivity";
113constexpr char kXGoogleUpdateAppId[] = "X-Goog-Update-AppId";
114constexpr char kXGoogleUpdateUpdater[] = "X-Goog-Update-Updater";
Alex Deymo14ad88e2016-06-29 12:30:14 -0700115
Alex Deymob3fa53b2016-04-18 19:57:58 -0700116// updatecheck attributes (without the underscore prefix).
Amin Hassani6600a562018-09-24 15:17:19 -0700117constexpr char kAttrEol[] = "eol";
118constexpr char kAttrRollback[] = "rollback";
119constexpr char kAttrFirmwareVersion[] = "firmware_version";
120constexpr char kAttrKernelVersion[] = "kernel_version";
Alex Deymob3fa53b2016-04-18 19:57:58 -0700121
Alex Deymoac41a822015-09-15 20:52:53 -0700122namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000123
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700124// Returns an XML ping element attribute assignment with attribute
125// |name| and value |ping_days| if |ping_days| has a value that needs
126// to be sent, or an empty string otherwise.
127string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700128 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -0700129 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700130 return "";
131}
132
133// Returns an XML ping element if any of the elapsed days need to be
134// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700135string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700136 string ping_active = GetPingAttribute("a", ping_active_days);
137 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
138 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700139 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700140 ping_active.c_str(),
141 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700142 }
143 return "";
144}
145
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700146// Returns an XML that goes into the body of the <app> element of the Omaha
147// request based on the given parameters.
148string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700149 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700150 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700151 bool include_ping,
Xiaochu Liu6310be62018-10-11 15:09:03 -0700152 bool skip_updatecheck,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700153 int ping_active_days,
154 int ping_roll_call_days,
155 PrefsInterface* prefs) {
156 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700157 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700158 if (include_ping)
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800159 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700160 if (!ping_only) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700161 if (!skip_updatecheck) {
162 app_body += " <updatecheck";
163 if (!params->target_version_prefix().empty()) {
164 app_body += base::StringPrintf(
165 " targetversionprefix=\"%s\"",
166 XmlEncodeWithDefault(params->target_version_prefix(), "")
167 .c_str());
168 // Rollback requires target_version_prefix set.
169 if (params->rollback_allowed()) {
170 app_body += " rollback_allowed=\"true\"";
171 }
Marton Hunyadyba51c3f2018-04-25 15:18:10 +0200172 }
Xiaochu Liu6310be62018-10-11 15:09:03 -0700173 app_body += "></updatecheck>\n";
Marton Hunyadyba51c3f2018-04-25 15:18:10 +0200174 }
Jay Srinivasan0a708742012-03-20 11:26:12 -0700175
Darin Petkov265f2902011-05-09 15:17:40 -0700176 // If this is the first update check after a reboot following a previous
177 // update, generate an event containing the previous version number. If
178 // the previous version preference file doesn't exist the event is still
179 // generated with a previous version of 0.0.0.0 -- this is relevant for
180 // older clients or new installs. The previous version event is not sent
181 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700182 // rebooted. The previous version event is also not sent if it was already
183 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700184 string prev_version;
185 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
186 prev_version = "0.0.0.0";
187 }
Alex Deymo87c08862015-10-30 21:56:55 -0700188 // We only store a non-empty previous version value after a successful
189 // update in the previous boot. After reporting it back to the server,
190 // we clear the previous version value so it doesn't get reported again.
191 if (!prev_version.empty()) {
192 app_body += base::StringPrintf(
193 " <event eventtype=\"%d\" eventresult=\"%d\" "
194 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800195 OmahaEvent::kTypeRebootedAfterUpdate,
196 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700197 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
198 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
199 << "Unable to reset the previous version.";
200 }
Darin Petkov95508da2011-01-05 12:42:29 -0800201 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700202 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800203 // The error code is an optional attribute so append it only if the result
204 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700205 string error_code;
206 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700207 error_code = base::StringPrintf(" errorcode=\"%d\"",
208 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700209 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700210 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700211 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800212 event->type,
213 event->result,
214 error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700215 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700216
217 return app_body;
218}
219
Alex Deymo8e18f932015-03-27 16:16:59 -0700220// Returns the cohort* argument to include in the <app> tag for the passed
221// |arg_name| and |prefs_key|, if any. The return value is suitable to
222// concatenate to the list of arguments and includes a space at the end.
223string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700224 const string arg_name,
225 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700226 // There's nothing wrong with not having a given cohort setting, so we check
Sen Jiang771f6482018-04-04 17:59:10 -0700227 // existence first to avoid the warning log message.
Alex Deymo8e18f932015-03-27 16:16:59 -0700228 if (!prefs->Exists(prefs_key))
229 return "";
230 string cohort_value;
231 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
232 return "";
233 // This is a sanity check to avoid sending a huge XML file back to Ohama due
234 // to a compromised stateful partition making the update check fail in low
235 // network environments envent after a reboot.
236 if (cohort_value.size() > 1024) {
237 LOG(WARNING) << "The omaha cohort setting " << arg_name
238 << " has a too big value, which must be an error or an "
239 "attacker trying to inhibit updates.";
240 return "";
241 }
242
Alex Deymob0d74eb2015-03-30 17:59:17 -0700243 string escaped_xml_value;
244 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
245 LOG(WARNING) << "The omaha cohort setting " << arg_name
246 << " is ASCII-7 invalid, ignoring it.";
247 return "";
248 }
249
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800250 return base::StringPrintf(
251 "%s=\"%s\" ", arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700252}
253
Sen Jiang94a4dec2017-03-28 18:23:35 -0700254struct OmahaAppData {
255 string id;
256 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700257 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700258};
259
Sen Jiang684c9cd2017-10-17 16:26:45 -0700260bool IsValidComponentID(const string& id) {
261 for (char c : id) {
262 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
263 return false;
264 }
265 return true;
266}
267
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700268// Returns an XML that corresponds to the entire <app> node of the Omaha
269// request based on the given parameters.
270string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700271 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700272 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700273 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700274 bool include_ping,
Xiaochu Liu6310be62018-10-11 15:09:03 -0700275 bool skip_updatecheck,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700276 int ping_active_days,
277 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800278 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700279 SystemState* system_state) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700280 string app_body = GetAppBody(event,
281 params,
282 ping_only,
283 include_ping,
284 skip_updatecheck,
285 ping_active_days,
286 ping_roll_call_days,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700287 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700288 string app_versions;
289
Sen Jiang8cd42342018-01-31 12:06:59 -0800290 // If we are downgrading to a more stable channel and we are allowed to do
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700291 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
292 // highest-versioned payload on the destination channel.
Sen Jiang8500d3a2018-02-08 12:04:05 -0800293 if (params->ShouldPowerwash()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700294 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
295 << "on downgrading to the version in the more stable channel";
296 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700297 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700298 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700299 app_versions = "version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700300 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700301 }
302
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700303 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700304 string app_channels =
305 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
306 if (params->current_channel() != download_channel) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800307 app_channels += "from_track=\"" +
308 XmlEncodeWithDefault(params->current_channel(), "") + "\" ";
Alex Deymob0d74eb2015-03-30 17:59:17 -0700309 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700310
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700311 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700312
David Zeuthen639aa362014-02-03 16:23:44 -0800313 // If install_date_days is not set (e.g. its value is -1 ), don't
314 // include the attribute.
315 string install_date_in_days_str = "";
316 if (install_date_in_days >= 0) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800317 install_date_in_days_str =
318 base::StringPrintf("installdate=\"%d\" ", install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800319 }
320
Alex Deymo8e18f932015-03-27 16:16:59 -0700321 string app_cohort_args;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800322 app_cohort_args +=
323 GetCohortArgXml(system_state->prefs(), "cohort", kPrefsOmahaCohort);
324 app_cohort_args += GetCohortArgXml(
325 system_state->prefs(), "cohorthint", kPrefsOmahaCohortHint);
326 app_cohort_args += GetCohortArgXml(
327 system_state->prefs(), "cohortname", kPrefsOmahaCohortName);
Alex Deymo8e18f932015-03-27 16:16:59 -0700328
Alex Deymoebf6e122017-03-10 16:12:01 -0800329 string fingerprint_arg;
330 if (!params->os_build_fingerprint().empty()) {
Sen Jiang8cd42342018-01-31 12:06:59 -0800331 fingerprint_arg = "fingerprint=\"" +
332 XmlEncodeWithDefault(params->os_build_fingerprint(), "") +
333 "\" ";
Alex Deymoebf6e122017-03-10 16:12:01 -0800334 }
335
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700336 string buildtype_arg;
337 if (!params->os_build_type().empty()) {
338 buildtype_arg = "os_build_type=\"" +
339 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
340 }
341
Sen Jiang684c9cd2017-10-17 16:26:45 -0700342 string product_components_args;
Sen Jiang8500d3a2018-02-08 12:04:05 -0800343 if (!params->ShouldPowerwash() && !app_data.product_components.empty()) {
Sen Jiang684c9cd2017-10-17 16:26:45 -0700344 brillo::KeyValueStore store;
345 if (store.LoadFromString(app_data.product_components)) {
346 for (const string& key : store.GetKeys()) {
347 if (!IsValidComponentID(key)) {
348 LOG(ERROR) << "Invalid component id: " << key;
349 continue;
350 }
351 string version;
352 if (!store.GetString(key, &version)) {
353 LOG(ERROR) << "Failed to get version for " << key
354 << " in product_components.";
355 continue;
356 }
357 product_components_args +=
358 base::StringPrintf("_%s.version=\"%s\" ",
359 key.c_str(),
360 XmlEncodeWithDefault(version, "").c_str());
361 }
362 } else {
363 LOG(ERROR) << "Failed to parse product_components:\n"
364 << app_data.product_components;
365 }
366 }
367
368 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700369 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700370 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700371 app_cohort_args +
372 app_versions +
373 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700374 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800375 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700376 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700377 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
378 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
379 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
380 "delta_okay=\"" + delta_okay_str + "\" "
381 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
382 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
383 install_date_in_days_str +
384 ">\n" +
385 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700386 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700387 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700388 return app_xml;
389}
390
391// Returns an XML that corresponds to the entire <os> node of the Omaha
392// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700393string GetOsXml(OmahaRequestParams* params) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800394 string os_xml =
395 " <os "
396 "version=\"" +
397 XmlEncodeWithDefault(params->os_version(), "") + "\" " + "platform=\"" +
398 XmlEncodeWithDefault(params->os_platform(), "") + "\" " + "sp=\"" +
399 XmlEncodeWithDefault(params->os_sp(), "") +
400 "\">"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700401 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700402 return os_xml;
403}
404
405// Returns an XML that corresponds to the entire Omaha request based on the
406// given parameters.
407string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700408 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700409 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700410 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700411 int ping_active_days,
412 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800413 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700414 SystemState* system_state) {
415 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700416 OmahaAppData product_app = {
417 .id = params->GetAppId(),
418 .version = params->app_version(),
419 .product_components = params->product_components()};
Xiaochu Liu6310be62018-10-11 15:09:03 -0700420 // Skips updatecheck for platform app in case of an install operation.
Sen Jiang94a4dec2017-03-28 18:23:35 -0700421 string app_xml = GetAppXml(event,
422 params,
423 product_app,
424 ping_only,
425 include_ping,
Xiaochu Liu6310be62018-10-11 15:09:03 -0700426 params->is_install(), /* skip_updatecheck */
Sen Jiang94a4dec2017-03-28 18:23:35 -0700427 ping_active_days,
428 ping_roll_call_days,
429 install_date_in_days,
430 system_state);
431 if (!params->system_app_id().empty()) {
432 OmahaAppData system_app = {.id = params->system_app_id(),
433 .version = params->system_version()};
434 app_xml += GetAppXml(event,
435 params,
436 system_app,
437 ping_only,
438 include_ping,
Xiaochu Liu6310be62018-10-11 15:09:03 -0700439 false, /* skip_updatecheck */
Sen Jiang94a4dec2017-03-28 18:23:35 -0700440 ping_active_days,
441 ping_roll_call_days,
442 install_date_in_days,
443 system_state);
444 }
Xiaochu Liuf53a5d32018-11-26 13:48:59 -0800445 // Create APP ID according to |dlc_module_id| (sticking the current AppID to
446 // the DLC module ID with an underscode).
447 for (const auto& dlc_module_id : params->dlc_module_ids()) {
448 OmahaAppData dlc_module_app = {
449 .id = params->GetAppId() + "_" + dlc_module_id,
450 .version = params->app_version()};
Xiaochu Liu88d90382018-08-29 16:09:11 -0700451 app_xml += GetAppXml(event,
452 params,
Xiaochu Liuf53a5d32018-11-26 13:48:59 -0800453 dlc_module_app,
Xiaochu Liu88d90382018-08-29 16:09:11 -0700454 ping_only,
455 include_ping,
Xiaochu Liu6310be62018-10-11 15:09:03 -0700456 false, /* skip_updatecheck */
Xiaochu Liu88d90382018-08-29 16:09:11 -0700457 ping_active_days,
458 ping_roll_call_days,
459 install_date_in_days,
460 system_state);
461 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700462
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800463 string install_source = base::StringPrintf(
464 "installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700465 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700466
Alex Deymoac41a822015-09-15 20:52:53 -0700467 string updater_version = XmlEncodeWithDefault(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800468 base::StringPrintf(
469 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion),
470 "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700471 string request_xml =
472 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800473 "<request protocol=\"3.0\" " +
474 ("version=\"" + updater_version +
475 "\" "
476 "updaterversion=\"" +
477 updater_version + "\" " + install_source + "ismachine=\"1\">\n") +
478 os_xml + app_xml + "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700479
480 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000481}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700482
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700483} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000484
David Zeuthene8ed8632014-07-24 13:38:10 -0400485// Struct used for holding data obtained when parsing the XML.
486struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400487 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
488
489 // Pointer to the expat XML_Parser object.
490 XML_Parser xml_parser;
491
David Zeuthene8ed8632014-07-24 13:38:10 -0400492 // This is the state of the parser as it's processing the XML.
493 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400494 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400495 string current_path;
496
497 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400498 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700499 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400500 string daystart_elapsed_days;
501 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800502
Sen Jiang81259682017-03-30 15:11:30 -0700503 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700504 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700505 vector<string> url_codebase;
506 string manifest_version;
507 map<string, string> action_postinstall_attrs;
508 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700509 string cohort;
510 string cohorthint;
511 string cohortname;
512 bool cohort_set = false;
513 bool cohorthint_set = false;
514 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700515
516 struct Package {
517 string name;
518 string size;
519 string hash;
520 };
521 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800522 };
Sen Jiang81259682017-03-30 15:11:30 -0700523 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400524};
525
526namespace {
527
528// Callback function invoked by expat.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800529void ParserHandlerStart(void* user_data,
530 const XML_Char* element,
David Zeuthene8ed8632014-07-24 13:38:10 -0400531 const XML_Char** attr) {
532 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
533
534 if (data->failed)
535 return;
536
537 data->current_path += string("/") + element;
538
539 map<string, string> attrs;
540 if (attr != nullptr) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800541 for (int n = 0; attr[n] != nullptr && attr[n + 1] != nullptr; n += 2) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400542 string key = attr[n];
543 string value = attr[n + 1];
544 attrs[key] = value;
545 }
546 }
547
Alex Deymo8e18f932015-03-27 16:16:59 -0700548 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700549 OmahaParserData::App app;
Amin Hassani6600a562018-09-24 15:17:19 -0700550 if (attrs.find(kAttrAppId) != attrs.end()) {
551 app.id = attrs[kAttrAppId];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700552 }
Amin Hassani6600a562018-09-24 15:17:19 -0700553 if (attrs.find(kAttrCohort) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700554 app.cohort_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700555 app.cohort = attrs[kAttrCohort];
Alex Deymo8e18f932015-03-27 16:16:59 -0700556 }
Amin Hassani6600a562018-09-24 15:17:19 -0700557 if (attrs.find(kAttrCohortHint) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700558 app.cohorthint_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700559 app.cohorthint = attrs[kAttrCohortHint];
Alex Deymo8e18f932015-03-27 16:16:59 -0700560 }
Amin Hassani6600a562018-09-24 15:17:19 -0700561 if (attrs.find(kAttrCohortName) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700562 app.cohortname_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700563 app.cohortname = attrs[kAttrCohortName];
Alex Deymo8e18f932015-03-27 16:16:59 -0700564 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700565 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700566 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700567 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700568 data->apps.back().updatecheck_status = attrs[kAttrStatus];
Sen Jiang81259682017-03-30 15:11:30 -0700569 if (data->updatecheck_poll_interval.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700570 data->updatecheck_poll_interval = attrs[kAttrPollInterval];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700571 // Omaha sends arbitrary key-value pairs as extra attributes starting with
572 // an underscore.
573 for (const auto& attr : attrs) {
574 if (!attr.first.empty() && attr.first[0] == '_')
575 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
576 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400577 } else if (data->current_path == "/response/daystart") {
578 // Get the install-date.
Amin Hassani6600a562018-09-24 15:17:19 -0700579 data->daystart_elapsed_days = attrs[kAttrElapsedDays];
580 data->daystart_elapsed_seconds = attrs[kAttrElapsedSeconds];
David Zeuthene8ed8632014-07-24 13:38:10 -0400581 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
582 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700583 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700584 data->apps.back().url_codebase.push_back(attrs[kAttrCodeBase]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800585 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400586 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800587 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700588 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700589 data->apps.back().packages.push_back({.name = attrs[kAttrName],
590 .size = attrs[kAttrSize],
591 .hash = attrs[kAttrHashSha256]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400592 } else if (data->current_path == "/response/app/updatecheck/manifest") {
593 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700594 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700595 data->apps.back().manifest_version = attrs[kAttrVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400596 } else if (data->current_path ==
597 "/response/app/updatecheck/manifest/actions/action") {
598 // We only care about the postinstall action.
Amin Hassani6600a562018-09-24 15:17:19 -0700599 if (attrs[kAttrEvent] == kValPostInstall && !data->apps.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700600 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400601 }
602 }
603}
604
605// Callback function invoked by expat.
606void ParserHandlerEnd(void* user_data, const XML_Char* element) {
607 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
608 if (data->failed)
609 return;
610
611 const string path_suffix = string("/") + element;
612
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800613 if (!base::EndsWith(
614 data->current_path, path_suffix, base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400615 LOG(ERROR) << "Unexpected end element '" << element
616 << "' with current_path='" << data->current_path << "'";
617 data->failed = true;
618 return;
619 }
620 data->current_path.resize(data->current_path.size() - path_suffix.size());
621}
622
David Zeuthenf3e28012014-08-26 18:23:52 -0400623// Callback function invoked by expat.
624//
625// This is called for entity declarations. Since Omaha is guaranteed
626// to never return any XML with entities our course of action is to
627// just stop parsing. This avoids potential resource exhaustion
628// problems AKA the "billion laughs". CVE-2013-0340.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800629void ParserHandlerEntityDecl(void* user_data,
630 const XML_Char* entity_name,
David Zeuthenf3e28012014-08-26 18:23:52 -0400631 int is_parameter_entity,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800632 const XML_Char* value,
David Zeuthenf3e28012014-08-26 18:23:52 -0400633 int value_length,
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800634 const XML_Char* base,
635 const XML_Char* system_id,
636 const XML_Char* public_id,
637 const XML_Char* notation_name) {
David Zeuthenf3e28012014-08-26 18:23:52 -0400638 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
639
640 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
641 data->failed = true;
642 data->entity_decl = true;
643 XML_StopParser(data->xml_parser, false);
644}
645
David Zeuthene8ed8632014-07-24 13:38:10 -0400646} // namespace
647
Alex Deymob0d74eb2015-03-30 17:59:17 -0700648bool XmlEncode(const string& input, string* output) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800649 if (std::find_if(input.begin(), input.end(), [](const char c) {
650 return c & 0x80;
651 }) != input.end()) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700652 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
653 utils::HexDumpString(input);
654 return false;
655 }
Alex Deymocc457852015-06-18 18:35:50 -0700656 output->clear();
657 // We need at least input.size() space in the output, but the code below will
658 // handle it if we need more.
659 output->reserve(input.size());
660 for (char c : input) {
661 switch (c) {
662 case '\"':
663 output->append("&quot;");
664 break;
665 case '\'':
666 output->append("&apos;");
667 break;
668 case '&':
669 output->append("&amp;");
670 break;
671 case '<':
672 output->append("&lt;");
673 break;
674 case '>':
675 output->append("&gt;");
676 break;
677 default:
678 output->push_back(c);
679 }
680 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700681 return true;
682}
683
684string XmlEncodeWithDefault(const string& input, const string& default_value) {
685 string output;
686 if (XmlEncode(input, &output))
687 return output;
688 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000689}
690
Alex Deymoc1c17b42015-11-23 03:53:15 -0300691OmahaRequestAction::OmahaRequestAction(
692 SystemState* system_state,
693 OmahaEvent* event,
694 std::unique_ptr<HttpFetcher> http_fetcher,
695 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800696 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800697 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700698 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300699 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800700 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700701 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700702 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700703 ping_roll_call_days_(0) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800704 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700705}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000706
Darin Petkov6a5b3222010-07-13 14:55:28 -0700707OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000708
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700709// Calculates the value to use for the ping days parameter.
710int OmahaRequestAction::CalculatePingDays(const string& key) {
711 int days = kNeverPinged;
712 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800713 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700714 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
715 if (days < 0) {
716 // If |days| is negative, then the system clock must have jumped
717 // back in time since the ping was sent. Mark the value so that
718 // it doesn't get sent to the server but we still update the
719 // last ping daystart preference. This way the next ping time
720 // will be correct, hopefully.
721 days = kPingTimeJump;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800722 LOG(WARNING)
723 << "System clock jumped back in time. Resetting ping daystarts.";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700724 }
725 }
726 return days;
727}
728
729void OmahaRequestAction::InitPingDays() {
730 // We send pings only along with update checks, not with events.
731 if (IsEvent()) {
732 return;
733 }
734 // TODO(petkov): Figure a way to distinguish active use pings
735 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700736 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700737 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
738 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
739}
740
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700741bool OmahaRequestAction::ShouldPing() const {
742 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
743 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
744 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
745 if (powerwash_count > 0) {
746 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
747 << "powerwash_count is " << powerwash_count;
748 return false;
749 }
Amin Hassani1677e812017-06-21 13:36:36 -0700750 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
751 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
752 << "the first_active_omaha_ping_sent is true";
753 return false;
754 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700755 return true;
756 }
757 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
758}
759
David Zeuthen639aa362014-02-03 16:23:44 -0800760// static
761int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
762 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700763 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800764 return -1;
765
766 // If we have the value stored on disk, just return it.
767 int64_t stored_value;
768 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
769 // Convert and sanity-check.
770 int install_date_days = static_cast<int>(stored_value);
771 if (install_date_days >= 0)
772 return install_date_days;
773 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
774 << install_date_days << " looks suspicious.";
775 prefs->Delete(kPrefsInstallDateDays);
776 }
777
778 // Otherwise, if OOBE is not complete then do nothing and wait for
779 // ParseResponse() to call ParseInstallDate() and then
780 // PersistInstallDate() to set the kPrefsInstallDateDays state
781 // variable. Once that is done, we'll then report back in future
782 // Omaha requests. This works exactly because OOBE triggers an
783 // update check.
784 //
785 // However, if OOBE is complete and the kPrefsInstallDateDays state
786 // variable is not set, there are two possibilities
787 //
788 // 1. The update check in OOBE failed so we never got a response
789 // from Omaha (no network etc.); or
790 //
791 // 2. OOBE was done on an older version that didn't write to the
792 // kPrefsInstallDateDays state variable.
793 //
794 // In both cases, we approximate the install date by simply
795 // inspecting the timestamp of when OOBE happened.
796
797 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700798 if (!system_state->hardware()->IsOOBEEnabled() ||
799 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800800 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700801 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800802 return -1;
803 }
804
805 int num_days;
806 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
807 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
808 << "as its value '" << utils::ToString(time_of_oobe)
809 << "' looks suspicious.";
810 return -1;
811 }
812
813 // Persist this to disk, for future use.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800814 if (!OmahaRequestAction::PersistInstallDate(
815 system_state, num_days, kProvisionedFromOOBEMarker))
David Zeuthen639aa362014-02-03 16:23:44 -0800816 return -1;
817
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800818 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to " << num_days
819 << " days";
David Zeuthen639aa362014-02-03 16:23:44 -0800820
821 return num_days;
822}
823
Darin Petkov6a5b3222010-07-13 14:55:28 -0700824void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000825 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700826 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700827 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700828 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700829 return;
830 }
David Zeuthen639aa362014-02-03 16:23:44 -0800831
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700832 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700833 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700834 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700835 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700836 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800837 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800838 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700839 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700840
Sen Jiang42fa45e2018-03-12 11:02:14 -0700841 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700842 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
843 params_->interactive() ? "fg" : "bg");
844 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
845 http_fetcher_->SetHeader(
846 kXGoogleUpdateUpdater,
847 base::StringPrintf(
848 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
849
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800850 http_fetcher_->SetPostData(
851 request_post.data(), request_post.size(), kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700852 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700853 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700854 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000855}
856
Darin Petkov6a5b3222010-07-13 14:55:28 -0700857void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000858 http_fetcher_->TerminateTransfer();
859}
860
861// We just store the response in the buffer. Once we've received all bytes,
862// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700863bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800864 const void* bytes,
865 size_t length) {
866 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
867 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700868 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000869}
870
871namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000872
873// Parses a 64 bit base-10 int from a string and returns it. Returns 0
874// on error. If the string contains "0", that's indistinguishable from
875// error.
876off_t ParseInt(const string& str) {
877 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700878 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000879 if (rc < 1) {
880 // failure
881 return 0;
882 }
883 return ret;
884}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700885
David Zeuthene8ed8632014-07-24 13:38:10 -0400886// Parses |str| and returns |true| if, and only if, its value is "true".
887bool ParseBool(const string& str) {
888 return str == "true";
889}
890
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700891// Update the last ping day preferences based on the server daystart
892// response. Returns true on success, false otherwise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800893bool UpdateLastPingDays(OmahaParserData* parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700894 int64_t elapsed_seconds = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800895 TEST_AND_RETURN_FALSE(base::StringToInt64(
896 parser_data->daystart_elapsed_seconds, &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700897 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
898
899 // Remember the local time that matches the server's last midnight
900 // time.
901 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
902 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
903 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
904 return true;
905}
Sen Jiang81259682017-03-30 15:11:30 -0700906
907// Parses the package node in the given XML document and populates
908// |output_object| if valid. Returns true if we should continue the parsing.
909// False otherwise, in which case it sets any error code using |completer|.
910bool ParsePackage(OmahaParserData::App* app,
911 OmahaResponse* output_object,
912 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700913 if (app->updatecheck_status.empty() ||
914 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700915 if (!app->packages.empty()) {
916 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
917 completer->set_code(ErrorCode::kOmahaResponseInvalid);
918 return false;
919 }
920 return true;
921 }
922 if (app->packages.empty()) {
923 LOG(ERROR) << "Omaha Response has no packages";
924 completer->set_code(ErrorCode::kOmahaResponseInvalid);
925 return false;
926 }
927 if (app->url_codebase.empty()) {
928 LOG(ERROR) << "No Omaha Response URLs";
929 completer->set_code(ErrorCode::kOmahaResponseInvalid);
930 return false;
931 }
932 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
933 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700934 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700935 ":",
936 base::TRIM_WHITESPACE,
937 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700938 vector<string> metadata_signatures = base::SplitString(
939 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
940 ":",
941 base::TRIM_WHITESPACE,
942 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700943 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700944 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700945 ":",
946 base::TRIM_WHITESPACE,
947 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700948 for (size_t i = 0; i < app->packages.size(); i++) {
949 const auto& package = app->packages[i];
950 if (package.name.empty()) {
951 LOG(ERROR) << "Omaha Response has empty package name";
952 completer->set_code(ErrorCode::kOmahaResponseInvalid);
953 return false;
954 }
955 LOG(INFO) << "Found package " << package.name;
956
957 OmahaResponse::Package out_package;
958 for (const string& codebase : app->url_codebase) {
959 if (codebase.empty()) {
960 LOG(ERROR) << "Omaha Response URL has empty codebase";
961 completer->set_code(ErrorCode::kOmahaResponseInvalid);
962 return false;
963 }
964 out_package.payload_urls.push_back(codebase + package.name);
965 }
966 // Parse the payload size.
967 base::StringToUint64(package.size, &out_package.size);
968 if (out_package.size <= 0) {
969 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
970 completer->set_code(ErrorCode::kOmahaResponseInvalid);
971 return false;
972 }
973 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
974
975 if (i < metadata_sizes.size())
976 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
977 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
978 << " bytes";
979
980 if (i < metadata_signatures.size())
981 out_package.metadata_signature = metadata_signatures[i];
982 LOG(INFO) << "Payload metadata signature = "
983 << out_package.metadata_signature;
984
985 out_package.hash = package.hash;
986 if (out_package.hash.empty()) {
987 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
988 completer->set_code(ErrorCode::kOmahaResponseInvalid);
989 return false;
990 }
991 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700992
993 if (i < is_delta_payloads.size())
994 out_package.is_delta = ParseBool(is_delta_payloads[i]);
995 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
996
Sen Jiang81259682017-03-30 15:11:30 -0700997 output_object->packages.push_back(std::move(out_package));
998 }
999
1000 return true;
1001}
1002
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001003// Parses the 2 key version strings kernel_version and firmware_version. If the
1004// field is not present, or cannot be parsed the values default to 0xffff.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001005void ParseRollbackVersions(int allowed_milestones,
1006 OmahaParserData* parser_data,
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001007 OmahaResponse* output_object) {
1008 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -07001009 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001010 &output_object->rollback_key_version.firmware_key,
1011 &output_object->rollback_key_version.firmware);
1012 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -07001013 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001014 &output_object->rollback_key_version.kernel_key,
1015 &output_object->rollback_key_version.kernel);
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001016
1017 // Create the attribute name strings for milestone N - allowed_milestones.
1018 const string firmware_max_rollforward_attr =
1019 base::StringPrintf("%s_%i", kAttrFirmwareVersion, allowed_milestones);
1020 const string kernel_max_rollforward_attr =
1021 base::StringPrintf("%s_%i", kAttrKernelVersion, allowed_milestones);
1022
1023 const bool max_firmware_and_kernel_exist =
1024 parser_data->updatecheck_attrs.count(firmware_max_rollforward_attr) > 0 &&
1025 parser_data->updatecheck_attrs.count(kernel_max_rollforward_attr) > 0;
1026
1027 string firmware_version;
1028 string kernel_version;
1029 if (max_firmware_and_kernel_exist) {
1030 firmware_version =
1031 parser_data->updatecheck_attrs[firmware_max_rollforward_attr];
1032 kernel_version =
1033 parser_data->updatecheck_attrs[kernel_max_rollforward_attr];
1034 }
1035
1036 LOG(INFO) << "For milestone N-" << allowed_milestones
1037 << " firmware_key_version=" << firmware_version
1038 << " kernel_key_version=" << kernel_version;
1039
1040 OmahaResponse::RollbackKeyVersion version;
1041 utils::ParseRollbackKeyVersion(
1042 firmware_version, &version.firmware_key, &version.firmware);
1043 utils::ParseRollbackKeyVersion(
1044 kernel_version, &version.kernel_key, &version.kernel);
1045
1046 output_object->past_rollback_key_version = std::move(version);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001047}
1048
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001049} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +00001050
David Zeuthene8ed8632014-07-24 13:38:10 -04001051bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001052 OmahaResponse* output_object,
1053 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001054 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001055 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001056 return false;
1057 }
Sen Jiang81259682017-03-30 15:11:30 -07001058 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001059
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001060 // chromium-os:37289: The PollInterval is not supported by Omaha server
1061 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -07001062 // slow down the request rate from the server-side. Note that the PollInterval
1063 // is not persisted, so it has to be sent by the server on every response to
1064 // guarantee that the scheduler uses this value (otherwise, if the device got
1065 // rebooted after the last server-indicated value, it'll revert to the default
1066 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
1067 // based on the assumption that we perform an update check every hour so that
1068 // the max value of 8 will roughly be equivalent to one work day. If we decide
1069 // to use PollInterval permanently, we should update the
1070 // max_update_checks_allowed to take PollInterval into account. Note: The
1071 // parsing for PollInterval happens even before parsing of the status because
1072 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -04001073 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001074 &output_object->poll_interval);
1075
David Zeuthen639aa362014-02-03 16:23:44 -08001076 // Check for the "elapsed_days" attribute in the "daystart"
1077 // element. This is the number of days since Jan 1 2007, 0:00
1078 // PST. If we don't have a persisted value of the Omaha InstallDate,
1079 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -04001080 if (ParseInstallDate(parser_data, output_object) &&
1081 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -08001082 // Since output_object->install_date_days is never negative, the
1083 // elapsed_days -> install-date calculation is reduced to simply
1084 // rounding down to the nearest number divisible by 7.
1085 int remainder = output_object->install_date_days % 7;
1086 int install_date_days_rounded =
1087 output_object->install_date_days - remainder;
1088 if (PersistInstallDate(system_state_,
1089 install_date_days_rounded,
1090 kProvisionedFromOmahaResponse)) {
1091 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
1092 << install_date_days_rounded << " days";
1093 }
1094 }
1095
Alex Deymo00d79ac2015-06-29 15:41:49 -07001096 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -07001097 for (const auto& app : parser_data->apps) {
1098 if (app.id == params_->GetAppId()) {
1099 if (app.cohort_set)
1100 PersistCohortData(kPrefsOmahaCohort, app.cohort);
1101 if (app.cohorthint_set)
1102 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
1103 if (app.cohortname_set)
1104 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
1105 break;
1106 }
1107 }
Alex Deymo00d79ac2015-06-29 15:41:49 -07001108
Alex Deymob3fa53b2016-04-18 19:57:58 -07001109 // Parse the updatecheck attributes.
1110 PersistEolStatus(parser_data->updatecheck_attrs);
Marton Hunyady199152d2018-05-07 19:08:48 +02001111 // Rollback-related updatecheck attributes.
1112 // Defaults to false if attribute is not present.
1113 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -07001114 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001115
1116 // Parses the rollback versions of the current image. If the fields do not
1117 // exist they default to 0xffff for the 4 key versions.
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001118 ParseRollbackVersions(
1119 params_->rollback_allowed_milestones(), parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -07001120
David Zeuthene8ed8632014-07-24 13:38:10 -04001121 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001122 return false;
1123
David Zeuthene8ed8632014-07-24 13:38:10 -04001124 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001125 return false;
1126
Sen Jiang0affc2c2017-02-10 15:55:05 -08001127 // Package has to be parsed after Params now because ParseParams need to make
1128 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -07001129 for (auto& app : parser_data->apps)
1130 if (!ParsePackage(&app, output_object, completer))
1131 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001132
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001133 return true;
1134}
1135
David Zeuthene8ed8632014-07-24 13:38:10 -04001136bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001137 OmahaResponse* output_object,
1138 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001139 output_object->update_exists = false;
Xiaochu Liu6310be62018-10-11 15:09:03 -07001140 for (const auto& app : parser_data->apps) {
1141 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -07001142 if (status == kValNoUpdate) {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001143 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -07001144 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001145 output_object->update_exists = false;
1146 break;
Sen Jiang81259682017-03-30 15:11:30 -07001147 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -07001148 auto const& attr_no_update =
1149 app.action_postinstall_attrs.find(kAttrNoUpdate);
1150 if (attr_no_update != app.action_postinstall_attrs.end() &&
1151 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001152 // noupdate="true" in postinstall attributes means it's an update to
1153 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -07001154 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001155 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -07001156 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001157 output_object->update_exists = true;
1158 }
Xiaochu Liu6310be62018-10-11 15:09:03 -07001159 } else if (status.empty() && params_->is_install() &&
1160 params_->GetAppId() == app.id) {
1161 // Skips the platform app for install operation.
1162 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -07001163 } else {
1164 LOG(ERROR) << "Unknown Omaha response status: " << status;
1165 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1166 return false;
1167 }
1168 }
1169 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001170 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001171 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001172 }
1173
Sen Jiang81259682017-03-30 15:11:30 -07001174 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001175}
1176
David Zeuthene8ed8632014-07-24 13:38:10 -04001177bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001178 OmahaResponse* output_object,
1179 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001180 map<string, string> attrs;
1181 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001182 if (app.id == params_->GetAppId()) {
1183 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001184 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001185 } else if (!params_->system_app_id().empty() &&
1186 app.id == params_->system_app_id()) {
1187 // this is the system app (this check is intentionally skipped if there is
1188 // no system_app_id set)
1189 output_object->system_version = app.manifest_version;
Xiaochu Liu6310be62018-10-11 15:09:03 -07001190 } else if (params_->is_install() &&
1191 app.manifest_version != params_->app_version()) {
1192 LOG(WARNING) << "An app has a different version (" << app.manifest_version
1193 << ") that is different than platform app version ("
1194 << params_->app_version() << ")";
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001195 }
1196 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001197 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001198 }
Sen Jiang81259682017-03-30 15:11:30 -07001199 }
Xiaochu Liu6310be62018-10-11 15:09:03 -07001200 if (params_->is_install()) {
1201 LOG(INFO) << "Use request version for Install operation.";
1202 output_object->version = params_->app_version();
1203 }
Chris Sosa3b748432013-06-20 16:42:59 -07001204 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001205 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001206 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001207 return false;
1208 }
1209
1210 LOG(INFO) << "Received omaha response to update to version "
1211 << output_object->version;
1212
David Zeuthene8ed8632014-07-24 13:38:10 -04001213 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001214 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001215 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001216 return false;
1217 }
1218
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001219 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -07001220 output_object->more_info_url = attrs[kAttrMoreInfo];
1221 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
1222 output_object->deadline = attrs[kAttrDeadline];
1223 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001224 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -07001225 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001226 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -07001227 ParseBool(attrs[kAttrDisableP2PForSharing]);
1228 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001229
Amin Hassani6600a562018-09-24 15:17:19 -07001230 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001231 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001232 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001233
Jay Srinivasan08262882012-12-28 19:29:43 -08001234 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -07001235 ParseBool(attrs[kAttrDisablePayloadBackoff]);
1236 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001237
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001238 return true;
1239}
1240
David Zeuthene8ed8632014-07-24 13:38:10 -04001241// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001242// and fill in the appropriate fields of the output object. Also, notifies
1243// the processor that we're done.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001244void OmahaRequestAction::TransferComplete(HttpFetcher* fetcher,
Darin Petkov6a5b3222010-07-13 14:55:28 -07001245 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001246 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001247 string current_response(response_buffer_.begin(), response_buffer_.end());
1248 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001249
Gilad Arnold74b5f552014-10-07 08:17:16 -07001250 PayloadStateInterface* const payload_state = system_state_->payload_state();
1251
Zentaro Kavanagh76af2662018-05-15 10:54:53 -07001252 // Set the max kernel key version based on whether rollback is allowed.
1253 SetMaxKernelKeyVersionForRollback();
1254
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001255 // Events are best effort transactions -- assume they always succeed.
1256 if (IsEvent()) {
1257 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001258 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001259 return;
1260 }
1261
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001262 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001263 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001264 int code = GetHTTPResponseCode();
1265 // Makes sure we send sane error values.
1266 if (code < 0 || code >= 1000) {
1267 code = 999;
1268 }
David Zeuthena99981f2013-04-29 13:42:47 -07001269 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001270 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001271 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001272 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001273
David Zeuthene8ed8632014-07-24 13:38:10 -04001274 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001275 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001276 XML_SetUserData(parser, &parser_data);
1277 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001278 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001279 XML_Status res =
1280 XML_Parse(parser,
1281 reinterpret_cast<const char*>(response_buffer_.data()),
1282 response_buffer_.size(),
1283 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001284
1285 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001286 LOG(ERROR) << "Omaha response not valid XML: "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001287 << XML_ErrorString(XML_GetErrorCode(parser)) << " at line "
1288 << XML_GetCurrentLineNumber(parser) << " col "
1289 << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -07001290 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001291 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1292 if (response_buffer_.empty()) {
1293 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1294 } else if (parser_data.entity_decl) {
1295 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1296 }
1297 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001298 return;
1299 }
Amin Hassani91f48b42018-08-06 17:47:14 -07001300 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001301
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001302 // Update the last ping day preferences based on the server daystart response
1303 // even if we didn't send a ping. Omaha always includes the daystart in the
1304 // response, but log the error if it didn't.
1305 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1306 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001307
Amin Hassani1677e812017-06-21 13:36:36 -07001308 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1309 // we have got a response from omaha and if its value has never been set to
1310 // true before. Failure of this function should be ignored. There should be no
1311 // need to check if a=-1 has been sent because older devices have already sent
1312 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1313 // future checks.
1314 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -07001315 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
1316 system_state_->metrics_reporter()->ReportInternalErrorCode(
1317 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
1318 }
Amin Hassani1677e812017-06-21 13:36:36 -07001319 }
1320
Thieu Le116fda32011-04-19 11:01:54 -07001321 if (!HasOutputPipe()) {
1322 // Just set success to whether or not the http transfer succeeded,
1323 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001324 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001325 return;
1326 }
1327
Darin Petkov6a5b3222010-07-13 14:55:28 -07001328 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001329 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001330 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001331 output_object.update_exists = true;
1332 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001333
Toni Barzic61544e62018-10-11 14:37:30 -07001334 LoadOrPersistUpdateFirstSeenAtPref();
1335
Weidong Guo421ff332017-04-17 10:08:38 -07001336 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -07001337 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -07001338 // No need to change output_object.update_exists here, since the value
1339 // has been output to the pipe.
1340 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001341 return;
1342 }
1343
David Zeuthen8f191b22013-08-06 12:27:50 -07001344 // If Omaha says to disable p2p, respect that
1345 if (output_object.disable_p2p_for_downloading) {
1346 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1347 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001348 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001349 }
1350 if (output_object.disable_p2p_for_sharing) {
1351 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1352 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001353 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001354 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001355
1356 // Update the payload state with the current response. The payload state
1357 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001358 // from what's stored already. We are updating the payload state as late
1359 // as possible in this method so that if a new release gets pushed and then
1360 // got pulled back due to some issues, we don't want to clear our internal
1361 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001362 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001363
David Zeuthen8f191b22013-08-06 12:27:50 -07001364 // It could be we've already exceeded the deadline for when p2p is
1365 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001366 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001367 payload_state->P2PNewAttempt();
1368 if (!payload_state->P2PAttemptAllowed()) {
1369 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1370 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001371 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001372 }
1373 }
1374
1375 // From here on, we'll complete stuff in CompleteProcessing() so
1376 // disable |completer| since we'll create a new one in that
1377 // function.
1378 completer.set_should_complete(false);
1379
1380 // If we're allowed to use p2p for downloading we do not pay
1381 // attention to wall-clock-based waiting if the URL is indeed
1382 // available via p2p. Therefore, check if the file is available via
1383 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001384 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001385 LookupPayloadViaP2P(output_object);
1386 } else {
1387 CompleteProcessing();
1388 }
1389}
1390
1391void OmahaRequestAction::CompleteProcessing() {
1392 ScopedActionCompleter completer(processor_, this);
1393 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1394 PayloadStateInterface* payload_state = system_state_->payload_state();
1395
1396 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001397 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001398 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001399 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001400 return;
1401 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001402
Chris Sosa20f005c2013-09-05 13:53:08 -07001403 if (payload_state->ShouldBackoffDownload()) {
1404 output_object.update_exists = false;
1405 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1406 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001407 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001408 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001409 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001410 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001411}
1412
1413void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1414 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1415 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001416 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001417 } else {
1418 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1419 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001420 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001421 }
1422 CompleteProcessing();
1423}
1424
1425void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001426 // If the device is in the middle of an update, the state variables
1427 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1428 // tracks the offset and length of the operation currently in
1429 // progress. The offset is based from the end of the manifest which
1430 // is kPrefsManifestMetadataSize bytes long.
1431 //
1432 // To make forward progress and avoid deadlocks, we need to find a
1433 // peer that has at least the entire operation we're currently
1434 // working on. Otherwise we may end up in a situation where two
1435 // devices bounce back and forth downloading from each other,
1436 // neither making any forward progress until one of them decides to
1437 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1438 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001439 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001440 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001441 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001442 int64_t next_data_offset = 0;
1443 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001444 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001445 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1446 &manifest_metadata_size) &&
1447 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001448 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1449 &manifest_signature_size) &&
1450 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001451 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001452 &next_data_offset) &&
1453 next_data_offset != -1 &&
1454 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1455 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001456 minimum_size = manifest_metadata_size + manifest_signature_size +
1457 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001458 }
1459
Sen Jiang0affc2c2017-02-10 15:55:05 -08001460 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001461 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001462 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001463 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001464 string file_id =
1465 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001466 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001467 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1468 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001469 system_state_->p2p_manager()->LookupUrlForFile(
1470 file_id,
1471 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001472 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001473 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1474 base::Unretained(this)));
1475 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001476}
1477
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001478bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001479 if (params_->interactive()) {
1480 LOG(INFO) << "Not deferring download because update is interactive.";
1481 return false;
1482 }
1483
David Zeuthen8f191b22013-08-06 12:27:50 -07001484 // If we're using p2p to download _and_ we have a p2p URL, we never
1485 // defer the download. This is because the download will always
1486 // happen from a peer on the LAN and we've been waiting in line for
1487 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001488 const PayloadStateInterface* payload_state = system_state_->payload_state();
1489 if (payload_state->GetUsingP2PForDownloading() &&
1490 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001491 LOG(INFO) << "Download not deferred because download "
1492 << "will happen from a local peer (via p2p).";
1493 return false;
1494 }
1495
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001496 // We should defer the downloads only if we've first satisfied the
1497 // wall-clock-based-waiting period and then the update-check-based waiting
1498 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001499 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001500 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1501 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001502 return false;
1503 }
1504
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001505 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001506 case kWallClockWaitNotSatisfied:
1507 // We haven't even satisfied the first condition, passing the
1508 // wall-clock-based waiting period, so we should defer the downloads
1509 // until that happens.
1510 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1511 return true;
1512
1513 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1514 LOG(INFO) << "wall-clock-based-wait satisfied and "
1515 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001516 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001517
1518 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1519 // Wall-clock-based waiting period is satisfied, and it's determined
1520 // that we do not need the update-check-based wait. so no need to
1521 // defer downloads.
1522 LOG(INFO) << "wall-clock-based-wait satisfied and "
1523 << "update-check-based-wait is not required.";
1524 return false;
1525
1526 default:
1527 // Returning false for this default case so we err on the
1528 // side of downloading updates than deferring in case of any bugs.
1529 NOTREACHED();
1530 return false;
1531 }
1532}
1533
1534OmahaRequestAction::WallClockWaitResult
1535OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001536 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001537 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1538 if (update_first_seen_at == base::Time()) {
1539 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
1540 "persisted";
1541 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001542 }
1543
Sen Jiang7c1171e2016-06-23 11:35:40 -07001544 TimeDelta elapsed_time =
1545 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1546 TimeDelta max_scatter_period =
1547 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001548 int64_t staging_wait_time_in_days = 0;
1549 // Use staging and its default max value if staging is on.
1550 if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1551 &staging_wait_time_in_days) &&
1552 staging_wait_time_in_days > 0)
1553 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001554
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001555 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001556 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001557 << ", Time Elapsed = "
1558 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001559 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001560
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001561 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001562 // The deadline is set for all rules which serve a delta update from a
1563 // previous FSI, which means this update will be applied mostly in OOBE
1564 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1565 // quickly.
1566 LOG(INFO) << "Not scattering as deadline flag is set";
1567 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1568 }
1569
1570 if (max_scatter_period.InDays() == 0) {
1571 // This means the Omaha rule creator decides that this rule
1572 // should not be scattered irrespective of the policy.
1573 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1574 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1575 }
1576
1577 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001578 // This means we've waited more than the upperbound wait in the rule
1579 // from the time we first saw a valid update available to us.
1580 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001581 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1582 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1583 }
1584
1585 // This means we are required to participate in scattering.
1586 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001587 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001588 if (remaining_wait_time.InSeconds() <= 0) {
1589 // Yes, it's our turn now.
1590 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1591
1592 // But we can't download until the update-check-count-based wait is also
1593 // satisfied, so mark it as required now if update checks are enabled.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001594 return params_->update_check_count_wait_enabled()
1595 ? kWallClockWaitDoneButUpdateCheckWaitRequired
1596 : kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001597 }
1598
1599 // Not our turn yet, so we have to wait until our turn to
1600 // help scatter the downloads across all clients of the enterprise.
1601 LOG(INFO) << "Update deferred for another "
1602 << utils::FormatSecs(remaining_wait_time.InSeconds())
1603 << " per policy.";
1604 return kWallClockWaitNotSatisfied;
1605}
1606
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001607bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001608 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001609
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001610 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1611 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1612 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001613 // We are unable to read the update check count from file for some reason.
1614 // So let's proceed anyway so as to not stall the update.
1615 LOG(ERROR) << "Unable to read update check count. "
1616 << "Skipping update-check-count-based-wait.";
1617 return true;
1618 }
1619 } else {
1620 // This file does not exist. This means we haven't started our update
1621 // check count down yet, so this is the right time to start the count down.
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001622 update_check_count_value =
1623 base::RandInt(params_->min_update_checks_needed(),
1624 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001625
1626 LOG(INFO) << "Randomly picked update check count value = "
1627 << update_check_count_value;
1628
1629 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001630 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1631 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001632 // We weren't able to write the update check count file for some reason.
1633 // So let's proceed anyway so as to not stall the update.
1634 LOG(ERROR) << "Unable to write update check count. "
1635 << "Skipping update-check-count-based-wait.";
1636 return true;
1637 }
1638 }
1639
1640 if (update_check_count_value == 0) {
1641 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1642 return true;
1643 }
1644
1645 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001646 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001647 // We err on the side of skipping scattering logic instead of stalling
1648 // a machine from receiving any updates in case of any unexpected state.
1649 LOG(ERROR) << "Invalid value for update check count detected. "
1650 << "Skipping update-check-count-based-wait.";
1651 return true;
1652 }
1653
1654 // Legal value, we need to wait for more update checks to happen
1655 // until this becomes 0.
1656 LOG(INFO) << "Deferring Omaha updates for another "
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001657 << update_check_count_value << " update checks per policy";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001658 return false;
1659}
1660
David Zeuthen639aa362014-02-03 16:23:44 -08001661// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001662bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001663 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001664 int64_t elapsed_days = 0;
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001665 if (!base::StringToInt64(parser_data->daystart_elapsed_days, &elapsed_days))
David Zeuthen639aa362014-02-03 16:23:44 -08001666 return false;
1667
1668 if (elapsed_days < 0)
1669 return false;
1670
1671 output_object->install_date_days = elapsed_days;
1672 return true;
1673}
1674
1675// static
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001676bool OmahaRequestAction::HasInstallDate(SystemState* system_state) {
David Zeuthen639aa362014-02-03 16:23:44 -08001677 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001678 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001679 return false;
1680
1681 return prefs->Exists(kPrefsInstallDateDays);
1682}
1683
1684// static
1685bool OmahaRequestAction::PersistInstallDate(
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001686 SystemState* system_state,
David Zeuthen639aa362014-02-03 16:23:44 -08001687 int install_date_days,
1688 InstallDateProvisioningSource source) {
1689 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1690
1691 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001692 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001693 return false;
1694
1695 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1696 return false;
1697
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001698 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001699 static_cast<int>(source), // Sample.
1700 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001701 return true;
1702}
1703
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001704bool OmahaRequestAction::PersistCohortData(const string& prefs_key,
1705 const string& new_value) {
Alex Deymo8e18f932015-03-27 16:16:59 -07001706 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1707 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1708 return system_state_->prefs()->Delete(prefs_key);
1709 } else if (!new_value.empty()) {
1710 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1711 return system_state_->prefs()->SetString(prefs_key, new_value);
1712 }
1713 return true;
1714}
1715
Alex Deymob3fa53b2016-04-18 19:57:58 -07001716bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
Amin Hassani6600a562018-09-24 15:17:19 -07001717 auto eol_attr = attrs.find(kAttrEol);
Alex Deymob3fa53b2016-04-18 19:57:58 -07001718 if (eol_attr != attrs.end()) {
1719 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1720 eol_attr->second);
1721 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1722 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1723 }
1724 return true;
1725}
1726
David Zeuthen33bae492014-02-25 16:16:18 -08001727void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1728 // We only want to report this on "update check".
1729 if (ping_only_ || event_ != nullptr)
1730 return;
1731
1732 metrics::CheckResult result = metrics::CheckResult::kUnset;
1733 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1734 metrics::DownloadErrorCode download_error_code =
1735 metrics::DownloadErrorCode::kUnset;
1736
1737 // Regular update attempt.
1738 switch (code) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001739 case ErrorCode::kSuccess:
1740 // OK, we parsed the response successfully but that does
1741 // necessarily mean that an update is available.
1742 if (HasOutputPipe()) {
1743 const OmahaResponse& response = GetOutputObject();
1744 if (response.update_exists) {
1745 result = metrics::CheckResult::kUpdateAvailable;
1746 reaction = metrics::CheckReaction::kUpdating;
1747 } else {
1748 result = metrics::CheckResult::kNoUpdateAvailable;
1749 }
David Zeuthen33bae492014-02-25 16:16:18 -08001750 } else {
1751 result = metrics::CheckResult::kNoUpdateAvailable;
1752 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001753 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001754
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001755 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
1756 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
1757 result = metrics::CheckResult::kUpdateAvailable;
1758 reaction = metrics::CheckReaction::kIgnored;
1759 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001760
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001761 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
1762 result = metrics::CheckResult::kUpdateAvailable;
1763 reaction = metrics::CheckReaction::kDeferring;
1764 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001765
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001766 case ErrorCode::kOmahaUpdateDeferredForBackoff:
1767 result = metrics::CheckResult::kUpdateAvailable;
1768 reaction = metrics::CheckReaction::kBackingOff;
1769 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001770
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001771 default:
1772 // We report two flavors of errors, "Download errors" and "Parsing
1773 // error". Try to convert to the former and if that doesn't work
1774 // we know it's the latter.
1775 metrics::DownloadErrorCode tmp_error =
1776 metrics_utils::GetDownloadErrorCode(code);
1777 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1778 result = metrics::CheckResult::kDownloadError;
1779 download_error_code = tmp_error;
1780 } else {
1781 result = metrics::CheckResult::kParsingError;
1782 }
1783 break;
David Zeuthen33bae492014-02-25 16:16:18 -08001784 }
1785
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001786 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1787 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001788}
1789
Toni Barzic61544e62018-10-11 14:37:30 -07001790bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1791 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001792 // Note: policy decision to not update to a version we rolled back from.
1793 string rollback_version =
1794 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001795 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001796 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001797 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001798 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001799 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001800 return true;
1801 }
1802 }
1803
Toni Barzic61544e62018-10-11 14:37:30 -07001804 if (system_state_->hardware()->IsOOBEEnabled() &&
1805 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
1806 (response.deadline.empty() ||
1807 system_state_->payload_state()->GetRollbackHappened()) &&
1808 params_->app_version() != "ForcedUpdate") {
1809 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1810 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1811 return true;
1812 }
1813
Weidong Guo421ff332017-04-17 10:08:38 -07001814 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001815 LOG(INFO) << "Update is not allowed over current connection.";
1816 return true;
1817 }
1818
1819 // Note: We could technically delete the UpdateFirstSeenAt state when we
1820 // return true. If we do, it'll mean a device has to restart the
1821 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1822 // turned on again. On the other hand, it also increases the chance of update
1823 // starvation if an admin turns AU on/off more frequently. We choose to err on
1824 // the side of preventing starvation at the cost of not applying scattering in
1825 // those cases.
1826 return false;
1827}
1828
Weidong Guo421ff332017-04-17 10:08:38 -07001829bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1830 const OmahaResponse& response) const {
1831 PrefsInterface* prefs = system_state_->prefs();
1832
1833 if (!prefs) {
1834 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1835 "not available.";
1836 return false;
1837 }
1838
1839 bool is_allowed;
1840
1841 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1842 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1843 is_allowed) {
1844 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1845 "set to true.";
1846 return true;
1847 }
1848
1849 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1850 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1851 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1852 "set to false or does not exist while target does not exist.";
1853 return false;
1854 }
1855
1856 std::string target_version;
1857 int64_t target_size;
1858
1859 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1860 &target_version) ||
1861 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1862 LOG(INFO) << "Disabling updates over cellular as the target version or "
1863 "size is not accessible.";
1864 return false;
1865 }
1866
1867 uint64_t total_packages_size = 0;
1868 for (const auto& package : response.packages) {
1869 total_packages_size += package.size;
1870 }
1871 if (target_version == response.version &&
1872 static_cast<uint64_t>(target_size) == total_packages_size) {
1873 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1874 "omaha response.";
1875 return true;
1876 } else {
1877 LOG(INFO) << "Disabling updates over cellular as the target does not"
1878 "match the omaha response.";
1879 return false;
1880 }
1881}
1882
1883bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1884 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001885 ConnectionType type;
1886 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001887 ConnectionManagerInterface* connection_manager =
1888 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001889 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001890 LOG(INFO) << "We could not determine our connection type. "
1891 << "Defaulting to allow updates.";
1892 return true;
1893 }
Weidong Guo421ff332017-04-17 10:08:38 -07001894
Chris Sosa77f79e82014-06-02 18:16:24 -07001895 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001896 bool is_device_policy_set =
1897 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1898 // Treats tethered connection as if it is cellular connection.
1899 bool is_over_cellular = type == ConnectionType::kCellular ||
1900 tethering == ConnectionTethering::kConfirmed;
1901
1902 if (!is_over_cellular) {
1903 // There's no need to further check user preferences as we are not over
1904 // cellular connection.
1905 if (!is_allowed)
1906 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1907 } else if (is_device_policy_set) {
1908 // There's no need to further check user preferences as the device policy
1909 // is set regarding updates over cellular.
1910 if (!is_allowed)
1911 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1912 } else {
1913 // Deivce policy is not set, so user preferences overwrite whether to
1914 // allow updates over cellular.
1915 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1916 if (!is_allowed)
1917 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1918 }
1919
Chris Sosa77f79e82014-06-02 18:16:24 -07001920 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001921 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001922 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1923 return is_allowed;
1924}
1925
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001926bool OmahaRequestAction::IsRollbackEnabled() const {
1927 if (policy_provider_->IsConsumerDevice()) {
1928 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1929 return false;
1930 }
1931
1932 if (!policy_provider_->device_policy_is_loaded()) {
1933 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1934 return true;
1935 }
1936
1937 int allowed_milestones;
1938 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1939 &allowed_milestones)) {
1940 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1941 "Defaulting to rollback enabled.";
1942 return true;
1943 }
1944
1945 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1946 return allowed_milestones > 0;
1947}
1948
1949void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001950 int max_kernel_rollforward;
1951 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001952 if (IsRollbackEnabled()) {
1953 // If rollback is enabled, set the max kernel key version to the current
1954 // kernel key version. This has the effect of freezing kernel key roll
1955 // forwards.
1956 //
1957 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1958 // key roll forward happens until the server side components of rollback
1959 // are implemented. Future changes will allow the Omaha server to return
1960 // the kernel key version from max_rollback_versions in the past. At that
1961 // point the max kernel key version will be set to that value, creating a
1962 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001963 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001964 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001965 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001966 } else {
1967 // For devices that are not rollback enabled (ie. consumer devices), the
1968 // max kernel key version is set to 0xfffffffe, which is logically
1969 // infinity. This maintains the previous behavior that that kernel key
1970 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001971 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001972 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001973 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001974 }
1975
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001976 bool max_rollforward_set =
1977 system_state_->hardware()->SetMaxKernelKeyRollforward(
1978 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001979 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001980 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001981 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001982 // Report metrics
1983 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1984 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001985}
1986
May Lippert60aa3ca2018-08-15 16:55:29 -07001987base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1988 Time update_first_seen_at;
1989 int64_t update_first_seen_at_int;
1990 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1991 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1992 &update_first_seen_at_int)) {
1993 // Note: This timestamp could be that of ANY update we saw in the past
1994 // (not necessarily this particular update we're considering to apply)
1995 // but never got to apply because of some reason (e.g. stop AU policy,
1996 // updates being pulled out from Omaha, changes in target version prefix,
1997 // new update being rolled out, etc.). But for the purposes of scattering
1998 // it doesn't matter which update the timestamp corresponds to. i.e.
1999 // the clock starts ticking the first time we see an update and we're
2000 // ready to apply when the random wait period is satisfied relative to
2001 // that first seen timestamp.
2002 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
2003 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
2004 << utils::ToString(update_first_seen_at);
2005 } else {
2006 // This seems like an unexpected error where the persisted value exists
2007 // but it's not readable for some reason.
2008 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
2009 return base::Time();
2010 }
2011 } else {
2012 update_first_seen_at = system_state_->clock()->GetWallclockTime();
2013 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
2014 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
2015 update_first_seen_at_int)) {
2016 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
2017 << utils::ToString(update_first_seen_at);
2018 } else {
2019 // This seems like an unexpected error where the value cannot be
2020 // persisted for some reason.
2021 LOG(INFO) << "UpdateFirstSeenAt value "
2022 << utils::ToString(update_first_seen_at)
2023 << " cannot be persisted";
2024 return base::Time();
2025 }
2026 }
2027 return update_first_seen_at;
2028}
2029
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07002030} // namespace chromeos_update_engine