blob: de02b5ec082859f0ab3b6c5a156830bcf4d40ee2 [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,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700152 int ping_active_days,
153 int ping_roll_call_days,
154 PrefsInterface* prefs) {
155 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700156 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700157 if (include_ping)
158 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700159 if (!ping_only) {
Marton Hunyadyba51c3f2018-04-25 15:18:10 +0200160 app_body += " <updatecheck";
161 if (!params->target_version_prefix().empty()) {
162 app_body += base::StringPrintf(
163 " targetversionprefix=\"%s\"",
164 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
165 // Rollback requires target_version_prefix set.
166 if (params->rollback_allowed()) {
167 app_body += " rollback_allowed=\"true\"";
168 }
169 }
170 app_body += "></updatecheck>\n";
Jay Srinivasan0a708742012-03-20 11:26:12 -0700171
Darin Petkov265f2902011-05-09 15:17:40 -0700172 // If this is the first update check after a reboot following a previous
173 // update, generate an event containing the previous version number. If
174 // the previous version preference file doesn't exist the event is still
175 // generated with a previous version of 0.0.0.0 -- this is relevant for
176 // older clients or new installs. The previous version event is not sent
177 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700178 // rebooted. The previous version event is also not sent if it was already
179 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700180 string prev_version;
181 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
182 prev_version = "0.0.0.0";
183 }
Alex Deymo87c08862015-10-30 21:56:55 -0700184 // We only store a non-empty previous version value after a successful
185 // update in the previous boot. After reporting it back to the server,
186 // we clear the previous version value so it doesn't get reported again.
187 if (!prev_version.empty()) {
188 app_body += base::StringPrintf(
189 " <event eventtype=\"%d\" eventresult=\"%d\" "
190 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800191 OmahaEvent::kTypeRebootedAfterUpdate,
192 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700193 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
194 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
195 << "Unable to reset the previous version.";
196 }
Darin Petkov95508da2011-01-05 12:42:29 -0800197 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700198 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800199 // The error code is an optional attribute so append it only if the result
200 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700201 string error_code;
202 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700203 error_code = base::StringPrintf(" errorcode=\"%d\"",
204 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700205 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700206 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700207 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700208 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700209 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700210
211 return app_body;
212}
213
Alex Deymo8e18f932015-03-27 16:16:59 -0700214// Returns the cohort* argument to include in the <app> tag for the passed
215// |arg_name| and |prefs_key|, if any. The return value is suitable to
216// concatenate to the list of arguments and includes a space at the end.
217string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700218 const string arg_name,
219 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700220 // There's nothing wrong with not having a given cohort setting, so we check
Sen Jiang771f6482018-04-04 17:59:10 -0700221 // existence first to avoid the warning log message.
Alex Deymo8e18f932015-03-27 16:16:59 -0700222 if (!prefs->Exists(prefs_key))
223 return "";
224 string cohort_value;
225 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
226 return "";
227 // This is a sanity check to avoid sending a huge XML file back to Ohama due
228 // to a compromised stateful partition making the update check fail in low
229 // network environments envent after a reboot.
230 if (cohort_value.size() > 1024) {
231 LOG(WARNING) << "The omaha cohort setting " << arg_name
232 << " has a too big value, which must be an error or an "
233 "attacker trying to inhibit updates.";
234 return "";
235 }
236
Alex Deymob0d74eb2015-03-30 17:59:17 -0700237 string escaped_xml_value;
238 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
239 LOG(WARNING) << "The omaha cohort setting " << arg_name
240 << " is ASCII-7 invalid, ignoring it.";
241 return "";
242 }
243
Alex Deymo8e18f932015-03-27 16:16:59 -0700244 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700245 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700246}
247
Sen Jiang94a4dec2017-03-28 18:23:35 -0700248struct OmahaAppData {
249 string id;
250 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700251 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700252};
253
Sen Jiang684c9cd2017-10-17 16:26:45 -0700254bool IsValidComponentID(const string& id) {
255 for (char c : id) {
256 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
257 return false;
258 }
259 return true;
260}
261
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700262// Returns an XML that corresponds to the entire <app> node of the Omaha
263// request based on the given parameters.
264string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700265 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700266 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700267 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700268 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700269 int ping_active_days,
270 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800271 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700272 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700273 string app_body = GetAppBody(event, params, ping_only, include_ping,
274 ping_active_days, ping_roll_call_days,
275 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700276 string app_versions;
277
Sen Jiang8cd42342018-01-31 12:06:59 -0800278 // If we are downgrading to a more stable channel and we are allowed to do
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700279 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
280 // highest-versioned payload on the destination channel.
Sen Jiang8500d3a2018-02-08 12:04:05 -0800281 if (params->ShouldPowerwash()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700282 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
283 << "on downgrading to the version in the more stable channel";
284 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700285 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700286 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700287 app_versions = "version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700288 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700289 }
290
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700291 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700292 string app_channels =
293 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
294 if (params->current_channel() != download_channel) {
295 app_channels += "from_track=\"" + XmlEncodeWithDefault(
296 params->current_channel(), "") + "\" ";
297 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700298
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700299 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700300
David Zeuthen639aa362014-02-03 16:23:44 -0800301 // If install_date_days is not set (e.g. its value is -1 ), don't
302 // include the attribute.
303 string install_date_in_days_str = "";
304 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700305 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
306 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800307 }
308
Alex Deymo8e18f932015-03-27 16:16:59 -0700309 string app_cohort_args;
310 app_cohort_args += GetCohortArgXml(system_state->prefs(),
311 "cohort", kPrefsOmahaCohort);
312 app_cohort_args += GetCohortArgXml(system_state->prefs(),
313 "cohorthint", kPrefsOmahaCohortHint);
314 app_cohort_args += GetCohortArgXml(system_state->prefs(),
315 "cohortname", kPrefsOmahaCohortName);
316
Alex Deymoebf6e122017-03-10 16:12:01 -0800317 string fingerprint_arg;
318 if (!params->os_build_fingerprint().empty()) {
Sen Jiang8cd42342018-01-31 12:06:59 -0800319 fingerprint_arg = "fingerprint=\"" +
320 XmlEncodeWithDefault(params->os_build_fingerprint(), "") +
321 "\" ";
Alex Deymoebf6e122017-03-10 16:12:01 -0800322 }
323
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700324 string buildtype_arg;
325 if (!params->os_build_type().empty()) {
326 buildtype_arg = "os_build_type=\"" +
327 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
328 }
329
Sen Jiang684c9cd2017-10-17 16:26:45 -0700330 string product_components_args;
Sen Jiang8500d3a2018-02-08 12:04:05 -0800331 if (!params->ShouldPowerwash() && !app_data.product_components.empty()) {
Sen Jiang684c9cd2017-10-17 16:26:45 -0700332 brillo::KeyValueStore store;
333 if (store.LoadFromString(app_data.product_components)) {
334 for (const string& key : store.GetKeys()) {
335 if (!IsValidComponentID(key)) {
336 LOG(ERROR) << "Invalid component id: " << key;
337 continue;
338 }
339 string version;
340 if (!store.GetString(key, &version)) {
341 LOG(ERROR) << "Failed to get version for " << key
342 << " in product_components.";
343 continue;
344 }
345 product_components_args +=
346 base::StringPrintf("_%s.version=\"%s\" ",
347 key.c_str(),
348 XmlEncodeWithDefault(version, "").c_str());
349 }
350 } else {
351 LOG(ERROR) << "Failed to parse product_components:\n"
352 << app_data.product_components;
353 }
354 }
355
356 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700357 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700358 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700359 app_cohort_args +
360 app_versions +
361 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700362 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800363 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700364 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700365 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
366 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
367 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
368 "delta_okay=\"" + delta_okay_str + "\" "
369 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
370 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
371 install_date_in_days_str +
372 ">\n" +
373 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700374 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700375 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700376 return app_xml;
377}
378
379// Returns an XML that corresponds to the entire <os> node of the Omaha
380// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700381string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700382 string os_xml =" <os "
383 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
384 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
385 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
386 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700387 return os_xml;
388}
389
390// Returns an XML that corresponds to the entire Omaha request based on the
391// given parameters.
392string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700393 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700394 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700395 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700396 int ping_active_days,
397 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800398 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700399 SystemState* system_state) {
400 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700401 OmahaAppData product_app = {
402 .id = params->GetAppId(),
403 .version = params->app_version(),
404 .product_components = params->product_components()};
Xiaochu Liu88d90382018-08-29 16:09:11 -0700405 // TODO(xiaochu): send update check flag only when operation is update.
Sen Jiang94a4dec2017-03-28 18:23:35 -0700406 string app_xml = GetAppXml(event,
407 params,
408 product_app,
409 ping_only,
410 include_ping,
411 ping_active_days,
412 ping_roll_call_days,
413 install_date_in_days,
414 system_state);
415 if (!params->system_app_id().empty()) {
416 OmahaAppData system_app = {.id = params->system_app_id(),
417 .version = params->system_version()};
418 app_xml += GetAppXml(event,
419 params,
420 system_app,
421 ping_only,
422 include_ping,
423 ping_active_days,
424 ping_roll_call_days,
425 install_date_in_days,
426 system_state);
427 }
Xiaochu Liu88d90382018-08-29 16:09:11 -0700428 // Create APP ID according to |dlc_id| (sticking the current AppID to the DLC
429 // ID with an underscode).
430 for (const auto& dlc_id : params->dlc_ids()) {
431 OmahaAppData dlc_app = {.id = params->GetAppId() + "_" + dlc_id,
432 .version = params->app_version()};
433 app_xml += GetAppXml(event,
434 params,
435 dlc_app,
436 ping_only,
437 include_ping,
438 ping_active_days,
439 ping_roll_call_days,
440 install_date_in_days,
441 system_state);
442 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700443
Alex Vakulenko75039d72014-03-25 12:36:28 -0700444 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700445 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700446
Alex Deymoac41a822015-09-15 20:52:53 -0700447 string updater_version = XmlEncodeWithDefault(
448 base::StringPrintf("%s-%s",
449 constants::kOmahaUpdaterID,
450 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700451 string request_xml =
452 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700453 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700454 "version=\"" + updater_version + "\" "
455 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700456 install_source +
457 "ismachine=\"1\">\n") +
458 os_xml +
459 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700460 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700461
462 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000463}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700464
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700465} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000466
David Zeuthene8ed8632014-07-24 13:38:10 -0400467// Struct used for holding data obtained when parsing the XML.
468struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400469 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
470
471 // Pointer to the expat XML_Parser object.
472 XML_Parser xml_parser;
473
David Zeuthene8ed8632014-07-24 13:38:10 -0400474 // This is the state of the parser as it's processing the XML.
475 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400476 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400477 string current_path;
478
479 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400480 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700481 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400482 string daystart_elapsed_days;
483 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800484
Sen Jiang81259682017-03-30 15:11:30 -0700485 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700486 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700487 vector<string> url_codebase;
488 string manifest_version;
489 map<string, string> action_postinstall_attrs;
490 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700491 string cohort;
492 string cohorthint;
493 string cohortname;
494 bool cohort_set = false;
495 bool cohorthint_set = false;
496 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700497
498 struct Package {
499 string name;
500 string size;
501 string hash;
502 };
503 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800504 };
Sen Jiang81259682017-03-30 15:11:30 -0700505 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400506};
507
508namespace {
509
510// Callback function invoked by expat.
511void ParserHandlerStart(void* user_data, const XML_Char* element,
512 const XML_Char** attr) {
513 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
514
515 if (data->failed)
516 return;
517
518 data->current_path += string("/") + element;
519
520 map<string, string> attrs;
521 if (attr != nullptr) {
522 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
523 string key = attr[n];
524 string value = attr[n + 1];
525 attrs[key] = value;
526 }
527 }
528
Alex Deymo8e18f932015-03-27 16:16:59 -0700529 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700530 OmahaParserData::App app;
Amin Hassani6600a562018-09-24 15:17:19 -0700531 if (attrs.find(kAttrAppId) != attrs.end()) {
532 app.id = attrs[kAttrAppId];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700533 }
Amin Hassani6600a562018-09-24 15:17:19 -0700534 if (attrs.find(kAttrCohort) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700535 app.cohort_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700536 app.cohort = attrs[kAttrCohort];
Alex Deymo8e18f932015-03-27 16:16:59 -0700537 }
Amin Hassani6600a562018-09-24 15:17:19 -0700538 if (attrs.find(kAttrCohortHint) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700539 app.cohorthint_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700540 app.cohorthint = attrs[kAttrCohortHint];
Alex Deymo8e18f932015-03-27 16:16:59 -0700541 }
Amin Hassani6600a562018-09-24 15:17:19 -0700542 if (attrs.find(kAttrCohortName) != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700543 app.cohortname_set = true;
Amin Hassani6600a562018-09-24 15:17:19 -0700544 app.cohortname = attrs[kAttrCohortName];
Alex Deymo8e18f932015-03-27 16:16:59 -0700545 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700546 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700547 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700548 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700549 data->apps.back().updatecheck_status = attrs[kAttrStatus];
Sen Jiang81259682017-03-30 15:11:30 -0700550 if (data->updatecheck_poll_interval.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700551 data->updatecheck_poll_interval = attrs[kAttrPollInterval];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700552 // Omaha sends arbitrary key-value pairs as extra attributes starting with
553 // an underscore.
554 for (const auto& attr : attrs) {
555 if (!attr.first.empty() && attr.first[0] == '_')
556 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
557 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400558 } else if (data->current_path == "/response/daystart") {
559 // Get the install-date.
Amin Hassani6600a562018-09-24 15:17:19 -0700560 data->daystart_elapsed_days = attrs[kAttrElapsedDays];
561 data->daystart_elapsed_seconds = attrs[kAttrElapsedSeconds];
David Zeuthene8ed8632014-07-24 13:38:10 -0400562 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
563 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700564 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700565 data->apps.back().url_codebase.push_back(attrs[kAttrCodeBase]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800566 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400567 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800568 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700569 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700570 data->apps.back().packages.push_back({.name = attrs[kAttrName],
571 .size = attrs[kAttrSize],
572 .hash = attrs[kAttrHashSha256]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400573 } else if (data->current_path == "/response/app/updatecheck/manifest") {
574 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700575 if (!data->apps.empty())
Amin Hassani6600a562018-09-24 15:17:19 -0700576 data->apps.back().manifest_version = attrs[kAttrVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400577 } else if (data->current_path ==
578 "/response/app/updatecheck/manifest/actions/action") {
579 // We only care about the postinstall action.
Amin Hassani6600a562018-09-24 15:17:19 -0700580 if (attrs[kAttrEvent] == kValPostInstall && !data->apps.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -0700581 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400582 }
583 }
584}
585
586// Callback function invoked by expat.
587void ParserHandlerEnd(void* user_data, const XML_Char* element) {
588 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
589 if (data->failed)
590 return;
591
592 const string path_suffix = string("/") + element;
593
Alex Vakulenko0103c362016-01-20 07:56:15 -0800594 if (!base::EndsWith(data->current_path, path_suffix,
595 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400596 LOG(ERROR) << "Unexpected end element '" << element
597 << "' with current_path='" << data->current_path << "'";
598 data->failed = true;
599 return;
600 }
601 data->current_path.resize(data->current_path.size() - path_suffix.size());
602}
603
David Zeuthenf3e28012014-08-26 18:23:52 -0400604// Callback function invoked by expat.
605//
606// This is called for entity declarations. Since Omaha is guaranteed
607// to never return any XML with entities our course of action is to
608// just stop parsing. This avoids potential resource exhaustion
609// problems AKA the "billion laughs". CVE-2013-0340.
610void ParserHandlerEntityDecl(void *user_data,
611 const XML_Char *entity_name,
612 int is_parameter_entity,
613 const XML_Char *value,
614 int value_length,
615 const XML_Char *base,
616 const XML_Char *system_id,
617 const XML_Char *public_id,
618 const XML_Char *notation_name) {
619 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
620
621 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
622 data->failed = true;
623 data->entity_decl = true;
624 XML_StopParser(data->xml_parser, false);
625}
626
David Zeuthene8ed8632014-07-24 13:38:10 -0400627} // namespace
628
Alex Deymob0d74eb2015-03-30 17:59:17 -0700629bool XmlEncode(const string& input, string* output) {
630 if (std::find_if(input.begin(), input.end(),
631 [](const char c){return c & 0x80;}) != input.end()) {
632 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
633 utils::HexDumpString(input);
634 return false;
635 }
Alex Deymocc457852015-06-18 18:35:50 -0700636 output->clear();
637 // We need at least input.size() space in the output, but the code below will
638 // handle it if we need more.
639 output->reserve(input.size());
640 for (char c : input) {
641 switch (c) {
642 case '\"':
643 output->append("&quot;");
644 break;
645 case '\'':
646 output->append("&apos;");
647 break;
648 case '&':
649 output->append("&amp;");
650 break;
651 case '<':
652 output->append("&lt;");
653 break;
654 case '>':
655 output->append("&gt;");
656 break;
657 default:
658 output->push_back(c);
659 }
660 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700661 return true;
662}
663
664string XmlEncodeWithDefault(const string& input, const string& default_value) {
665 string output;
666 if (XmlEncode(input, &output))
667 return output;
668 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000669}
670
Alex Deymoc1c17b42015-11-23 03:53:15 -0300671OmahaRequestAction::OmahaRequestAction(
672 SystemState* system_state,
673 OmahaEvent* event,
674 std::unique_ptr<HttpFetcher> http_fetcher,
675 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800676 : system_state_(system_state),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800677 params_(system_state->request_params()),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700678 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300679 http_fetcher_(std::move(http_fetcher)),
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800680 policy_provider_(std::make_unique<policy::PolicyProvider>()),
Thieu Le116fda32011-04-19 11:01:54 -0700681 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700682 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700683 ping_roll_call_days_(0) {
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -0800684 policy_provider_->Reload();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700685}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000686
Darin Petkov6a5b3222010-07-13 14:55:28 -0700687OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000688
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700689// Calculates the value to use for the ping days parameter.
690int OmahaRequestAction::CalculatePingDays(const string& key) {
691 int days = kNeverPinged;
692 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800693 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700694 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
695 if (days < 0) {
696 // If |days| is negative, then the system clock must have jumped
697 // back in time since the ping was sent. Mark the value so that
698 // it doesn't get sent to the server but we still update the
699 // last ping daystart preference. This way the next ping time
700 // will be correct, hopefully.
701 days = kPingTimeJump;
702 LOG(WARNING) <<
703 "System clock jumped back in time. Resetting ping daystarts.";
704 }
705 }
706 return days;
707}
708
709void OmahaRequestAction::InitPingDays() {
710 // We send pings only along with update checks, not with events.
711 if (IsEvent()) {
712 return;
713 }
714 // TODO(petkov): Figure a way to distinguish active use pings
715 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700716 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700717 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
718 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
719}
720
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700721bool OmahaRequestAction::ShouldPing() const {
722 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
723 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
724 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
725 if (powerwash_count > 0) {
726 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
727 << "powerwash_count is " << powerwash_count;
728 return false;
729 }
Amin Hassani1677e812017-06-21 13:36:36 -0700730 if (system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
731 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
732 << "the first_active_omaha_ping_sent is true";
733 return false;
734 }
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700735 return true;
736 }
737 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
738}
739
David Zeuthen639aa362014-02-03 16:23:44 -0800740// static
741int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
742 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700743 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800744 return -1;
745
746 // If we have the value stored on disk, just return it.
747 int64_t stored_value;
748 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
749 // Convert and sanity-check.
750 int install_date_days = static_cast<int>(stored_value);
751 if (install_date_days >= 0)
752 return install_date_days;
753 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
754 << install_date_days << " looks suspicious.";
755 prefs->Delete(kPrefsInstallDateDays);
756 }
757
758 // Otherwise, if OOBE is not complete then do nothing and wait for
759 // ParseResponse() to call ParseInstallDate() and then
760 // PersistInstallDate() to set the kPrefsInstallDateDays state
761 // variable. Once that is done, we'll then report back in future
762 // Omaha requests. This works exactly because OOBE triggers an
763 // update check.
764 //
765 // However, if OOBE is complete and the kPrefsInstallDateDays state
766 // variable is not set, there are two possibilities
767 //
768 // 1. The update check in OOBE failed so we never got a response
769 // from Omaha (no network etc.); or
770 //
771 // 2. OOBE was done on an older version that didn't write to the
772 // kPrefsInstallDateDays state variable.
773 //
774 // In both cases, we approximate the install date by simply
775 // inspecting the timestamp of when OOBE happened.
776
777 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700778 if (!system_state->hardware()->IsOOBEEnabled() ||
779 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800780 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700781 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800782 return -1;
783 }
784
785 int num_days;
786 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
787 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
788 << "as its value '" << utils::ToString(time_of_oobe)
789 << "' looks suspicious.";
790 return -1;
791 }
792
793 // Persist this to disk, for future use.
794 if (!OmahaRequestAction::PersistInstallDate(system_state,
795 num_days,
796 kProvisionedFromOOBEMarker))
797 return -1;
798
799 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
800 << num_days << " days";
801
802 return num_days;
803}
804
Darin Petkov6a5b3222010-07-13 14:55:28 -0700805void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000806 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700807 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700808 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700809 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700810 return;
811 }
David Zeuthen639aa362014-02-03 16:23:44 -0800812
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700813 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700814 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700815 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700816 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700817 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800818 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800819 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700820 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700821
Sen Jiang42fa45e2018-03-12 11:02:14 -0700822 // Set X-Goog-Update headers.
Alex Deymo14ad88e2016-06-29 12:30:14 -0700823 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
824 params_->interactive() ? "fg" : "bg");
825 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
826 http_fetcher_->SetHeader(
827 kXGoogleUpdateUpdater,
828 base::StringPrintf(
829 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
830
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800831 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
832 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700833 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700834 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700835 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000836}
837
Darin Petkov6a5b3222010-07-13 14:55:28 -0700838void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000839 http_fetcher_->TerminateTransfer();
840}
841
842// We just store the response in the buffer. Once we've received all bytes,
843// we'll look in the buffer and decide what to do.
Amin Hassani0cd9d772018-07-31 23:55:43 -0700844bool OmahaRequestAction::ReceivedBytes(HttpFetcher* fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800845 const void* bytes,
846 size_t length) {
847 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
848 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
Amin Hassani0cd9d772018-07-31 23:55:43 -0700849 return true;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000850}
851
852namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000853
854// Parses a 64 bit base-10 int from a string and returns it. Returns 0
855// on error. If the string contains "0", that's indistinguishable from
856// error.
857off_t ParseInt(const string& str) {
858 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700859 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000860 if (rc < 1) {
861 // failure
862 return 0;
863 }
864 return ret;
865}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700866
David Zeuthene8ed8632014-07-24 13:38:10 -0400867// Parses |str| and returns |true| if, and only if, its value is "true".
868bool ParseBool(const string& str) {
869 return str == "true";
870}
871
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700872// Update the last ping day preferences based on the server daystart
873// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400874bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700875 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400876 TEST_AND_RETURN_FALSE(
877 base::StringToInt64(parser_data->daystart_elapsed_seconds,
878 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700879 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
880
881 // Remember the local time that matches the server's last midnight
882 // time.
883 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
884 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
885 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
886 return true;
887}
Sen Jiang81259682017-03-30 15:11:30 -0700888
889// Parses the package node in the given XML document and populates
890// |output_object| if valid. Returns true if we should continue the parsing.
891// False otherwise, in which case it sets any error code using |completer|.
892bool ParsePackage(OmahaParserData::App* app,
893 OmahaResponse* output_object,
894 ScopedActionCompleter* completer) {
Amin Hassani6600a562018-09-24 15:17:19 -0700895 if (app->updatecheck_status == kValNoUpdate) {
Sen Jiang81259682017-03-30 15:11:30 -0700896 if (!app->packages.empty()) {
897 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
898 completer->set_code(ErrorCode::kOmahaResponseInvalid);
899 return false;
900 }
901 return true;
902 }
903 if (app->packages.empty()) {
904 LOG(ERROR) << "Omaha Response has no packages";
905 completer->set_code(ErrorCode::kOmahaResponseInvalid);
906 return false;
907 }
908 if (app->url_codebase.empty()) {
909 LOG(ERROR) << "No Omaha Response URLs";
910 completer->set_code(ErrorCode::kOmahaResponseInvalid);
911 return false;
912 }
913 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
914 vector<string> metadata_sizes =
Amin Hassani6600a562018-09-24 15:17:19 -0700915 base::SplitString(app->action_postinstall_attrs[kAttrMetadataSize],
Sen Jiang81259682017-03-30 15:11:30 -0700916 ":",
917 base::TRIM_WHITESPACE,
918 base::SPLIT_WANT_ALL);
Amin Hassani6600a562018-09-24 15:17:19 -0700919 vector<string> metadata_signatures = base::SplitString(
920 app->action_postinstall_attrs[kAttrMetadataSignatureRsa],
921 ":",
922 base::TRIM_WHITESPACE,
923 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700924 vector<string> is_delta_payloads =
Amin Hassani6600a562018-09-24 15:17:19 -0700925 base::SplitString(app->action_postinstall_attrs[kAttrIsDeltaPayload],
Sen Jiangcdd52062017-05-18 15:33:10 -0700926 ":",
927 base::TRIM_WHITESPACE,
928 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700929 for (size_t i = 0; i < app->packages.size(); i++) {
930 const auto& package = app->packages[i];
931 if (package.name.empty()) {
932 LOG(ERROR) << "Omaha Response has empty package name";
933 completer->set_code(ErrorCode::kOmahaResponseInvalid);
934 return false;
935 }
936 LOG(INFO) << "Found package " << package.name;
937
938 OmahaResponse::Package out_package;
939 for (const string& codebase : app->url_codebase) {
940 if (codebase.empty()) {
941 LOG(ERROR) << "Omaha Response URL has empty codebase";
942 completer->set_code(ErrorCode::kOmahaResponseInvalid);
943 return false;
944 }
945 out_package.payload_urls.push_back(codebase + package.name);
946 }
947 // Parse the payload size.
948 base::StringToUint64(package.size, &out_package.size);
949 if (out_package.size <= 0) {
950 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
951 completer->set_code(ErrorCode::kOmahaResponseInvalid);
952 return false;
953 }
954 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
955
956 if (i < metadata_sizes.size())
957 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
958 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
959 << " bytes";
960
961 if (i < metadata_signatures.size())
962 out_package.metadata_signature = metadata_signatures[i];
963 LOG(INFO) << "Payload metadata signature = "
964 << out_package.metadata_signature;
965
966 out_package.hash = package.hash;
967 if (out_package.hash.empty()) {
968 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
969 completer->set_code(ErrorCode::kOmahaResponseInvalid);
970 return false;
971 }
972 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700973
974 if (i < is_delta_payloads.size())
975 out_package.is_delta = ParseBool(is_delta_payloads[i]);
976 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
977
Sen Jiang81259682017-03-30 15:11:30 -0700978 output_object->packages.push_back(std::move(out_package));
979 }
980
981 return true;
982}
983
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700984// Parses the 2 key version strings kernel_version and firmware_version. If the
985// field is not present, or cannot be parsed the values default to 0xffff.
986void ParseRollbackVersions(OmahaParserData* parser_data,
987 OmahaResponse* output_object) {
988 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700989 parser_data->updatecheck_attrs[kAttrFirmwareVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700990 &output_object->rollback_key_version.firmware_key,
991 &output_object->rollback_key_version.firmware);
992 utils::ParseRollbackKeyVersion(
Amin Hassani6600a562018-09-24 15:17:19 -0700993 parser_data->updatecheck_attrs[kAttrKernelVersion],
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -0700994 &output_object->rollback_key_version.kernel_key,
995 &output_object->rollback_key_version.kernel);
996}
997
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700998} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000999
David Zeuthene8ed8632014-07-24 13:38:10 -04001000bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001001 OmahaResponse* output_object,
1002 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001003 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001004 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001005 return false;
1006 }
Sen Jiang81259682017-03-30 15:11:30 -07001007 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001008
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001009 // chromium-os:37289: The PollInterval is not supported by Omaha server
1010 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -07001011 // slow down the request rate from the server-side. Note that the PollInterval
1012 // is not persisted, so it has to be sent by the server on every response to
1013 // guarantee that the scheduler uses this value (otherwise, if the device got
1014 // rebooted after the last server-indicated value, it'll revert to the default
1015 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
1016 // based on the assumption that we perform an update check every hour so that
1017 // the max value of 8 will roughly be equivalent to one work day. If we decide
1018 // to use PollInterval permanently, we should update the
1019 // max_update_checks_allowed to take PollInterval into account. Note: The
1020 // parsing for PollInterval happens even before parsing of the status because
1021 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -04001022 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001023 &output_object->poll_interval);
1024
David Zeuthen639aa362014-02-03 16:23:44 -08001025 // Check for the "elapsed_days" attribute in the "daystart"
1026 // element. This is the number of days since Jan 1 2007, 0:00
1027 // PST. If we don't have a persisted value of the Omaha InstallDate,
1028 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -04001029 if (ParseInstallDate(parser_data, output_object) &&
1030 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -08001031 // Since output_object->install_date_days is never negative, the
1032 // elapsed_days -> install-date calculation is reduced to simply
1033 // rounding down to the nearest number divisible by 7.
1034 int remainder = output_object->install_date_days % 7;
1035 int install_date_days_rounded =
1036 output_object->install_date_days - remainder;
1037 if (PersistInstallDate(system_state_,
1038 install_date_days_rounded,
1039 kProvisionedFromOmahaResponse)) {
1040 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
1041 << install_date_days_rounded << " days";
1042 }
1043 }
1044
Alex Deymo00d79ac2015-06-29 15:41:49 -07001045 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -07001046 for (const auto& app : parser_data->apps) {
1047 if (app.id == params_->GetAppId()) {
1048 if (app.cohort_set)
1049 PersistCohortData(kPrefsOmahaCohort, app.cohort);
1050 if (app.cohorthint_set)
1051 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
1052 if (app.cohortname_set)
1053 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
1054 break;
1055 }
1056 }
Alex Deymo00d79ac2015-06-29 15:41:49 -07001057
Alex Deymob3fa53b2016-04-18 19:57:58 -07001058 // Parse the updatecheck attributes.
1059 PersistEolStatus(parser_data->updatecheck_attrs);
Marton Hunyady199152d2018-05-07 19:08:48 +02001060 // Rollback-related updatecheck attributes.
1061 // Defaults to false if attribute is not present.
1062 output_object->is_rollback =
Amin Hassani6600a562018-09-24 15:17:19 -07001063 ParseBool(parser_data->updatecheck_attrs[kAttrRollback]);
Zentaro Kavanagh0ff621c2018-07-13 13:06:56 -07001064
1065 // Parses the rollback versions of the current image. If the fields do not
1066 // exist they default to 0xffff for the 4 key versions.
1067 ParseRollbackVersions(parser_data, output_object);
Alex Deymob3fa53b2016-04-18 19:57:58 -07001068
David Zeuthene8ed8632014-07-24 13:38:10 -04001069 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001070 return false;
1071
David Zeuthene8ed8632014-07-24 13:38:10 -04001072 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001073 return false;
1074
Sen Jiang0affc2c2017-02-10 15:55:05 -08001075 // Package has to be parsed after Params now because ParseParams need to make
1076 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -07001077 for (auto& app : parser_data->apps)
1078 if (!ParsePackage(&app, output_object, completer))
1079 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001080
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001081 return true;
1082}
1083
David Zeuthene8ed8632014-07-24 13:38:10 -04001084bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001085 OmahaResponse* output_object,
1086 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001087 output_object->update_exists = false;
1088 for (size_t i = 0; i < parser_data->apps.size(); i++) {
1089 const string& status = parser_data->apps[i].updatecheck_status;
Amin Hassani6600a562018-09-24 15:17:19 -07001090 if (status == kValNoUpdate) {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001091 // Don't update if any app has status="noupdate".
Sen Jiang81259682017-03-30 15:11:30 -07001092 LOG(INFO) << "No update for <app> " << i;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001093 output_object->update_exists = false;
1094 break;
Sen Jiang81259682017-03-30 15:11:30 -07001095 } else if (status == "ok") {
Amin Hassani6600a562018-09-24 15:17:19 -07001096 if (parser_data->apps[i].action_postinstall_attrs[kAttrNoUpdate] ==
1097 "true") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001098 // noupdate="true" in postinstall attributes means it's an update to
1099 // self, only update if there's at least one app really have update.
1100 LOG(INFO) << "Update to self for <app> " << i;
1101 } else {
1102 LOG(INFO) << "Update for <app> " << i;
1103 output_object->update_exists = true;
1104 }
Sen Jiang81259682017-03-30 15:11:30 -07001105 } else {
1106 LOG(ERROR) << "Unknown Omaha response status: " << status;
1107 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1108 return false;
1109 }
1110 }
1111 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001112 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001113 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001114 }
1115
Sen Jiang81259682017-03-30 15:11:30 -07001116 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001117}
1118
David Zeuthene8ed8632014-07-24 13:38:10 -04001119bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001120 OmahaResponse* output_object,
1121 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001122 map<string, string> attrs;
1123 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001124 if (app.id == params_->GetAppId()) {
1125 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001126 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001127 } else if (!params_->system_app_id().empty() &&
1128 app.id == params_->system_app_id()) {
1129 // this is the system app (this check is intentionally skipped if there is
1130 // no system_app_id set)
1131 output_object->system_version = app.manifest_version;
1132 }
1133 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001134 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001135 }
Sen Jiang81259682017-03-30 15:11:30 -07001136 }
Chris Sosa3b748432013-06-20 16:42:59 -07001137 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001138 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001139 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001140 return false;
1141 }
1142
1143 LOG(INFO) << "Received omaha response to update to version "
1144 << output_object->version;
1145
David Zeuthene8ed8632014-07-24 13:38:10 -04001146 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001147 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001148 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001149 return false;
1150 }
1151
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001152 // Get the optional properties one by one.
Amin Hassani6600a562018-09-24 15:17:19 -07001153 output_object->more_info_url = attrs[kAttrMoreInfo];
1154 output_object->prompt = ParseBool(attrs[kAttrPrompt]);
1155 output_object->deadline = attrs[kAttrDeadline];
1156 output_object->max_days_to_scatter = ParseInt(attrs[kAttrMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001157 output_object->disable_p2p_for_downloading =
Amin Hassani6600a562018-09-24 15:17:19 -07001158 ParseBool(attrs[kAttrDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001159 output_object->disable_p2p_for_sharing =
Amin Hassani6600a562018-09-24 15:17:19 -07001160 ParseBool(attrs[kAttrDisableP2PForSharing]);
1161 output_object->public_key_rsa = attrs[kAttrPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001162
Amin Hassani6600a562018-09-24 15:17:19 -07001163 string max = attrs[kAttrMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001164 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001165 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001166
Jay Srinivasan08262882012-12-28 19:29:43 -08001167 output_object->disable_payload_backoff =
Amin Hassani6600a562018-09-24 15:17:19 -07001168 ParseBool(attrs[kAttrDisablePayloadBackoff]);
1169 output_object->powerwash_required = ParseBool(attrs[kAttrPowerwash]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001170
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001171 return true;
1172}
1173
David Zeuthene8ed8632014-07-24 13:38:10 -04001174// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001175// and fill in the appropriate fields of the output object. Also, notifies
1176// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001177void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1178 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001179 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001180 string current_response(response_buffer_.begin(), response_buffer_.end());
1181 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001182
Gilad Arnold74b5f552014-10-07 08:17:16 -07001183 PayloadStateInterface* const payload_state = system_state_->payload_state();
1184
Zentaro Kavanagh76af2662018-05-15 10:54:53 -07001185 // Set the max kernel key version based on whether rollback is allowed.
1186 SetMaxKernelKeyVersionForRollback();
1187
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001188 // Events are best effort transactions -- assume they always succeed.
1189 if (IsEvent()) {
1190 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001191 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001192 return;
1193 }
1194
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001195 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001196 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001197 int code = GetHTTPResponseCode();
1198 // Makes sure we send sane error values.
1199 if (code < 0 || code >= 1000) {
1200 code = 999;
1201 }
David Zeuthena99981f2013-04-29 13:42:47 -07001202 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001203 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001204 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001205 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001206
David Zeuthene8ed8632014-07-24 13:38:10 -04001207 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001208 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001209 XML_SetUserData(parser, &parser_data);
1210 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001211 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001212 XML_Status res = XML_Parse(
1213 parser,
1214 reinterpret_cast<const char*>(response_buffer_.data()),
1215 response_buffer_.size(),
1216 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001217
1218 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001219 LOG(ERROR) << "Omaha response not valid XML: "
1220 << XML_ErrorString(XML_GetErrorCode(parser))
1221 << " at line " << XML_GetCurrentLineNumber(parser)
1222 << " col " << XML_GetCurrentColumnNumber(parser);
Amin Hassani91f48b42018-08-06 17:47:14 -07001223 XML_ParserFree(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001224 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1225 if (response_buffer_.empty()) {
1226 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1227 } else if (parser_data.entity_decl) {
1228 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1229 }
1230 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001231 return;
1232 }
Amin Hassani91f48b42018-08-06 17:47:14 -07001233 XML_ParserFree(parser);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001234
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001235 // Update the last ping day preferences based on the server daystart response
1236 // even if we didn't send a ping. Omaha always includes the daystart in the
1237 // response, but log the error if it didn't.
1238 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1239 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001240
Amin Hassani1677e812017-06-21 13:36:36 -07001241 // Sets first_active_omaha_ping_sent to true (vpd in CrOS). We only do this if
1242 // we have got a response from omaha and if its value has never been set to
1243 // true before. Failure of this function should be ignored. There should be no
1244 // need to check if a=-1 has been sent because older devices have already sent
1245 // their a=-1 in the past and we have to set first_active_omaha_ping_sent for
1246 // future checks.
1247 if (!system_state_->hardware()->GetFirstActiveOmahaPingSent()) {
Amin Hassani80f4d4c2018-05-16 13:34:00 -07001248 if (!system_state_->hardware()->SetFirstActiveOmahaPingSent()) {
1249 system_state_->metrics_reporter()->ReportInternalErrorCode(
1250 ErrorCode::kFirstActiveOmahaPingSentPersistenceError);
1251 }
Amin Hassani1677e812017-06-21 13:36:36 -07001252 }
1253
Thieu Le116fda32011-04-19 11:01:54 -07001254 if (!HasOutputPipe()) {
1255 // Just set success to whether or not the http transfer succeeded,
1256 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001257 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001258 return;
1259 }
1260
Darin Petkov6a5b3222010-07-13 14:55:28 -07001261 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001262 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001263 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001264 output_object.update_exists = true;
1265 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001266
Toni Barzic61544e62018-10-11 14:37:30 -07001267 LoadOrPersistUpdateFirstSeenAtPref();
1268
Weidong Guo421ff332017-04-17 10:08:38 -07001269 ErrorCode error = ErrorCode::kSuccess;
Toni Barzic61544e62018-10-11 14:37:30 -07001270 if (ShouldIgnoreUpdate(output_object, &error)) {
Weidong Guo421ff332017-04-17 10:08:38 -07001271 // No need to change output_object.update_exists here, since the value
1272 // has been output to the pipe.
1273 completer.set_code(error);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001274 return;
1275 }
1276
May Lippert60aa3ca2018-08-15 16:55:29 -07001277
David Zeuthen8f191b22013-08-06 12:27:50 -07001278 // If Omaha says to disable p2p, respect that
1279 if (output_object.disable_p2p_for_downloading) {
1280 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1281 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001282 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001283 }
1284 if (output_object.disable_p2p_for_sharing) {
1285 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1286 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001287 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001288 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001289
1290 // Update the payload state with the current response. The payload state
1291 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001292 // from what's stored already. We are updating the payload state as late
1293 // as possible in this method so that if a new release gets pushed and then
1294 // got pulled back due to some issues, we don't want to clear our internal
1295 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001296 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001297
David Zeuthen8f191b22013-08-06 12:27:50 -07001298 // It could be we've already exceeded the deadline for when p2p is
1299 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001300 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001301 payload_state->P2PNewAttempt();
1302 if (!payload_state->P2PAttemptAllowed()) {
1303 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1304 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001305 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001306 }
1307 }
1308
1309 // From here on, we'll complete stuff in CompleteProcessing() so
1310 // disable |completer| since we'll create a new one in that
1311 // function.
1312 completer.set_should_complete(false);
1313
1314 // If we're allowed to use p2p for downloading we do not pay
1315 // attention to wall-clock-based waiting if the URL is indeed
1316 // available via p2p. Therefore, check if the file is available via
1317 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001318 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001319 LookupPayloadViaP2P(output_object);
1320 } else {
1321 CompleteProcessing();
1322 }
1323}
1324
1325void OmahaRequestAction::CompleteProcessing() {
1326 ScopedActionCompleter completer(processor_, this);
1327 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1328 PayloadStateInterface* payload_state = system_state_->payload_state();
1329
1330 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001331 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001332 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001333 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001334 return;
1335 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001336
Chris Sosa20f005c2013-09-05 13:53:08 -07001337 if (payload_state->ShouldBackoffDownload()) {
1338 output_object.update_exists = false;
1339 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1340 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001341 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001342 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001343 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001344 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001345}
1346
1347void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1348 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1349 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001350 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001351 } else {
1352 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1353 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001354 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001355 }
1356 CompleteProcessing();
1357}
1358
1359void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001360 // If the device is in the middle of an update, the state variables
1361 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1362 // tracks the offset and length of the operation currently in
1363 // progress. The offset is based from the end of the manifest which
1364 // is kPrefsManifestMetadataSize bytes long.
1365 //
1366 // To make forward progress and avoid deadlocks, we need to find a
1367 // peer that has at least the entire operation we're currently
1368 // working on. Otherwise we may end up in a situation where two
1369 // devices bounce back and forth downloading from each other,
1370 // neither making any forward progress until one of them decides to
1371 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1372 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001373 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001374 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001375 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001376 int64_t next_data_offset = 0;
1377 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001378 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001379 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1380 &manifest_metadata_size) &&
1381 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001382 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1383 &manifest_signature_size) &&
1384 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001385 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001386 &next_data_offset) &&
1387 next_data_offset != -1 &&
1388 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1389 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001390 minimum_size = manifest_metadata_size + manifest_signature_size +
1391 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001392 }
1393
Sen Jiang0affc2c2017-02-10 15:55:05 -08001394 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001395 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001396 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001397 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001398 string file_id =
1399 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001400 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001401 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1402 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001403 system_state_->p2p_manager()->LookupUrlForFile(
1404 file_id,
1405 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001406 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001407 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1408 base::Unretained(this)));
1409 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001410}
1411
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001412bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001413 if (params_->interactive()) {
1414 LOG(INFO) << "Not deferring download because update is interactive.";
1415 return false;
1416 }
1417
David Zeuthen8f191b22013-08-06 12:27:50 -07001418 // If we're using p2p to download _and_ we have a p2p URL, we never
1419 // defer the download. This is because the download will always
1420 // happen from a peer on the LAN and we've been waiting in line for
1421 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001422 const PayloadStateInterface* payload_state = system_state_->payload_state();
1423 if (payload_state->GetUsingP2PForDownloading() &&
1424 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001425 LOG(INFO) << "Download not deferred because download "
1426 << "will happen from a local peer (via p2p).";
1427 return false;
1428 }
1429
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001430 // We should defer the downloads only if we've first satisfied the
1431 // wall-clock-based-waiting period and then the update-check-based waiting
1432 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001433 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001434 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1435 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001436 return false;
1437 }
1438
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001439 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001440 case kWallClockWaitNotSatisfied:
1441 // We haven't even satisfied the first condition, passing the
1442 // wall-clock-based waiting period, so we should defer the downloads
1443 // until that happens.
1444 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1445 return true;
1446
1447 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1448 LOG(INFO) << "wall-clock-based-wait satisfied and "
1449 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001450 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001451
1452 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1453 // Wall-clock-based waiting period is satisfied, and it's determined
1454 // that we do not need the update-check-based wait. so no need to
1455 // defer downloads.
1456 LOG(INFO) << "wall-clock-based-wait satisfied and "
1457 << "update-check-based-wait is not required.";
1458 return false;
1459
1460 default:
1461 // Returning false for this default case so we err on the
1462 // side of downloading updates than deferring in case of any bugs.
1463 NOTREACHED();
1464 return false;
1465 }
1466}
1467
1468OmahaRequestAction::WallClockWaitResult
1469OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001470 OmahaResponse* output_object) {
May Lippert60aa3ca2018-08-15 16:55:29 -07001471 Time update_first_seen_at = LoadOrPersistUpdateFirstSeenAtPref();
1472 if (update_first_seen_at == base::Time()) {
1473 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read or "
1474 "persisted";
1475 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001476 }
1477
Sen Jiang7c1171e2016-06-23 11:35:40 -07001478 TimeDelta elapsed_time =
1479 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1480 TimeDelta max_scatter_period =
1481 TimeDelta::FromDays(output_object->max_days_to_scatter);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001482 int64_t staging_wait_time_in_days = 0;
1483 // Use staging and its default max value if staging is on.
1484 if (system_state_->prefs()->GetInt64(kPrefsWallClockStagingWaitPeriod,
1485 &staging_wait_time_in_days) &&
1486 staging_wait_time_in_days > 0)
1487 max_scatter_period = TimeDelta::FromDays(kMaxWaitTimeStagingInDays);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001488
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001489 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001490 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001491 << ", Time Elapsed = "
1492 << utils::FormatSecs(elapsed_time.InSeconds())
Adolfo Victoria497044c2018-07-18 07:51:42 -07001493 << ", MaxDaysToScatter = " << max_scatter_period.InDays();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001494
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001495 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001496 // The deadline is set for all rules which serve a delta update from a
1497 // previous FSI, which means this update will be applied mostly in OOBE
1498 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1499 // quickly.
1500 LOG(INFO) << "Not scattering as deadline flag is set";
1501 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1502 }
1503
1504 if (max_scatter_period.InDays() == 0) {
1505 // This means the Omaha rule creator decides that this rule
1506 // should not be scattered irrespective of the policy.
1507 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1508 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1509 }
1510
1511 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001512 // This means we've waited more than the upperbound wait in the rule
1513 // from the time we first saw a valid update available to us.
1514 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001515 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1516 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1517 }
1518
1519 // This means we are required to participate in scattering.
1520 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001521 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001522 if (remaining_wait_time.InSeconds() <= 0) {
1523 // Yes, it's our turn now.
1524 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1525
1526 // But we can't download until the update-check-count-based wait is also
1527 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001528 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001529 kWallClockWaitDoneButUpdateCheckWaitRequired :
1530 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1531 }
1532
1533 // Not our turn yet, so we have to wait until our turn to
1534 // help scatter the downloads across all clients of the enterprise.
1535 LOG(INFO) << "Update deferred for another "
1536 << utils::FormatSecs(remaining_wait_time.InSeconds())
1537 << " per policy.";
1538 return kWallClockWaitNotSatisfied;
1539}
1540
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001541bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001542 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001543
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001544 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1545 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1546 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001547 // We are unable to read the update check count from file for some reason.
1548 // So let's proceed anyway so as to not stall the update.
1549 LOG(ERROR) << "Unable to read update check count. "
1550 << "Skipping update-check-count-based-wait.";
1551 return true;
1552 }
1553 } else {
1554 // This file does not exist. This means we haven't started our update
1555 // check count down yet, so this is the right time to start the count down.
1556 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001557 params_->min_update_checks_needed(),
1558 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001559
1560 LOG(INFO) << "Randomly picked update check count value = "
1561 << update_check_count_value;
1562
1563 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001564 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1565 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001566 // We weren't able to write the update check count file for some reason.
1567 // So let's proceed anyway so as to not stall the update.
1568 LOG(ERROR) << "Unable to write update check count. "
1569 << "Skipping update-check-count-based-wait.";
1570 return true;
1571 }
1572 }
1573
1574 if (update_check_count_value == 0) {
1575 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1576 return true;
1577 }
1578
1579 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001580 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001581 // We err on the side of skipping scattering logic instead of stalling
1582 // a machine from receiving any updates in case of any unexpected state.
1583 LOG(ERROR) << "Invalid value for update check count detected. "
1584 << "Skipping update-check-count-based-wait.";
1585 return true;
1586 }
1587
1588 // Legal value, we need to wait for more update checks to happen
1589 // until this becomes 0.
1590 LOG(INFO) << "Deferring Omaha updates for another "
1591 << update_check_count_value
1592 << " update checks per policy";
1593 return false;
1594}
1595
David Zeuthen639aa362014-02-03 16:23:44 -08001596// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001597bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001598 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001599 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001600 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001601 &elapsed_days))
1602 return false;
1603
1604 if (elapsed_days < 0)
1605 return false;
1606
1607 output_object->install_date_days = elapsed_days;
1608 return true;
1609}
1610
1611// static
1612bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1613 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001614 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001615 return false;
1616
1617 return prefs->Exists(kPrefsInstallDateDays);
1618}
1619
1620// static
1621bool OmahaRequestAction::PersistInstallDate(
1622 SystemState *system_state,
1623 int install_date_days,
1624 InstallDateProvisioningSource source) {
1625 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1626
1627 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001628 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001629 return false;
1630
1631 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1632 return false;
1633
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001634 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001635 static_cast<int>(source), // Sample.
1636 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001637 return true;
1638}
1639
Alex Deymo8e18f932015-03-27 16:16:59 -07001640bool OmahaRequestAction::PersistCohortData(
1641 const string& prefs_key,
1642 const string& new_value) {
1643 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1644 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1645 return system_state_->prefs()->Delete(prefs_key);
1646 } else if (!new_value.empty()) {
1647 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1648 return system_state_->prefs()->SetString(prefs_key, new_value);
1649 }
1650 return true;
1651}
1652
Alex Deymob3fa53b2016-04-18 19:57:58 -07001653bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
Amin Hassani6600a562018-09-24 15:17:19 -07001654 auto eol_attr = attrs.find(kAttrEol);
Alex Deymob3fa53b2016-04-18 19:57:58 -07001655 if (eol_attr != attrs.end()) {
1656 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1657 eol_attr->second);
1658 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1659 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1660 }
1661 return true;
1662}
1663
David Zeuthen33bae492014-02-25 16:16:18 -08001664void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1665 // We only want to report this on "update check".
1666 if (ping_only_ || event_ != nullptr)
1667 return;
1668
1669 metrics::CheckResult result = metrics::CheckResult::kUnset;
1670 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1671 metrics::DownloadErrorCode download_error_code =
1672 metrics::DownloadErrorCode::kUnset;
1673
1674 // Regular update attempt.
1675 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001676 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001677 // OK, we parsed the response successfully but that does
1678 // necessarily mean that an update is available.
1679 if (HasOutputPipe()) {
1680 const OmahaResponse& response = GetOutputObject();
1681 if (response.update_exists) {
1682 result = metrics::CheckResult::kUpdateAvailable;
1683 reaction = metrics::CheckReaction::kUpdating;
1684 } else {
1685 result = metrics::CheckResult::kNoUpdateAvailable;
1686 }
1687 } else {
1688 result = metrics::CheckResult::kNoUpdateAvailable;
1689 }
1690 break;
1691
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001692 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
Weidong Guo421ff332017-04-17 10:08:38 -07001693 case ErrorCode::kOmahaUpdateIgnoredOverCellular:
David Zeuthen33bae492014-02-25 16:16:18 -08001694 result = metrics::CheckResult::kUpdateAvailable;
1695 reaction = metrics::CheckReaction::kIgnored;
1696 break;
1697
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001698 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001699 result = metrics::CheckResult::kUpdateAvailable;
1700 reaction = metrics::CheckReaction::kDeferring;
1701 break;
1702
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001703 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001704 result = metrics::CheckResult::kUpdateAvailable;
1705 reaction = metrics::CheckReaction::kBackingOff;
1706 break;
1707
1708 default:
1709 // We report two flavors of errors, "Download errors" and "Parsing
1710 // error". Try to convert to the former and if that doesn't work
1711 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001712 metrics::DownloadErrorCode tmp_error =
1713 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001714 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1715 result = metrics::CheckResult::kDownloadError;
1716 download_error_code = tmp_error;
1717 } else {
1718 result = metrics::CheckResult::kParsingError;
1719 }
1720 break;
1721 }
1722
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001723 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1724 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001725}
1726
Toni Barzic61544e62018-10-11 14:37:30 -07001727bool OmahaRequestAction::ShouldIgnoreUpdate(const OmahaResponse& response,
1728 ErrorCode* error) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001729 // Note: policy decision to not update to a version we rolled back from.
1730 string rollback_version =
1731 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001732 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001733 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001734 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001735 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
Weidong Guo421ff332017-04-17 10:08:38 -07001736 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
Chris Sosa77f79e82014-06-02 18:16:24 -07001737 return true;
1738 }
1739 }
1740
Toni Barzic61544e62018-10-11 14:37:30 -07001741 if (system_state_->hardware()->IsOOBEEnabled() &&
1742 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
1743 (response.deadline.empty() ||
1744 system_state_->payload_state()->GetRollbackHappened()) &&
1745 params_->app_version() != "ForcedUpdate") {
1746 LOG(INFO) << "Ignoring a non-critical Omaha update before OOBE completion.";
1747 *error = ErrorCode::kNonCriticalUpdateInOOBE;
1748 return true;
1749 }
1750
Weidong Guo421ff332017-04-17 10:08:38 -07001751 if (!IsUpdateAllowedOverCurrentConnection(error, response)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001752 LOG(INFO) << "Update is not allowed over current connection.";
1753 return true;
1754 }
1755
1756 // Note: We could technically delete the UpdateFirstSeenAt state when we
1757 // return true. If we do, it'll mean a device has to restart the
1758 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1759 // turned on again. On the other hand, it also increases the chance of update
1760 // starvation if an admin turns AU on/off more frequently. We choose to err on
1761 // the side of preventing starvation at the cost of not applying scattering in
1762 // those cases.
1763 return false;
1764}
1765
Weidong Guo421ff332017-04-17 10:08:38 -07001766bool OmahaRequestAction::IsUpdateAllowedOverCellularByPrefs(
1767 const OmahaResponse& response) const {
1768 PrefsInterface* prefs = system_state_->prefs();
1769
1770 if (!prefs) {
1771 LOG(INFO) << "Disabling updates over cellular as the preferences are "
1772 "not available.";
1773 return false;
1774 }
1775
1776 bool is_allowed;
1777
1778 if (prefs->Exists(kPrefsUpdateOverCellularPermission) &&
1779 prefs->GetBoolean(kPrefsUpdateOverCellularPermission, &is_allowed) &&
1780 is_allowed) {
1781 LOG(INFO) << "Allowing updates over cellular as permission preference is "
1782 "set to true.";
1783 return true;
1784 }
1785
1786 if (!prefs->Exists(kPrefsUpdateOverCellularTargetVersion) ||
1787 !prefs->Exists(kPrefsUpdateOverCellularTargetSize)) {
1788 LOG(INFO) << "Disabling updates over cellular as permission preference is "
1789 "set to false or does not exist while target does not exist.";
1790 return false;
1791 }
1792
1793 std::string target_version;
1794 int64_t target_size;
1795
1796 if (!prefs->GetString(kPrefsUpdateOverCellularTargetVersion,
1797 &target_version) ||
1798 !prefs->GetInt64(kPrefsUpdateOverCellularTargetSize, &target_size)) {
1799 LOG(INFO) << "Disabling updates over cellular as the target version or "
1800 "size is not accessible.";
1801 return false;
1802 }
1803
1804 uint64_t total_packages_size = 0;
1805 for (const auto& package : response.packages) {
1806 total_packages_size += package.size;
1807 }
1808 if (target_version == response.version &&
1809 static_cast<uint64_t>(target_size) == total_packages_size) {
1810 LOG(INFO) << "Allowing updates over cellular as the target matches the"
1811 "omaha response.";
1812 return true;
1813 } else {
1814 LOG(INFO) << "Disabling updates over cellular as the target does not"
1815 "match the omaha response.";
1816 return false;
1817 }
1818}
1819
1820bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection(
1821 ErrorCode* error, const OmahaResponse& response) const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001822 ConnectionType type;
1823 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001824 ConnectionManagerInterface* connection_manager =
1825 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001826 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001827 LOG(INFO) << "We could not determine our connection type. "
1828 << "Defaulting to allow updates.";
1829 return true;
1830 }
Weidong Guo421ff332017-04-17 10:08:38 -07001831
Chris Sosa77f79e82014-06-02 18:16:24 -07001832 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
Weidong Guo421ff332017-04-17 10:08:38 -07001833 bool is_device_policy_set =
1834 connection_manager->IsAllowedConnectionTypesForUpdateSet();
1835 // Treats tethered connection as if it is cellular connection.
1836 bool is_over_cellular = type == ConnectionType::kCellular ||
1837 tethering == ConnectionTethering::kConfirmed;
1838
1839 if (!is_over_cellular) {
1840 // There's no need to further check user preferences as we are not over
1841 // cellular connection.
1842 if (!is_allowed)
1843 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1844 } else if (is_device_policy_set) {
1845 // There's no need to further check user preferences as the device policy
1846 // is set regarding updates over cellular.
1847 if (!is_allowed)
1848 *error = ErrorCode::kOmahaUpdateIgnoredPerPolicy;
1849 } else {
1850 // Deivce policy is not set, so user preferences overwrite whether to
1851 // allow updates over cellular.
1852 is_allowed = IsUpdateAllowedOverCellularByPrefs(response);
1853 if (!is_allowed)
1854 *error = ErrorCode::kOmahaUpdateIgnoredOverCellular;
1855 }
1856
Chris Sosa77f79e82014-06-02 18:16:24 -07001857 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001858 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001859 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1860 return is_allowed;
1861}
1862
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001863bool OmahaRequestAction::IsRollbackEnabled() const {
1864 if (policy_provider_->IsConsumerDevice()) {
1865 LOG(INFO) << "Rollback is not enabled for consumer devices.";
1866 return false;
1867 }
1868
1869 if (!policy_provider_->device_policy_is_loaded()) {
1870 LOG(INFO) << "No device policy is loaded. Assuming rollback enabled.";
1871 return true;
1872 }
1873
1874 int allowed_milestones;
1875 if (!policy_provider_->GetDevicePolicy().GetRollbackAllowedMilestones(
1876 &allowed_milestones)) {
1877 LOG(INFO) << "RollbackAllowedMilestones policy can't be read. "
1878 "Defaulting to rollback enabled.";
1879 return true;
1880 }
1881
1882 LOG(INFO) << "Rollback allows " << allowed_milestones << " milestones.";
1883 return allowed_milestones > 0;
1884}
1885
1886void OmahaRequestAction::SetMaxKernelKeyVersionForRollback() const {
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001887 int max_kernel_rollforward;
1888 int min_kernel_version = system_state_->hardware()->GetMinKernelKeyVersion();
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001889 if (IsRollbackEnabled()) {
1890 // If rollback is enabled, set the max kernel key version to the current
1891 // kernel key version. This has the effect of freezing kernel key roll
1892 // forwards.
1893 //
1894 // TODO(zentaro): This behavior is temporary, and ensures that no kernel
1895 // key roll forward happens until the server side components of rollback
1896 // are implemented. Future changes will allow the Omaha server to return
1897 // the kernel key version from max_rollback_versions in the past. At that
1898 // point the max kernel key version will be set to that value, creating a
1899 // sliding window of versions that can be rolled back to.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001900 LOG(INFO) << "Rollback is enabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001901 << min_kernel_version;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001902 max_kernel_rollforward = min_kernel_version;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001903 } else {
1904 // For devices that are not rollback enabled (ie. consumer devices), the
1905 // max kernel key version is set to 0xfffffffe, which is logically
1906 // infinity. This maintains the previous behavior that that kernel key
1907 // versions roll forward each time they are incremented.
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001908 LOG(INFO) << "Rollback is disabled. Setting kernel_max_rollforward to "
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001909 << kRollforwardInfinity;
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001910 max_kernel_rollforward = kRollforwardInfinity;
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001911 }
1912
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001913 bool max_rollforward_set =
1914 system_state_->hardware()->SetMaxKernelKeyRollforward(
1915 max_kernel_rollforward);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001916 if (!max_rollforward_set) {
Zentaro Kavanagh5d956152018-05-15 09:40:33 -07001917 LOG(ERROR) << "Failed to set kernel_max_rollforward";
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001918 }
Marton Hunyadyffbfdfb2018-05-30 13:03:29 +02001919 // Report metrics
1920 system_state_->metrics_reporter()->ReportKeyVersionMetrics(
1921 min_kernel_version, max_kernel_rollforward, max_rollforward_set);
Zentaro Kavanagh1f899d52018-02-27 15:02:47 -08001922}
1923
May Lippert60aa3ca2018-08-15 16:55:29 -07001924base::Time OmahaRequestAction::LoadOrPersistUpdateFirstSeenAtPref() const {
1925 Time update_first_seen_at;
1926 int64_t update_first_seen_at_int;
1927 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1928 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1929 &update_first_seen_at_int)) {
1930 // Note: This timestamp could be that of ANY update we saw in the past
1931 // (not necessarily this particular update we're considering to apply)
1932 // but never got to apply because of some reason (e.g. stop AU policy,
1933 // updates being pulled out from Omaha, changes in target version prefix,
1934 // new update being rolled out, etc.). But for the purposes of scattering
1935 // it doesn't matter which update the timestamp corresponds to. i.e.
1936 // the clock starts ticking the first time we see an update and we're
1937 // ready to apply when the random wait period is satisfied relative to
1938 // that first seen timestamp.
1939 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1940 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1941 << utils::ToString(update_first_seen_at);
1942 } else {
1943 // This seems like an unexpected error where the persisted value exists
1944 // but it's not readable for some reason.
1945 LOG(INFO) << "UpdateFirstSeenAt value cannot be read";
1946 return base::Time();
1947 }
1948 } else {
1949 update_first_seen_at = system_state_->clock()->GetWallclockTime();
1950 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
1951 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1952 update_first_seen_at_int)) {
1953 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1954 << utils::ToString(update_first_seen_at);
1955 } else {
1956 // This seems like an unexpected error where the value cannot be
1957 // persisted for some reason.
1958 LOG(INFO) << "UpdateFirstSeenAt value "
1959 << utils::ToString(update_first_seen_at)
1960 << " cannot be persisted";
1961 return base::Time();
1962 }
1963 }
1964 return update_first_seen_at;
1965}
1966
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001967} // namespace chromeos_update_engine