blob: 6adacc33ee094729b6aff6a96fadf29be4abb2e2 [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)
159 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",
Darin Petkove17f86b2010-07-20 09:12:01 -0700212 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700213 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700214
215 return app_body;
216}
217
Alex Deymo8e18f932015-03-27 16:16:59 -0700218// Returns the cohort* argument to include in the <app> tag for the passed
219// |arg_name| and |prefs_key|, if any. The return value is suitable to
220// concatenate to the list of arguments and includes a space at the end.
221string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700222 const string arg_name,
223 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700224 // There's nothing wrong with not having a given cohort setting, so we check
Sen Jiang771f6482018-04-04 17:59:10 -0700225 // existence first to avoid the warning log message.
Alex Deymo8e18f932015-03-27 16:16:59 -0700226 if (!prefs->Exists(prefs_key))
227 return "";
228 string cohort_value;
229 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
230 return "";
231 // This is a sanity check to avoid sending a huge XML file back to Ohama due
232 // to a compromised stateful partition making the update check fail in low
233 // network environments envent after a reboot.
234 if (cohort_value.size() > 1024) {
235 LOG(WARNING) << "The omaha cohort setting " << arg_name
236 << " has a too big value, which must be an error or an "
237 "attacker trying to inhibit updates.";
238 return "";
239 }
240
Alex Deymob0d74eb2015-03-30 17:59:17 -0700241 string escaped_xml_value;
242 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
243 LOG(WARNING) << "The omaha cohort setting " << arg_name
244 << " is ASCII-7 invalid, ignoring it.";
245 return "";
246 }
247
Alex Deymo8e18f932015-03-27 16:16:59 -0700248 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700249 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700250}
251
Sen Jiang94a4dec2017-03-28 18:23:35 -0700252struct OmahaAppData {
253 string id;
254 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700255 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700256};
257
Sen Jiang684c9cd2017-10-17 16:26:45 -0700258bool IsValidComponentID(const string& id) {
259 for (char c : id) {
260 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
261 return false;
262 }
263 return true;
264}
265
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700266// Returns an XML that corresponds to the entire <app> node of the Omaha
267// request based on the given parameters.
268string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700269 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700270 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700271 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700272 bool include_ping,
Xiaochu Liu6310be62018-10-11 15:09:03 -0700273 bool skip_updatecheck,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700274 int ping_active_days,
275 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800276 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700277 SystemState* system_state) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700278 string app_body = GetAppBody(event,
279 params,
280 ping_only,
281 include_ping,
282 skip_updatecheck,
283 ping_active_days,
284 ping_roll_call_days,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700285 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700286 string app_versions;
287
Sen Jiang8cd42342018-01-31 12:06:59 -0800288 // If we are downgrading to a more stable channel and we are allowed to do
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700289 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
290 // highest-versioned payload on the destination channel.
Sen Jiang8500d3a2018-02-08 12:04:05 -0800291 if (params->ShouldPowerwash()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700292 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
293 << "on downgrading to the version in the more stable channel";
294 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700295 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700296 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700297 app_versions = "version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700298 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700299 }
300
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700301 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700302 string app_channels =
303 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
304 if (params->current_channel() != download_channel) {
305 app_channels += "from_track=\"" + XmlEncodeWithDefault(
306 params->current_channel(), "") + "\" ";
307 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700308
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700309 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700310
David Zeuthen639aa362014-02-03 16:23:44 -0800311 // If install_date_days is not set (e.g. its value is -1 ), don't
312 // include the attribute.
313 string install_date_in_days_str = "";
314 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700315 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
316 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800317 }
318
Alex Deymo8e18f932015-03-27 16:16:59 -0700319 string app_cohort_args;
320 app_cohort_args += GetCohortArgXml(system_state->prefs(),
321 "cohort", kPrefsOmahaCohort);
322 app_cohort_args += GetCohortArgXml(system_state->prefs(),
323 "cohorthint", kPrefsOmahaCohortHint);
324 app_cohort_args += GetCohortArgXml(system_state->prefs(),
325 "cohortname", kPrefsOmahaCohortName);
326
Alex Deymoebf6e122017-03-10 16:12:01 -0800327 string fingerprint_arg;
328 if (!params->os_build_fingerprint().empty()) {
Sen Jiang8cd42342018-01-31 12:06:59 -0800329 fingerprint_arg = "fingerprint=\"" +
330 XmlEncodeWithDefault(params->os_build_fingerprint(), "") +
331 "\" ";
Alex Deymoebf6e122017-03-10 16:12:01 -0800332 }
333
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700334 string buildtype_arg;
335 if (!params->os_build_type().empty()) {
336 buildtype_arg = "os_build_type=\"" +
337 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
338 }
339
Sen Jiang684c9cd2017-10-17 16:26:45 -0700340 string product_components_args;
Sen Jiang8500d3a2018-02-08 12:04:05 -0800341 if (!params->ShouldPowerwash() && !app_data.product_components.empty()) {
Sen Jiang684c9cd2017-10-17 16:26:45 -0700342 brillo::KeyValueStore store;
343 if (store.LoadFromString(app_data.product_components)) {
344 for (const string& key : store.GetKeys()) {
345 if (!IsValidComponentID(key)) {
346 LOG(ERROR) << "Invalid component id: " << key;
347 continue;
348 }
349 string version;
350 if (!store.GetString(key, &version)) {
351 LOG(ERROR) << "Failed to get version for " << key
352 << " in product_components.";
353 continue;
354 }
355 product_components_args +=
356 base::StringPrintf("_%s.version=\"%s\" ",
357 key.c_str(),
358 XmlEncodeWithDefault(version, "").c_str());
359 }
360 } else {
361 LOG(ERROR) << "Failed to parse product_components:\n"
362 << app_data.product_components;
363 }
364 }
365
366 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700367 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700368 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700369 app_cohort_args +
370 app_versions +
371 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700372 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800373 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700374 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700375 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
376 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
377 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
378 "delta_okay=\"" + delta_okay_str + "\" "
379 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
380 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
381 install_date_in_days_str +
382 ">\n" +
383 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700384 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700385 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700386 return app_xml;
387}
388
389// Returns an XML that corresponds to the entire <os> node of the Omaha
390// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700391string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700392 string os_xml =" <os "
393 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
394 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
395 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
396 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700397 return os_xml;
398}
399
400// Returns an XML that corresponds to the entire Omaha request based on the
401// given parameters.
402string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700403 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700404 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700405 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700406 int ping_active_days,
407 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800408 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700409 SystemState* system_state) {
410 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700411 OmahaAppData product_app = {
412 .id = params->GetAppId(),
413 .version = params->app_version(),
414 .product_components = params->product_components()};
Xiaochu Liu6310be62018-10-11 15:09:03 -0700415 // Skips updatecheck for platform app in case of an install operation.
Sen Jiang94a4dec2017-03-28 18:23:35 -0700416 string app_xml = GetAppXml(event,
417 params,
418 product_app,
419 ping_only,
420 include_ping,
Xiaochu Liu6310be62018-10-11 15:09:03 -0700421 params->is_install(), /* skip_updatecheck */
Sen Jiang94a4dec2017-03-28 18:23:35 -0700422 ping_active_days,
423 ping_roll_call_days,
424 install_date_in_days,
425 system_state);
426 if (!params->system_app_id().empty()) {
427 OmahaAppData system_app = {.id = params->system_app_id(),
428 .version = params->system_version()};
429 app_xml += GetAppXml(event,
430 params,
431 system_app,
432 ping_only,
433 include_ping,
Xiaochu Liu6310be62018-10-11 15:09:03 -0700434 false, /* skip_updatecheck */
Sen Jiang94a4dec2017-03-28 18:23:35 -0700435 ping_active_days,
436 ping_roll_call_days,
437 install_date_in_days,
438 system_state);
439 }
Xiaochu Liu88d90382018-08-29 16:09:11 -0700440 // Create APP ID according to |dlc_id| (sticking the current AppID to the DLC
441 // ID with an underscode).
442 for (const auto& dlc_id : params->dlc_ids()) {
443 OmahaAppData dlc_app = {.id = params->GetAppId() + "_" + dlc_id,
444 .version = params->app_version()};
445 app_xml += GetAppXml(event,
446 params,
447 dlc_app,
448 ping_only,
449 include_ping,
Xiaochu Liu6310be62018-10-11 15:09:03 -0700450 false, /* skip_updatecheck */
Xiaochu Liu88d90382018-08-29 16:09:11 -0700451 ping_active_days,
452 ping_roll_call_days,
453 install_date_in_days,
454 system_state);
455 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700456
Alex Vakulenko75039d72014-03-25 12:36:28 -0700457 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700458 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700459
Alex Deymoac41a822015-09-15 20:52:53 -0700460 string updater_version = XmlEncodeWithDefault(
461 base::StringPrintf("%s-%s",
462 constants::kOmahaUpdaterID,
463 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700464 string request_xml =
465 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700466 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700467 "version=\"" + updater_version + "\" "
468 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700469 install_source +
470 "ismachine=\"1\">\n") +
471 os_xml +
472 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700473 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700474
475 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000476}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700477
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700478} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000479
David Zeuthene8ed8632014-07-24 13:38:10 -0400480// Struct used for holding data obtained when parsing the XML.
481struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400482 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
483
484 // Pointer to the expat XML_Parser object.
485 XML_Parser xml_parser;
486
David Zeuthene8ed8632014-07-24 13:38:10 -0400487 // This is the state of the parser as it's processing the XML.
488 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400489 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400490 string current_path;
491
492 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400493 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700494 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400495 string daystart_elapsed_days;
496 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800497
Sen Jiang81259682017-03-30 15:11:30 -0700498 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700499 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700500 vector<string> url_codebase;
501 string manifest_version;
502 map<string, string> action_postinstall_attrs;
503 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700504 string cohort;
505 string cohorthint;
506 string cohortname;
507 bool cohort_set = false;
508 bool cohorthint_set = false;
509 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700510
511 struct Package {
512 string name;
513 string size;
514 string hash;
515 };
516 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800517 };
Sen Jiang81259682017-03-30 15:11:30 -0700518 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400519};
520
521namespace {
522
523// Callback function invoked by expat.
524void ParserHandlerStart(void* user_data, const XML_Char* element,
525 const XML_Char** attr) {
526 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
527
528 if (data->failed)
529 return;
530
531 data->current_path += string("/") + element;
532
533 map<string, string> attrs;
534 if (attr != nullptr) {
535 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
536 string key = attr[n];
537 string value = attr[n + 1];
538 attrs[key] = value;
539 }
540 }
541
Alex Deymo8e18f932015-03-27 16:16:59 -0700542 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700543 OmahaParserData::App app;
Amin Hassani6600a562018-09-24 15:17:19 -0700544 if (attrs.find(kAttrAppId) != attrs.end()) {
545 app.id = attrs[kAttrAppId];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700546 }
Amin Hassani6600a562018-09-24 15:17:19 -0700547 if (attrs.find(kAttrCohort) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700548 app.cohort_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700549 app.cohort = attrs[kAttrCohort];
Alex Deymo8e18f932015-03-27 16:16:59 -0700550 }
Amin Hassani6600a562018-09-24 15:17:19 -0700551 if (attrs.find(kAttrCohortHint) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700552 app.cohorthint_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700553 app.cohorthint = attrs[kAttrCohortHint];
Alex Deymo8e18f932015-03-27 16:16:59 -0700554 }
Amin Hassani6600a562018-09-24 15:17:19 -0700555 if (attrs.find(kAttrCohortName) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700556 app.cohortname_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700557 app.cohortname = attrs[kAttrCohortName];
Alex Deymo8e18f932015-03-27 16:16:59 -0700558 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700559 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700560 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700561 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700562 data->apps.back().updatecheck_status = attrs[kAttrStatus];
Sen Jiang81259682017-03-30 15:11:30 -0700563 if (data->updatecheck_poll_interval.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700564 data->updatecheck_poll_interval = attrs[kAttrPollInterval];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700565 // Omaha sends arbitrary key-value pairs as extra attributes starting with
566 // an underscore.
567 for (const auto& attr : attrs) {
568 if (!attr.first.empty() && attr.first[0] == '_')
569 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
570 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400571 } else if (data->current_path == "/response/daystart") {
572 // Get the install-date.
Amin Hassani6600a562018-09-24 15:17:19 -0700573 data->daystart_elapsed_days = attrs[kAttrElapsedDays];
574 data->daystart_elapsed_seconds = attrs[kAttrElapsedSeconds];
David Zeuthene8ed8632014-07-24 13:38:10 -0400575 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
576 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700577 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700578 data->apps.back().url_codebase.push_back(attrs[kAttrCodeBase]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800579 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400580 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800581 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700582 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700583 data->apps.back().packages.push_back({.name = attrs[kAttrName],
584 .size = attrs[kAttrSize],
585 .hash = attrs[kAttrHashSha256]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400586 } else if (data->current_path == "/response/app/updatecheck/manifest") {
587 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700588 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700589 data->apps.back().manifest_version = attrs[kAttrVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400590 } else if (data->current_path ==
591 "/response/app/updatecheck/manifest/actions/action") {
592 // We only care about the postinstall action.
Amin Hassani6600a562018-09-24 15:17:19 -0700593 if (attrs[kAttrEvent] == kValPostInstall && !data->apps.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700594 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400595 }
596 }
597}
598
599// Callback function invoked by expat.
600void ParserHandlerEnd(void* user_data, const XML_Char* element) {
601 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
602 if (data->failed)
603 return;
604
605 const string path_suffix = string("/") + element;
606
Alex Vakulenko0103c362016-01-20 07:56:15 -0800607 if (!base::EndsWith(data->current_path, path_suffix,
608 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400609 LOG(ERROR) << "Unexpected end element '" << element
610 << "' with current_path='" << data->current_path << "'";
611 data->failed = true;
612 return;
613 }
614 data->current_path.resize(data->current_path.size() - path_suffix.size());
615}
616
David Zeuthenf3e28012014-08-26 18:23:52 -0400617// Callback function invoked by expat.
618//
619// This is called for entity declarations. Since Omaha is guaranteed
620// to never return any XML with entities our course of action is to
621// just stop parsing. This avoids potential resource exhaustion
622// problems AKA the "billion laughs". CVE-2013-0340.
623void ParserHandlerEntityDecl(void *user_data,
624 const XML_Char *entity_name,
625 int is_parameter_entity,
626 const XML_Char *value,
627 int value_length,
628 const XML_Char *base,
629 const XML_Char *system_id,
630 const XML_Char *public_id,
631 const XML_Char *notation_name) {
632 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
633
634 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
635 data->failed = true;
636 data->entity_decl = true;
637 XML_StopParser(data->xml_parser, false);
638}
639
David Zeuthene8ed8632014-07-24 13:38:10 -0400640} // namespace
641
Alex Deymob0d74eb2015-03-30 17:59:17 -0700642bool XmlEncode(const string& input, string* output) {
643 if (std::find_if(input.begin(), input.end(),
644 [](const char c){return c & 0x80;}) != input.end()) {
645 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
646 utils::HexDumpString(input);
647 return false;
648 }
Alex Deymocc457852015-06-18 18:35:50 -0700649 output->clear();
650 // We need at least input.size() space in the output, but the code below will
651 // handle it if we need more.
652 output->reserve(input.size());
653 for (char c : input) {
654 switch (c) {
655 case '\"':
656 output->append("&quot;");
657 break;
658 case '\'':
659 output->append("&apos;");
660 break;
661 case '&':
662 output->append("&amp;");
663 break;
664 case '<':
665 output->append("&lt;");
666 break;
667 case '>':
668 output->append("&gt;");
669 break;
670 default:
671 output->push_back(c);
672 }
673 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700674 return true;
675}
676
677string XmlEncodeWithDefault(const string& input, const string& default_value) {
678 string output;
679 if (XmlEncode(input, &output))
680 return output;
681 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000682}
683
Alex Deymoc1c17b42015-11-23 03:53:15 -0300684OmahaRequestAction::OmahaRequestAction(
685 SystemState* system_state,
686 OmahaEvent* event,
687 std::unique_ptr<HttpFetcher> http_fetcher,
688 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800689 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800690 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700691 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300692 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800693 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700694 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700695 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700696 ping_roll_call_days_(0) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800697 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700698}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000699
Darin Petkov6a5b3222010-07-13 14:55:28 -0700700OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000701
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700702// Calculates the value to use for the ping days parameter.
703int OmahaRequestAction::CalculatePingDays(const string& key) {
704 int days = kNeverPinged;
705 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800706 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700707 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
708 if (days < 0) {
709 // If |days| is negative, then the system clock must have jumped
710 // back in time since the ping was sent. Mark the value so that
711 // it doesn't get sent to the server but we still update the
712 // last ping daystart preference. This way the next ping time
713 // will be correct, hopefully.
714 days = kPingTimeJump;
715 LOG(WARNING) <<
716 "System clock jumped back in time. Resetting ping daystarts.";
717 }
718 }
719 return days;
720}
721
722void OmahaRequestAction::InitPingDays() {
723 // We send pings only along with update checks, not with events.
724 if (IsEvent()) {
725 return;
726 }
727 // TODO(petkov): Figure a way to distinguish active use pings
728 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700729 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700730 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
731 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
732}
733
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700734bool OmahaRequestAction::ShouldPing() const {
735 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
736 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
737 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
738 if (powerwash_count > 0) {
739 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
740 << "powerwash_count is " << powerwash_count;
741 return false;
742 }
Amin Hassani1677e812017-06-21 13:36:36 -0700743 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
744 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
745 << "the first_active_omaha_ping_sent is true";
746 return false;
747 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700748 return true;
749 }
750 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
751}
752
David Zeuthen639aa362014-02-03 16:23:44 -0800753// static
754int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
755 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700756 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800757 return -1;
758
759 // If we have the value stored on disk, just return it.
760 int64_t stored_value;
761 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
762 // Convert and sanity-check.
763 int install_date_days = static_cast<int>(stored_value);
764 if (install_date_days >= 0)
765 return install_date_days;
766 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
767 << install_date_days << " looks suspicious.";
768 prefs->Delete(kPrefsInstallDateDays);
769 }
770
771 // Otherwise, if OOBE is not complete then do nothing and wait for
772 // ParseResponse() to call ParseInstallDate() and then
773 // PersistInstallDate() to set the kPrefsInstallDateDays state
774 // variable. Once that is done, we'll then report back in future
775 // Omaha requests. This works exactly because OOBE triggers an
776 // update check.
777 //
778 // However, if OOBE is complete and the kPrefsInstallDateDays state
779 // variable is not set, there are two possibilities
780 //
781 // 1. The update check in OOBE failed so we never got a response
782 // from Omaha (no network etc.); or
783 //
784 // 2. OOBE was done on an older version that didn't write to the
785 // kPrefsInstallDateDays state variable.
786 //
787 // In both cases, we approximate the install date by simply
788 // inspecting the timestamp of when OOBE happened.
789
790 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700791 if (!system_state->hardware()->IsOOBEEnabled() ||
792 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800793 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700794 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800795 return -1;
796 }
797
798 int num_days;
799 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
800 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
801 << "as its value '" << utils::ToString(time_of_oobe)
802 << "' looks suspicious.";
803 return -1;
804 }
805
806 // Persist this to disk, for future use.
807 if (!OmahaRequestAction::PersistInstallDate(system_state,
808 num_days,
809 kProvisionedFromOOBEMarker))
810 return -1;
811
812 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
813 << num_days << " days";
814
815 return num_days;
816}
817
Darin Petkov6a5b3222010-07-13 14:55:28 -0700818void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000819 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700820 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700821 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700822 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700823 return;
824 }
David Zeuthen639aa362014-02-03 16:23:44 -0800825
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700826 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700827 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700828 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700829 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700830 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800831 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800832 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700833 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700834
Sen Jiang42fa45e2018-03-12 11:02:14 -0700835 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700836 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
837 params_->interactive() ? "fg" : "bg");
838 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
839 http_fetcher_->SetHeader(
840 kXGoogleUpdateUpdater,
841 base::StringPrintf(
842 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
843
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800844 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
845 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700846 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700847 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700848 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000849}
850
Darin Petkov6a5b3222010-07-13 14:55:28 -0700851void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000852 http_fetcher_->TerminateTransfer();
853}
854
855// We just store the response in the buffer. Once we've received all bytes,
856// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700857bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800858 const void* bytes,
859 size_t length) {
860 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
861 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700862 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000863}
864
865namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000866
867// Parses a 64 bit base-10 int from a string and returns it. Returns 0
868// on error. If the string contains "0", that's indistinguishable from
869// error.
870off_t ParseInt(const string& str) {
871 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700872 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000873 if (rc < 1) {
874 // failure
875 return 0;
876 }
877 return ret;
878}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700879
David Zeuthene8ed8632014-07-24 13:38:10 -0400880// Parses |str| and returns |true| if, and only if, its value is "true".
881bool ParseBool(const string& str) {
882 return str == "true";
883}
884
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700885// Update the last ping day preferences based on the server daystart
886// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400887bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700888 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400889 TEST_AND_RETURN_FALSE(
890 base::StringToInt64(parser_data->daystart_elapsed_seconds,
891 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700892 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
893
894 // Remember the local time that matches the server's last midnight
895 // time.
896 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
897 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
898 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
899 return true;
900}
Sen Jiang81259682017-03-30 15:11:30 -0700901
902// Parses the package node in the given XML document and populates
903// |output_object| if valid. Returns true if we should continue the parsing.
904// False otherwise, in which case it sets any error code using |completer|.
905bool ParsePackage(OmahaParserData::App* app,
906 OmahaResponse* output_object,
907 ScopedActionCompleter* completer) {
Xiaochu Liu6310be62018-10-11 15:09:03 -0700908 if (app->updatecheck_status.empty() ||
909 app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700910 if (!app->packages.empty()) {
911 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
912 completer->set_code(ErrorCode::kOmahaResponseInvalid);
913 return false;
914 }
915 return true;
916 }
917 if (app->packages.empty()) {
918 LOG(ERROR) << "Omaha Response has no packages";
919 completer->set_code(ErrorCode::kOmahaResponseInvalid);
920 return false;
921 }
922 if (app->url_codebase.empty()) {
923 LOG(ERROR) << "No Omaha Response URLs";
924 completer->set_code(ErrorCode::kOmahaResponseInvalid);
925 return false;
926 }
927 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
928 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700929 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700930 ":",
931 base::TRIM_WHITESPACE,
932 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700933 vector<string> metadata_signatures = base::SplitString(
934 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
935 ":",
936 base::TRIM_WHITESPACE,
937 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700938 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700939 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700940 ":",
941 base::TRIM_WHITESPACE,
942 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700943 for (size_t i = 0; i < app->packages.size(); i++) {
944 const auto& package = app->packages[i];
945 if (package.name.empty()) {
946 LOG(ERROR) << "Omaha Response has empty package name";
947 completer->set_code(ErrorCode::kOmahaResponseInvalid);
948 return false;
949 }
950 LOG(INFO) << "Found package " << package.name;
951
952 OmahaResponse::Package out_package;
953 for (const string& codebase : app->url_codebase) {
954 if (codebase.empty()) {
955 LOG(ERROR) << "Omaha Response URL has empty codebase";
956 completer->set_code(ErrorCode::kOmahaResponseInvalid);
957 return false;
958 }
959 out_package.payload_urls.push_back(codebase + package.name);
960 }
961 // Parse the payload size.
962 base::StringToUint64(package.size, &out_package.size);
963 if (out_package.size <= 0) {
964 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
965 completer->set_code(ErrorCode::kOmahaResponseInvalid);
966 return false;
967 }
968 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
969
970 if (i < metadata_sizes.size())
971 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
972 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
973 << " bytes";
974
975 if (i < metadata_signatures.size())
976 out_package.metadata_signature = metadata_signatures[i];
977 LOG(INFO) << "Payload metadata signature = "
978 << out_package.metadata_signature;
979
980 out_package.hash = package.hash;
981 if (out_package.hash.empty()) {
982 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
983 completer->set_code(ErrorCode::kOmahaResponseInvalid);
984 return false;
985 }
986 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700987
988 if (i < is_delta_payloads.size())
989 out_package.is_delta = ParseBool(is_delta_payloads[i]);
990 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
991
Sen Jiang81259682017-03-30 15:11:30 -0700992 output_object->packages.push_back(std::move(out_package));
993 }
994
995 return true;
996}
997
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700998// Parses the 2 key version strings kernel_version and firmware_version. If the
999// field is not present, or cannot be parsed the values default to 0xffff.
1000void ParseRollbackVersions(OmahaParserData* parser_data,
1001 OmahaResponse* output_object) {
1002 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -07001003 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001004 &output_object->rollback_key_version.firmware_key,
1005 &output_object->rollback_key_version.firmware);
1006 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -07001007 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001008 &output_object->rollback_key_version.kernel_key,
1009 &output_object->rollback_key_version.kernel);
1010}
1011
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001012} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +00001013
David Zeuthene8ed8632014-07-24 13:38:10 -04001014bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001015 OmahaResponse* output_object,
1016 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001017 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001018 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001019 return false;
1020 }
Sen Jiang81259682017-03-30 15:11:30 -07001021 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001022
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001023 // chromium-os:37289: The PollInterval is not supported by Omaha server
1024 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -07001025 // slow down the request rate from the server-side. Note that the PollInterval
1026 // is not persisted, so it has to be sent by the server on every response to
1027 // guarantee that the scheduler uses this value (otherwise, if the device got
1028 // rebooted after the last server-indicated value, it'll revert to the default
1029 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
1030 // based on the assumption that we perform an update check every hour so that
1031 // the max value of 8 will roughly be equivalent to one work day. If we decide
1032 // to use PollInterval permanently, we should update the
1033 // max_update_checks_allowed to take PollInterval into account. Note: The
1034 // parsing for PollInterval happens even before parsing of the status because
1035 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -04001036 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001037 &output_object->poll_interval);
1038
David Zeuthen639aa362014-02-03 16:23:44 -08001039 // Check for the "elapsed_days" attribute in the "daystart"
1040 // element. This is the number of days since Jan 1 2007, 0:00
1041 // PST. If we don't have a persisted value of the Omaha InstallDate,
1042 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -04001043 if (ParseInstallDate(parser_data, output_object) &&
1044 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -08001045 // Since output_object->install_date_days is never negative, the
1046 // elapsed_days -> install-date calculation is reduced to simply
1047 // rounding down to the nearest number divisible by 7.
1048 int remainder = output_object->install_date_days % 7;
1049 int install_date_days_rounded =
1050 output_object->install_date_days - remainder;
1051 if (PersistInstallDate(system_state_,
1052 install_date_days_rounded,
1053 kProvisionedFromOmahaResponse)) {
1054 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
1055 << install_date_days_rounded << " days";
1056 }
1057 }
1058
Alex Deymo00d79ac2015-06-29 15:41:49 -07001059 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -07001060 for (const auto& app : parser_data->apps) {
1061 if (app.id == params_->GetAppId()) {
1062 if (app.cohort_set)
1063 PersistCohortData(kPrefsOmahaCohort, app.cohort);
1064 if (app.cohorthint_set)
1065 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
1066 if (app.cohortname_set)
1067 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
1068 break;
1069 }
1070 }
Alex Deymo00d79ac2015-06-29 15:41:49 -07001071
Alex Deymob3fa53b2016-04-18 19:57:58 -07001072 // Parse the updatecheck attributes.
1073 PersistEolStatus(parser_data->updatecheck_attrs);
Marton Hunyady199152d2018-05-07 19:08:48 +02001074 // Rollback-related updatecheck attributes.
1075 // Defaults to false if attribute is not present.
1076 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -07001077 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001078
1079 // Parses the rollback versions of the current image. If the fields do not
1080 // exist they default to 0xffff for the 4 key versions.
1081 ParseRollbackVersions(parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -07001082
David Zeuthene8ed8632014-07-24 13:38:10 -04001083 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001084 return false;
1085
David Zeuthene8ed8632014-07-24 13:38:10 -04001086 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001087 return false;
1088
Sen Jiang0affc2c2017-02-10 15:55:05 -08001089 // Package has to be parsed after Params now because ParseParams need to make
1090 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -07001091 for (auto& app : parser_data->apps)
1092 if (!ParsePackage(&app, output_object, completer))
1093 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001094
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001095 return true;
1096}
1097
David Zeuthene8ed8632014-07-24 13:38:10 -04001098bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001099 OmahaResponse* output_object,
1100 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001101 output_object->update_exists = false;
Xiaochu Liu6310be62018-10-11 15:09:03 -07001102 for (const auto& app : parser_data->apps) {
1103 const string& status = app.updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -07001104 if (status == kValNoUpdate) {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001105 // Don't update if any app has status="noupdate".
Xiaochu Liu6310be62018-10-11 15:09:03 -07001106 LOG(INFO) << "No update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001107 output_object->update_exists = false;
1108 break;
Sen Jiang81259682017-03-30 15:11:30 -07001109 } else if (status == "ok") {
Xiaochu Liu6310be62018-10-11 15:09:03 -07001110 auto const& attr_no_update =
1111 app.action_postinstall_attrs.find(kAttrNoUpdate);
1112 if (attr_no_update != app.action_postinstall_attrs.end() &&
1113 attr_no_update->second == "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001114 // noupdate="true" in postinstall attributes means it's an update to
1115 // self, only update if there's at least one app really have update.
Xiaochu Liu6310be62018-10-11 15:09:03 -07001116 LOG(INFO) << "Update to self for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001117 } else {
Xiaochu Liu6310be62018-10-11 15:09:03 -07001118 LOG(INFO) << "Update for <app> " << app.id;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001119 output_object->update_exists = true;
1120 }
Xiaochu Liu6310be62018-10-11 15:09:03 -07001121 } else if (status.empty() && params_->is_install() &&
1122 params_->GetAppId() == app.id) {
1123 // Skips the platform app for install operation.
1124 LOG(INFO) << "No payload (and ignore) for <app> " << app.id;
Sen Jiang81259682017-03-30 15:11:30 -07001125 } else {
1126 LOG(ERROR) << "Unknown Omaha response status: " << status;
1127 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1128 return false;
1129 }
1130 }
1131 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001132 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001133 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001134 }
1135
Sen Jiang81259682017-03-30 15:11:30 -07001136 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001137}
1138
David Zeuthene8ed8632014-07-24 13:38:10 -04001139bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001140 OmahaResponse* output_object,
1141 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001142 map<string, string> attrs;
1143 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001144 if (app.id == params_->GetAppId()) {
1145 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001146 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001147 } else if (!params_->system_app_id().empty() &&
1148 app.id == params_->system_app_id()) {
1149 // this is the system app (this check is intentionally skipped if there is
1150 // no system_app_id set)
1151 output_object->system_version = app.manifest_version;
Xiaochu Liu6310be62018-10-11 15:09:03 -07001152 } else if (params_->is_install() &&
1153 app.manifest_version != params_->app_version()) {
1154 LOG(WARNING) << "An app has a different version (" << app.manifest_version
1155 << ") that is different than platform app version ("
1156 << params_->app_version() << ")";
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001157 }
1158 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001159 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001160 }
Sen Jiang81259682017-03-30 15:11:30 -07001161 }
Xiaochu Liu6310be62018-10-11 15:09:03 -07001162 if (params_->is_install()) {
1163 LOG(INFO) << "Use request version for Install operation.";
1164 output_object->version = params_->app_version();
1165 }
Chris Sosa3b748432013-06-20 16:42:59 -07001166 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001167 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001168 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001169 return false;
1170 }
1171
1172 LOG(INFO) << "Received omaha response to update to version "
1173 << output_object->version;
1174
David Zeuthene8ed8632014-07-24 13:38:10 -04001175 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001176 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001177 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001178 return false;
1179 }
1180
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001181 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -07001182 output_object->more_info_url = attrs[kAttrMoreInfo];
1183 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
1184 output_object->deadline = attrs[kAttrDeadline];
1185 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001186 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -07001187 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001188 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -07001189 ParseBool(attrs[kAttrDisableP2PForSharing]);
1190 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001191
Amin Hassani6600a562018-09-24 15:17:19 -07001192 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001193 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001194 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001195
Jay Srinivasan08262882012-12-28 19:29:43 -08001196 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -07001197 ParseBool(attrs[kAttrDisablePayloadBackoff]);
1198 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001199
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001200 return true;
1201}
1202
David Zeuthene8ed8632014-07-24 13:38:10 -04001203// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001204// and fill in the appropriate fields of the output object. Also, notifies
1205// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001206void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1207 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001208 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001209 string current_response(response_buffer_.begin(), response_buffer_.end());
1210 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001211
Gilad Arnold74b5f552014-10-07 08:17:16 -07001212 PayloadStateInterface* const payload_state = system_state_->payload_state();
1213
Zentaro Kavanagh76af2662018-05-15 10:54:53 -07001214 // Set the max kernel key version based on whether rollback is allowed.
1215 SetMaxKernelKeyVersionForRollback();
1216
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001217 // Events are best effort transactions -- assume they always succeed.
1218 if (IsEvent()) {
1219 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001220 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001221 return;
1222 }
1223
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001224 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001225 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001226 int code = GetHTTPResponseCode();
1227 // Makes sure we send sane error values.
1228 if (code < 0 || code >= 1000) {
1229 code = 999;
1230 }
David Zeuthena99981f2013-04-29 13:42:47 -07001231 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001232 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001233 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001234 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001235
David Zeuthene8ed8632014-07-24 13:38:10 -04001236 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001237 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001238 XML_SetUserData(parser, &parser_data);
1239 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001240 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001241 XML_Status res = XML_Parse(
1242 parser,
1243 reinterpret_cast<const char*>(response_buffer_.data()),
1244 response_buffer_.size(),
1245 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001246
1247 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001248 LOG(ERROR) << "Omaha response not valid XML: "
1249 << XML_ErrorString(XML_GetErrorCode(parser))
1250 << " at line " << XML_GetCurrentLineNumber(parser)
1251 << " col " << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -07001252 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001253 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1254 if (response_buffer_.empty()) {
1255 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1256 } else if (parser_data.entity_decl) {
1257 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1258 }
1259 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001260 return;
1261 }
Amin Hassani91f48b42018-08-06 17:47:14 -07001262 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001263
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001264 // Update the last ping day preferences based on the server daystart response
1265 // even if we didn't send a ping. Omaha always includes the daystart in the
1266 // response, but log the error if it didn't.
1267 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1268 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001269
Amin Hassani1677e812017-06-21 13:36:36 -07001270 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1271 // we have got a response from omaha and if its value has never been set to
1272 // true before. Failure of this function should be ignored. There should be no
1273 // need to check if a=-1 has been sent because older devices have already sent
1274 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1275 // future checks.
1276 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -07001277 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
1278 system_state_->metrics_reporter()->ReportInternalErrorCode(
1279 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
1280 }
Amin Hassani1677e812017-06-21 13:36:36 -07001281 }
1282
Thieu Le116fda32011-04-19 11:01:54 -07001283 if (!HasOutputPipe()) {
1284 // Just set success to whether or not the http transfer succeeded,
1285 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001286 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001287 return;
1288 }
1289
Darin Petkov6a5b3222010-07-13 14:55:28 -07001290 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001291 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001292 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001293 output_object.update_exists = true;
1294 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001295
Toni Barzic61544e62018-10-11 14:37:30 -07001296 LoadOrPersistUpdateFirstSeenAtPref();
1297
Weidong Guo421ff332017-04-17 10:08:38 -07001298 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -07001299 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -07001300 // No need to change output_object.update_exists here, since the value
1301 // has been output to the pipe.
1302 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001303 return;
1304 }
1305
May Lippert60aa3ca2018-08-15 16:55:29 -07001306
David Zeuthen8f191b22013-08-06 12:27:50 -07001307 // If Omaha says to disable p2p, respect that
1308 if (output_object.disable_p2p_for_downloading) {
1309 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1310 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001311 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001312 }
1313 if (output_object.disable_p2p_for_sharing) {
1314 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1315 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001316 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001317 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001318
1319 // Update the payload state with the current response. The payload state
1320 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001321 // from what's stored already. We are updating the payload state as late
1322 // as possible in this method so that if a new release gets pushed and then
1323 // got pulled back due to some issues, we don't want to clear our internal
1324 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001325 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001326
David Zeuthen8f191b22013-08-06 12:27:50 -07001327 // It could be we've already exceeded the deadline for when p2p is
1328 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001329 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001330 payload_state->P2PNewAttempt();
1331 if (!payload_state->P2PAttemptAllowed()) {
1332 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1333 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001334 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001335 }
1336 }
1337
1338 // From here on, we'll complete stuff in CompleteProcessing() so
1339 // disable |completer| since we'll create a new one in that
1340 // function.
1341 completer.set_should_complete(false);
1342
1343 // If we're allowed to use p2p for downloading we do not pay
1344 // attention to wall-clock-based waiting if the URL is indeed
1345 // available via p2p. Therefore, check if the file is available via
1346 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001347 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001348 LookupPayloadViaP2P(output_object);
1349 } else {
1350 CompleteProcessing();
1351 }
1352}
1353
1354void OmahaRequestAction::CompleteProcessing() {
1355 ScopedActionCompleter completer(processor_, this);
1356 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1357 PayloadStateInterface* payload_state = system_state_->payload_state();
1358
1359 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001360 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001361 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001362 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001363 return;
1364 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001365
Chris Sosa20f005c2013-09-05 13:53:08 -07001366 if (payload_state->ShouldBackoffDownload()) {
1367 output_object.update_exists = false;
1368 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1369 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001370 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001371 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001372 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001373 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001374}
1375
1376void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1377 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1378 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001379 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001380 } else {
1381 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1382 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001383 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001384 }
1385 CompleteProcessing();
1386}
1387
1388void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001389 // If the device is in the middle of an update, the state variables
1390 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1391 // tracks the offset and length of the operation currently in
1392 // progress. The offset is based from the end of the manifest which
1393 // is kPrefsManifestMetadataSize bytes long.
1394 //
1395 // To make forward progress and avoid deadlocks, we need to find a
1396 // peer that has at least the entire operation we're currently
1397 // working on. Otherwise we may end up in a situation where two
1398 // devices bounce back and forth downloading from each other,
1399 // neither making any forward progress until one of them decides to
1400 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1401 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001402 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001403 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001404 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001405 int64_t next_data_offset = 0;
1406 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001407 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001408 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1409 &manifest_metadata_size) &&
1410 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001411 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1412 &manifest_signature_size) &&
1413 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001414 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001415 &next_data_offset) &&
1416 next_data_offset != -1 &&
1417 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1418 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001419 minimum_size = manifest_metadata_size + manifest_signature_size +
1420 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001421 }
1422
Sen Jiang0affc2c2017-02-10 15:55:05 -08001423 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001424 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001425 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001426 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001427 string file_id =
1428 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001429 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001430 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1431 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001432 system_state_->p2p_manager()->LookupUrlForFile(
1433 file_id,
1434 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001435 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001436 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1437 base::Unretained(this)));
1438 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001439}
1440
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001441bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001442 if (params_->interactive()) {
1443 LOG(INFO) << "Not deferring download because update is interactive.";
1444 return false;
1445 }
1446
David Zeuthen8f191b22013-08-06 12:27:50 -07001447 // If we're using p2p to download _and_ we have a p2p URL, we never
1448 // defer the download. This is because the download will always
1449 // happen from a peer on the LAN and we've been waiting in line for
1450 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001451 const PayloadStateInterface* payload_state = system_state_->payload_state();
1452 if (payload_state->GetUsingP2PForDownloading() &&
1453 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001454 LOG(INFO) << "Download not deferred because download "
1455 << "will happen from a local peer (via p2p).";
1456 return false;
1457 }
1458
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001459 // We should defer the downloads only if we've first satisfied the
1460 // wall-clock-based-waiting period and then the update-check-based waiting
1461 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001462 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001463 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1464 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001465 return false;
1466 }
1467
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001468 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001469 case kWallClockWaitNotSatisfied:
1470 // We haven't even satisfied the first condition, passing the
1471 // wall-clock-based waiting period, so we should defer the downloads
1472 // until that happens.
1473 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1474 return true;
1475
1476 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1477 LOG(INFO) << "wall-clock-based-wait satisfied and "
1478 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001479 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001480
1481 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1482 // Wall-clock-based waiting period is satisfied, and it's determined
1483 // that we do not need the update-check-based wait. so no need to
1484 // defer downloads.
1485 LOG(INFO) << "wall-clock-based-wait satisfied and "
1486 << "update-check-based-wait is not required.";
1487 return false;
1488
1489 default:
1490 // Returning false for this default case so we err on the
1491 // side of downloading updates than deferring in case of any bugs.
1492 NOTREACHED();
1493 return false;
1494 }
1495}
1496
1497OmahaRequestAction::WallClockWaitResult
1498OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001499 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001500 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1501 if (update_first_seen_at == base::Time()) {
1502 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
1503 "persisted";
1504 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001505 }
1506
Sen Jiang7c1171e2016-06-23 11:35:40 -07001507 TimeDelta elapsed_time =
1508 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1509 TimeDelta max_scatter_period =
1510 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001511 int64_t staging_wait_time_in_days = 0;
1512 // Use staging and its default max value if staging is on.
1513 if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1514 &staging_wait_time_in_days) &&
1515 staging_wait_time_in_days > 0)
1516 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001517
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001518 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001519 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001520 << ", Time Elapsed = "
1521 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001522 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001523
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001524 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001525 // The deadline is set for all rules which serve a delta update from a
1526 // previous FSI, which means this update will be applied mostly in OOBE
1527 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1528 // quickly.
1529 LOG(INFO) << "Not scattering as deadline flag is set";
1530 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1531 }
1532
1533 if (max_scatter_period.InDays() == 0) {
1534 // This means the Omaha rule creator decides that this rule
1535 // should not be scattered irrespective of the policy.
1536 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1537 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1538 }
1539
1540 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001541 // This means we've waited more than the upperbound wait in the rule
1542 // from the time we first saw a valid update available to us.
1543 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001544 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1545 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1546 }
1547
1548 // This means we are required to participate in scattering.
1549 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001550 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001551 if (remaining_wait_time.InSeconds() <= 0) {
1552 // Yes, it's our turn now.
1553 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1554
1555 // But we can't download until the update-check-count-based wait is also
1556 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001557 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001558 kWallClockWaitDoneButUpdateCheckWaitRequired :
1559 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1560 }
1561
1562 // Not our turn yet, so we have to wait until our turn to
1563 // help scatter the downloads across all clients of the enterprise.
1564 LOG(INFO) << "Update deferred for another "
1565 << utils::FormatSecs(remaining_wait_time.InSeconds())
1566 << " per policy.";
1567 return kWallClockWaitNotSatisfied;
1568}
1569
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001570bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001571 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001572
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001573 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1574 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1575 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001576 // We are unable to read the update check count from file for some reason.
1577 // So let's proceed anyway so as to not stall the update.
1578 LOG(ERROR) << "Unable to read update check count. "
1579 << "Skipping update-check-count-based-wait.";
1580 return true;
1581 }
1582 } else {
1583 // This file does not exist. This means we haven't started our update
1584 // check count down yet, so this is the right time to start the count down.
1585 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001586 params_->min_update_checks_needed(),
1587 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001588
1589 LOG(INFO) << "Randomly picked update check count value = "
1590 << update_check_count_value;
1591
1592 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001593 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1594 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001595 // We weren't able to write the update check count file for some reason.
1596 // So let's proceed anyway so as to not stall the update.
1597 LOG(ERROR) << "Unable to write update check count. "
1598 << "Skipping update-check-count-based-wait.";
1599 return true;
1600 }
1601 }
1602
1603 if (update_check_count_value == 0) {
1604 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1605 return true;
1606 }
1607
1608 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001609 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001610 // We err on the side of skipping scattering logic instead of stalling
1611 // a machine from receiving any updates in case of any unexpected state.
1612 LOG(ERROR) << "Invalid value for update check count detected. "
1613 << "Skipping update-check-count-based-wait.";
1614 return true;
1615 }
1616
1617 // Legal value, we need to wait for more update checks to happen
1618 // until this becomes 0.
1619 LOG(INFO) << "Deferring Omaha updates for another "
1620 << update_check_count_value
1621 << " update checks per policy";
1622 return false;
1623}
1624
David Zeuthen639aa362014-02-03 16:23:44 -08001625// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001626bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001627 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001628 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001629 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001630 &elapsed_days))
1631 return false;
1632
1633 if (elapsed_days < 0)
1634 return false;
1635
1636 output_object->install_date_days = elapsed_days;
1637 return true;
1638}
1639
1640// static
1641bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1642 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001643 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001644 return false;
1645
1646 return prefs->Exists(kPrefsInstallDateDays);
1647}
1648
1649// static
1650bool OmahaRequestAction::PersistInstallDate(
1651 SystemState *system_state,
1652 int install_date_days,
1653 InstallDateProvisioningSource source) {
1654 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1655
1656 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001657 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001658 return false;
1659
1660 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1661 return false;
1662
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001663 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001664 static_cast<int>(source), // Sample.
1665 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001666 return true;
1667}
1668
Alex Deymo8e18f932015-03-27 16:16:59 -07001669bool OmahaRequestAction::PersistCohortData(
1670 const string& prefs_key,
1671 const string& new_value) {
1672 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1673 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1674 return system_state_->prefs()->Delete(prefs_key);
1675 } else if (!new_value.empty()) {
1676 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1677 return system_state_->prefs()->SetString(prefs_key, new_value);
1678 }
1679 return true;
1680}
1681
Alex Deymob3fa53b2016-04-18 19:57:58 -07001682bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
Amin Hassani6600a562018-09-24 15:17:19 -07001683 auto eol_attr = attrs.find(kAttrEol);
Alex Deymob3fa53b2016-04-18 19:57:58 -07001684 if (eol_attr != attrs.end()) {
1685 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1686 eol_attr->second);
1687 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1688 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1689 }
1690 return true;
1691}
1692
David Zeuthen33bae492014-02-25 16:16:18 -08001693void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1694 // We only want to report this on "update check".
1695 if (ping_only_ || event_ != nullptr)
1696 return;
1697
1698 metrics::CheckResult result = metrics::CheckResult::kUnset;
1699 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1700 metrics::DownloadErrorCode download_error_code =
1701 metrics::DownloadErrorCode::kUnset;
1702
1703 // Regular update attempt.
1704 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001705 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001706 // OK, we parsed the response successfully but that does
1707 // necessarily mean that an update is available.
1708 if (HasOutputPipe()) {
1709 const OmahaResponse& response = GetOutputObject();
1710 if (response.update_exists) {
1711 result = metrics::CheckResult::kUpdateAvailable;
1712 reaction = metrics::CheckReaction::kUpdating;
1713 } else {
1714 result = metrics::CheckResult::kNoUpdateAvailable;
1715 }
1716 } else {
1717 result = metrics::CheckResult::kNoUpdateAvailable;
1718 }
1719 break;
1720
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001721 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
Weidong Guo421ff332017-04-17 10:08:38 -07001722 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
David Zeuthen33bae492014-02-25 16:16:18 -08001723 result = metrics::CheckResult::kUpdateAvailable;
1724 reaction = metrics::CheckReaction::kIgnored;
1725 break;
1726
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001727 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001728 result = metrics::CheckResult::kUpdateAvailable;
1729 reaction = metrics::CheckReaction::kDeferring;
1730 break;
1731
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001732 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001733 result = metrics::CheckResult::kUpdateAvailable;
1734 reaction = metrics::CheckReaction::kBackingOff;
1735 break;
1736
1737 default:
1738 // We report two flavors of errors, "Download errors" and "Parsing
1739 // error". Try to convert to the former and if that doesn't work
1740 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001741 metrics::DownloadErrorCode tmp_error =
1742 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001743 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1744 result = metrics::CheckResult::kDownloadError;
1745 download_error_code = tmp_error;
1746 } else {
1747 result = metrics::CheckResult::kParsingError;
1748 }
1749 break;
1750 }
1751
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001752 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1753 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001754}
1755
Toni Barzic61544e62018-10-11 14:37:30 -07001756bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1757 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001758 // Note: policy decision to not update to a version we rolled back from.
1759 string rollback_version =
1760 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001761 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001762 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001763 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001764 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001765 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001766 return true;
1767 }
1768 }
1769
Toni Barzic61544e62018-10-11 14:37:30 -07001770 if (system_state_->hardware()->IsOOBEEnabled() &&
1771 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
1772 (response.deadline.empty() ||
1773 system_state_->payload_state()->GetRollbackHappened()) &&
1774 params_->app_version() != "ForcedUpdate") {
1775 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1776 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1777 return true;
1778 }
1779
Weidong Guo421ff332017-04-17 10:08:38 -07001780 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001781 LOG(INFO) << "Update is not allowed over current connection.";
1782 return true;
1783 }
1784
1785 // Note: We could technically delete the UpdateFirstSeenAt state when we
1786 // return true. If we do, it'll mean a device has to restart the
1787 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1788 // turned on again. On the other hand, it also increases the chance of update
1789 // starvation if an admin turns AU on/off more frequently. We choose to err on
1790 // the side of preventing starvation at the cost of not applying scattering in
1791 // those cases.
1792 return false;
1793}
1794
Weidong Guo421ff332017-04-17 10:08:38 -07001795bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1796 const OmahaResponse& response) const {
1797 PrefsInterface* prefs = system_state_->prefs();
1798
1799 if (!prefs) {
1800 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1801 "not available.";
1802 return false;
1803 }
1804
1805 bool is_allowed;
1806
1807 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1808 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1809 is_allowed) {
1810 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1811 "set to true.";
1812 return true;
1813 }
1814
1815 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1816 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1817 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1818 "set to false or does not exist while target does not exist.";
1819 return false;
1820 }
1821
1822 std::string target_version;
1823 int64_t target_size;
1824
1825 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1826 &target_version) ||
1827 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1828 LOG(INFO) << "Disabling updates over cellular as the target version or "
1829 "size is not accessible.";
1830 return false;
1831 }
1832
1833 uint64_t total_packages_size = 0;
1834 for (const auto& package : response.packages) {
1835 total_packages_size += package.size;
1836 }
1837 if (target_version == response.version &&
1838 static_cast<uint64_t>(target_size) == total_packages_size) {
1839 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1840 "omaha response.";
1841 return true;
1842 } else {
1843 LOG(INFO) << "Disabling updates over cellular as the target does not"
1844 "match the omaha response.";
1845 return false;
1846 }
1847}
1848
1849bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1850 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001851 ConnectionType type;
1852 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001853 ConnectionManagerInterface* connection_manager =
1854 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001855 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001856 LOG(INFO) << "We could not determine our connection type. "
1857 << "Defaulting to allow updates.";
1858 return true;
1859 }
Weidong Guo421ff332017-04-17 10:08:38 -07001860
Chris Sosa77f79e82014-06-02 18:16:24 -07001861 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001862 bool is_device_policy_set =
1863 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1864 // Treats tethered connection as if it is cellular connection.
1865 bool is_over_cellular = type == ConnectionType::kCellular ||
1866 tethering == ConnectionTethering::kConfirmed;
1867
1868 if (!is_over_cellular) {
1869 // There's no need to further check user preferences as we are not over
1870 // cellular connection.
1871 if (!is_allowed)
1872 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1873 } else if (is_device_policy_set) {
1874 // There's no need to further check user preferences as the device policy
1875 // is set regarding updates over cellular.
1876 if (!is_allowed)
1877 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1878 } else {
1879 // Deivce policy is not set, so user preferences overwrite whether to
1880 // allow updates over cellular.
1881 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1882 if (!is_allowed)
1883 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1884 }
1885
Chris Sosa77f79e82014-06-02 18:16:24 -07001886 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001887 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001888 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1889 return is_allowed;
1890}
1891
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001892bool OmahaRequestAction::IsRollbackEnabled() const {
1893 if (policy_provider_->IsConsumerDevice()) {
1894 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1895 return false;
1896 }
1897
1898 if (!policy_provider_->device_policy_is_loaded()) {
1899 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1900 return true;
1901 }
1902
1903 int allowed_milestones;
1904 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1905 &allowed_milestones)) {
1906 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1907 "Defaulting to rollback enabled.";
1908 return true;
1909 }
1910
1911 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1912 return allowed_milestones > 0;
1913}
1914
1915void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001916 int max_kernel_rollforward;
1917 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001918 if (IsRollbackEnabled()) {
1919 // If rollback is enabled, set the max kernel key version to the current
1920 // kernel key version. This has the effect of freezing kernel key roll
1921 // forwards.
1922 //
1923 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1924 // key roll forward happens until the server side components of rollback
1925 // are implemented. Future changes will allow the Omaha server to return
1926 // the kernel key version from max_rollback_versions in the past. At that
1927 // point the max kernel key version will be set to that value, creating a
1928 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001929 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001930 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001931 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001932 } else {
1933 // For devices that are not rollback enabled (ie. consumer devices), the
1934 // max kernel key version is set to 0xfffffffe, which is logically
1935 // infinity. This maintains the previous behavior that that kernel key
1936 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001937 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001938 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001939 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001940 }
1941
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001942 bool max_rollforward_set =
1943 system_state_->hardware()->SetMaxKernelKeyRollforward(
1944 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001945 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001946 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001947 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001948 // Report metrics
1949 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1950 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001951}
1952
May Lippert60aa3ca2018-08-15 16:55:29 -07001953base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1954 Time update_first_seen_at;
1955 int64_t update_first_seen_at_int;
1956 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1957 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1958 &update_first_seen_at_int)) {
1959 // Note: This timestamp could be that of ANY update we saw in the past
1960 // (not necessarily this particular update we're considering to apply)
1961 // but never got to apply because of some reason (e.g. stop AU policy,
1962 // updates being pulled out from Omaha, changes in target version prefix,
1963 // new update being rolled out, etc.). But for the purposes of scattering
1964 // it doesn't matter which update the timestamp corresponds to. i.e.
1965 // the clock starts ticking the first time we see an update and we're
1966 // ready to apply when the random wait period is satisfied relative to
1967 // that first seen timestamp.
1968 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1969 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1970 << utils::ToString(update_first_seen_at);
1971 } else {
1972 // This seems like an unexpected error where the persisted value exists
1973 // but it's not readable for some reason.
1974 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1975 return base::Time();
1976 }
1977 } else {
1978 update_first_seen_at = system_state_->clock()->GetWallclockTime();
1979 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
1980 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1981 update_first_seen_at_int)) {
1982 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1983 << utils::ToString(update_first_seen_at);
1984 } else {
1985 // This seems like an unexpected error where the value cannot be
1986 // persisted for some reason.
1987 LOG(INFO) << "UpdateFirstSeenAt value "
1988 << utils::ToString(update_first_seen_at)
1989 << " cannot be persisted";
1990 return base::Time();
1991 }
1992 }
1993 return update_first_seen_at;
1994}
1995
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001996} // namespace chromeos_update_engine