blob: 43327024a60a1b2db8a8e8e502845f3302c55cac [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
David Zeuthene8ed8632014-07-24 13:38:10 -040021#include <map>
rspangler@google.com49fdf182009-10-10 00:57:34 +000022#include <sstream>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070023#include <string>
David Zeuthene8ed8632014-07-24 13:38:10 -040024#include <vector>
rspangler@google.com49fdf182009-10-10 00:57:34 +000025
David Zeuthen8f191b22013-08-06 12:27:50 -070026#include <base/bind.h>
Jay Srinivasan480ddfa2012-06-01 19:15:26 -070027#include <base/logging.h>
28#include <base/rand_util.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070029#include <base/strings/string_number_conversions.h>
Sen Jiang0affc2c2017-02-10 15:55:05 -080030#include <base/strings/string_split.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070031#include <base/strings/string_util.h>
32#include <base/strings/stringprintf.h>
33#include <base/time/time.h>
Sen Jiang684c9cd2017-10-17 16:26:45 -070034#include <brillo/key_value_store.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040035#include <expat.h>
Alex Deymoa2591792015-11-17 00:39:40 -030036#include <metrics/metrics_library.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000037
Alex Deymo39910dc2015-11-09 17:04:30 -080038#include "update_engine/common/action_pipe.h"
39#include "update_engine/common/constants.h"
40#include "update_engine/common/hardware_interface.h"
41#include "update_engine/common/hash_calculator.h"
42#include "update_engine/common/platform_constants.h"
43#include "update_engine/common/prefs_interface.h"
44#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070045#include "update_engine/connection_manager_interface.h"
Tianjie Xu282aa1f2017-09-05 13:42:45 -070046#include "update_engine/metrics_reporter_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080047#include "update_engine/metrics_utils.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070048#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070049#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080050#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000051
Darin Petkov1cbd78f2010-07-29 12:38:34 -070052using base::Time;
53using base::TimeDelta;
David Zeuthene8ed8632014-07-24 13:38:10 -040054using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000055using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040056using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000057
58namespace chromeos_update_engine {
59
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080060// List of custom pair tags that we interpret in the Omaha Response:
61static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080062static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070063static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080064// Deprecated: "IsDelta"
65static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080066static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
67static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
68// Deprecated: "ManifestSignatureRsa"
69// Deprecated: "ManifestSize"
70static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
71static const char* kTagMetadataSize = "MetadataSize";
72static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070073// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080074static const char* kTagPrompt = "Prompt";
David Zeuthen8f191b22013-08-06 12:27:50 -070075static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
76static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070077static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080078
Alex Deymoac41a822015-09-15 20:52:53 -070079static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000080
Alex Deymo14ad88e2016-06-29 12:30:14 -070081// X-GoogleUpdate headers.
82static const char* kXGoogleUpdateInteractivity = "X-GoogleUpdate-Interactivity";
83static const char* kXGoogleUpdateAppId = "X-GoogleUpdate-AppId";
84static const char* kXGoogleUpdateUpdater = "X-GoogleUpdate-Updater";
85
Alex Deymob3fa53b2016-04-18 19:57:58 -070086// updatecheck attributes (without the underscore prefix).
87static const char* kEolAttr = "eol";
88
Alex Deymoac41a822015-09-15 20:52:53 -070089namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000090
Darin Petkov1cbd78f2010-07-29 12:38:34 -070091// Returns an XML ping element attribute assignment with attribute
92// |name| and value |ping_days| if |ping_days| has a value that needs
93// to be sent, or an empty string otherwise.
94string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070095 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070096 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070097 return "";
98}
99
100// Returns an XML ping element if any of the elapsed days need to be
101// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700102string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700103 string ping_active = GetPingAttribute("a", ping_active_days);
104 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
105 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700106 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700107 ping_active.c_str(),
108 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700109 }
110 return "";
111}
112
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700113// Returns an XML that goes into the body of the <app> element of the Omaha
114// request based on the given parameters.
115string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700116 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700117 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700118 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700119 int ping_active_days,
120 int ping_roll_call_days,
121 PrefsInterface* prefs) {
122 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700123 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700124 if (include_ping)
125 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700126 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700127 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700128 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700129 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700130 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700131
Darin Petkov265f2902011-05-09 15:17:40 -0700132 // If this is the first update check after a reboot following a previous
133 // update, generate an event containing the previous version number. If
134 // the previous version preference file doesn't exist the event is still
135 // generated with a previous version of 0.0.0.0 -- this is relevant for
136 // older clients or new installs. The previous version event is not sent
137 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700138 // rebooted. The previous version event is also not sent if it was already
139 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700140 string prev_version;
141 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
142 prev_version = "0.0.0.0";
143 }
Alex Deymo87c08862015-10-30 21:56:55 -0700144 // We only store a non-empty previous version value after a successful
145 // update in the previous boot. After reporting it back to the server,
146 // we clear the previous version value so it doesn't get reported again.
147 if (!prev_version.empty()) {
148 app_body += base::StringPrintf(
149 " <event eventtype=\"%d\" eventresult=\"%d\" "
150 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800151 OmahaEvent::kTypeRebootedAfterUpdate,
152 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700153 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
154 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
155 << "Unable to reset the previous version.";
156 }
Darin Petkov95508da2011-01-05 12:42:29 -0800157 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700158 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800159 // The error code is an optional attribute so append it only if the result
160 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700161 string error_code;
162 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700163 error_code = base::StringPrintf(" errorcode=\"%d\"",
164 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700165 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700166 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700167 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700168 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700169 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700170
171 return app_body;
172}
173
Alex Deymo8e18f932015-03-27 16:16:59 -0700174// Returns the cohort* argument to include in the <app> tag for the passed
175// |arg_name| and |prefs_key|, if any. The return value is suitable to
176// concatenate to the list of arguments and includes a space at the end.
177string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700178 const string arg_name,
179 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700180 // There's nothing wrong with not having a given cohort setting, so we check
181 // existance first to avoid the warning log message.
182 if (!prefs->Exists(prefs_key))
183 return "";
184 string cohort_value;
185 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
186 return "";
187 // This is a sanity check to avoid sending a huge XML file back to Ohama due
188 // to a compromised stateful partition making the update check fail in low
189 // network environments envent after a reboot.
190 if (cohort_value.size() > 1024) {
191 LOG(WARNING) << "The omaha cohort setting " << arg_name
192 << " has a too big value, which must be an error or an "
193 "attacker trying to inhibit updates.";
194 return "";
195 }
196
Alex Deymob0d74eb2015-03-30 17:59:17 -0700197 string escaped_xml_value;
198 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
199 LOG(WARNING) << "The omaha cohort setting " << arg_name
200 << " is ASCII-7 invalid, ignoring it.";
201 return "";
202 }
203
Alex Deymo8e18f932015-03-27 16:16:59 -0700204 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700205 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700206}
207
Sen Jiang94a4dec2017-03-28 18:23:35 -0700208struct OmahaAppData {
209 string id;
210 string version;
Sen Jiang684c9cd2017-10-17 16:26:45 -0700211 string product_components;
Sen Jiang94a4dec2017-03-28 18:23:35 -0700212};
213
Sen Jiang684c9cd2017-10-17 16:26:45 -0700214bool IsValidComponentID(const string& id) {
215 for (char c : id) {
216 if (!isalnum(c) && c != '-' && c != '_' && c != '.')
217 return false;
218 }
219 return true;
220}
221
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700222// Returns an XML that corresponds to the entire <app> node of the Omaha
223// request based on the given parameters.
224string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700225 OmahaRequestParams* params,
Sen Jiang94a4dec2017-03-28 18:23:35 -0700226 const OmahaAppData& app_data,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700227 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700228 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700229 int ping_active_days,
230 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800231 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700232 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700233 string app_body = GetAppBody(event, params, ping_only, include_ping,
234 ping_active_days, ping_roll_call_days,
235 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700236 string app_versions;
237
238 // If we are upgrading to a more stable channel and we are allowed to do
239 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
240 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700241 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700242 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
243 << "on downgrading to the version in the more stable channel";
244 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700245 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700246 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700247 app_versions = "version=\"" +
Sen Jiang94a4dec2017-03-28 18:23:35 -0700248 XmlEncodeWithDefault(app_data.version, "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700249 }
250
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700251 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700252 string app_channels =
253 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
254 if (params->current_channel() != download_channel) {
255 app_channels += "from_track=\"" + XmlEncodeWithDefault(
256 params->current_channel(), "") + "\" ";
257 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700258
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700259 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700260
David Zeuthen639aa362014-02-03 16:23:44 -0800261 // If install_date_days is not set (e.g. its value is -1 ), don't
262 // include the attribute.
263 string install_date_in_days_str = "";
264 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700265 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
266 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800267 }
268
Alex Deymo8e18f932015-03-27 16:16:59 -0700269 string app_cohort_args;
270 app_cohort_args += GetCohortArgXml(system_state->prefs(),
271 "cohort", kPrefsOmahaCohort);
272 app_cohort_args += GetCohortArgXml(system_state->prefs(),
273 "cohorthint", kPrefsOmahaCohortHint);
274 app_cohort_args += GetCohortArgXml(system_state->prefs(),
275 "cohortname", kPrefsOmahaCohortName);
276
Alex Deymoebf6e122017-03-10 16:12:01 -0800277 string fingerprint_arg;
278 if (!params->os_build_fingerprint().empty()) {
279 fingerprint_arg =
280 "fingerprint=\"" + XmlEncodeWithDefault(params->os_build_fingerprint(), "") + "\" ";
281 }
282
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700283 string buildtype_arg;
284 if (!params->os_build_type().empty()) {
285 buildtype_arg = "os_build_type=\"" +
286 XmlEncodeWithDefault(params->os_build_type(), "") + "\" ";
287 }
288
Sen Jiang684c9cd2017-10-17 16:26:45 -0700289 string product_components_args;
290 if (!app_data.product_components.empty()) {
291 brillo::KeyValueStore store;
292 if (store.LoadFromString(app_data.product_components)) {
293 for (const string& key : store.GetKeys()) {
294 if (!IsValidComponentID(key)) {
295 LOG(ERROR) << "Invalid component id: " << key;
296 continue;
297 }
298 string version;
299 if (!store.GetString(key, &version)) {
300 LOG(ERROR) << "Failed to get version for " << key
301 << " in product_components.";
302 continue;
303 }
304 product_components_args +=
305 base::StringPrintf("_%s.version=\"%s\" ",
306 key.c_str(),
307 XmlEncodeWithDefault(version, "").c_str());
308 }
309 } else {
310 LOG(ERROR) << "Failed to parse product_components:\n"
311 << app_data.product_components;
312 }
313 }
314
315 // clang-format off
Alex Deymob0d74eb2015-03-30 17:59:17 -0700316 string app_xml = " <app "
Sen Jiang94a4dec2017-03-28 18:23:35 -0700317 "appid=\"" + XmlEncodeWithDefault(app_data.id, "") + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700318 app_cohort_args +
319 app_versions +
320 app_channels +
Sen Jiang684c9cd2017-10-17 16:26:45 -0700321 product_components_args +
Alex Deymoebf6e122017-03-10 16:12:01 -0800322 fingerprint_arg +
Sen Jiang1d5d95f2017-05-19 11:33:10 -0700323 buildtype_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700324 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
325 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
326 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
327 "delta_okay=\"" + delta_okay_str + "\" "
328 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
329 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
330 install_date_in_days_str +
331 ">\n" +
332 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700333 " </app>\n";
Sen Jiang684c9cd2017-10-17 16:26:45 -0700334 // clang-format on
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700335 return app_xml;
336}
337
338// Returns an XML that corresponds to the entire <os> node of the Omaha
339// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700340string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700341 string os_xml =" <os "
342 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
343 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
344 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
345 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700346 return os_xml;
347}
348
349// Returns an XML that corresponds to the entire Omaha request based on the
350// given parameters.
351string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700352 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700353 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700354 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700355 int ping_active_days,
356 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800357 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700358 SystemState* system_state) {
359 string os_xml = GetOsXml(params);
Sen Jiang684c9cd2017-10-17 16:26:45 -0700360 OmahaAppData product_app = {
361 .id = params->GetAppId(),
362 .version = params->app_version(),
363 .product_components = params->product_components()};
Sen Jiang94a4dec2017-03-28 18:23:35 -0700364 string app_xml = GetAppXml(event,
365 params,
366 product_app,
367 ping_only,
368 include_ping,
369 ping_active_days,
370 ping_roll_call_days,
371 install_date_in_days,
372 system_state);
373 if (!params->system_app_id().empty()) {
374 OmahaAppData system_app = {.id = params->system_app_id(),
375 .version = params->system_version()};
376 app_xml += GetAppXml(event,
377 params,
378 system_app,
379 ping_only,
380 include_ping,
381 ping_active_days,
382 ping_roll_call_days,
383 install_date_in_days,
384 system_state);
385 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700386
Alex Vakulenko75039d72014-03-25 12:36:28 -0700387 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700388 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700389
Alex Deymoac41a822015-09-15 20:52:53 -0700390 string updater_version = XmlEncodeWithDefault(
391 base::StringPrintf("%s-%s",
392 constants::kOmahaUpdaterID,
393 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700394 string request_xml =
395 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700396 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700397 "version=\"" + updater_version + "\" "
398 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700399 install_source +
400 "ismachine=\"1\">\n") +
401 os_xml +
402 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700403 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700404
405 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000406}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700407
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700408} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000409
David Zeuthene8ed8632014-07-24 13:38:10 -0400410// Struct used for holding data obtained when parsing the XML.
411struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400412 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
413
414 // Pointer to the expat XML_Parser object.
415 XML_Parser xml_parser;
416
David Zeuthene8ed8632014-07-24 13:38:10 -0400417 // This is the state of the parser as it's processing the XML.
418 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400419 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400420 string current_path;
421
422 // These are the values extracted from the XML.
David Zeuthene8ed8632014-07-24 13:38:10 -0400423 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700424 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400425 string daystart_elapsed_days;
426 string daystart_elapsed_seconds;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800427
Sen Jiang81259682017-03-30 15:11:30 -0700428 struct App {
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700429 string id;
Sen Jiang81259682017-03-30 15:11:30 -0700430 vector<string> url_codebase;
431 string manifest_version;
432 map<string, string> action_postinstall_attrs;
433 string updatecheck_status;
Sen Jiangb1e063a2017-09-15 17:44:31 -0700434 string cohort;
435 string cohorthint;
436 string cohortname;
437 bool cohort_set = false;
438 bool cohorthint_set = false;
439 bool cohortname_set = false;
Sen Jiang81259682017-03-30 15:11:30 -0700440
441 struct Package {
442 string name;
443 string size;
444 string hash;
445 };
446 vector<Package> packages;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800447 };
Sen Jiang81259682017-03-30 15:11:30 -0700448 vector<App> apps;
David Zeuthene8ed8632014-07-24 13:38:10 -0400449};
450
451namespace {
452
453// Callback function invoked by expat.
454void ParserHandlerStart(void* user_data, const XML_Char* element,
455 const XML_Char** attr) {
456 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
457
458 if (data->failed)
459 return;
460
461 data->current_path += string("/") + element;
462
463 map<string, string> attrs;
464 if (attr != nullptr) {
465 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
466 string key = attr[n];
467 string value = attr[n + 1];
468 attrs[key] = value;
469 }
470 }
471
Alex Deymo8e18f932015-03-27 16:16:59 -0700472 if (data->current_path == "/response/app") {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700473 OmahaParserData::App app;
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700474 if (attrs.find("appid") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700475 app.id = attrs["appid"];
Aaron Wood7dcdedf2017-09-06 17:17:41 -0700476 }
Alex Deymo8e18f932015-03-27 16:16:59 -0700477 if (attrs.find("cohort") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700478 app.cohort_set = true;
479 app.cohort = attrs["cohort"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700480 }
481 if (attrs.find("cohorthint") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700482 app.cohorthint_set = true;
483 app.cohorthint = attrs["cohorthint"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700484 }
485 if (attrs.find("cohortname") != attrs.end()) {
Sen Jiangb1e063a2017-09-15 17:44:31 -0700486 app.cohortname_set = true;
487 app.cohortname = attrs["cohortname"];
Alex Deymo8e18f932015-03-27 16:16:59 -0700488 }
Sen Jiangb1e063a2017-09-15 17:44:31 -0700489 data->apps.push_back(std::move(app));
Alex Deymo8e18f932015-03-27 16:16:59 -0700490 } else if (data->current_path == "/response/app/updatecheck") {
Sen Jiang81259682017-03-30 15:11:30 -0700491 if (!data->apps.empty())
492 data->apps.back().updatecheck_status = attrs["status"];
493 if (data->updatecheck_poll_interval.empty())
494 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700495 // Omaha sends arbitrary key-value pairs as extra attributes starting with
496 // an underscore.
497 for (const auto& attr : attrs) {
498 if (!attr.first.empty() && attr.first[0] == '_')
499 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
500 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400501 } else if (data->current_path == "/response/daystart") {
502 // Get the install-date.
503 data->daystart_elapsed_days = attrs["elapsed_days"];
504 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
505 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
506 // Look at all <url> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700507 if (!data->apps.empty())
508 data->apps.back().url_codebase.push_back(attrs["codebase"]);
Sen Jiang0affc2c2017-02-10 15:55:05 -0800509 } else if (data->current_path ==
David Zeuthene8ed8632014-07-24 13:38:10 -0400510 "/response/app/updatecheck/manifest/packages/package") {
Sen Jiang0affc2c2017-02-10 15:55:05 -0800511 // Look at all <package> elements.
Sen Jiang81259682017-03-30 15:11:30 -0700512 if (!data->apps.empty())
513 data->apps.back().packages.push_back({.name = attrs["name"],
514 .size = attrs["size"],
515 .hash = attrs["hash_sha256"]});
David Zeuthene8ed8632014-07-24 13:38:10 -0400516 } else if (data->current_path == "/response/app/updatecheck/manifest") {
517 // Get the version.
Sen Jiang81259682017-03-30 15:11:30 -0700518 if (!data->apps.empty())
519 data->apps.back().manifest_version = attrs[kTagVersion];
David Zeuthene8ed8632014-07-24 13:38:10 -0400520 } else if (data->current_path ==
521 "/response/app/updatecheck/manifest/actions/action") {
522 // We only care about the postinstall action.
Sen Jiang81259682017-03-30 15:11:30 -0700523 if (attrs["event"] == "postinstall" && !data->apps.empty()) {
524 data->apps.back().action_postinstall_attrs = std::move(attrs);
David Zeuthene8ed8632014-07-24 13:38:10 -0400525 }
526 }
527}
528
529// Callback function invoked by expat.
530void ParserHandlerEnd(void* user_data, const XML_Char* element) {
531 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
532 if (data->failed)
533 return;
534
535 const string path_suffix = string("/") + element;
536
Alex Vakulenko0103c362016-01-20 07:56:15 -0800537 if (!base::EndsWith(data->current_path, path_suffix,
538 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400539 LOG(ERROR) << "Unexpected end element '" << element
540 << "' with current_path='" << data->current_path << "'";
541 data->failed = true;
542 return;
543 }
544 data->current_path.resize(data->current_path.size() - path_suffix.size());
545}
546
David Zeuthenf3e28012014-08-26 18:23:52 -0400547// Callback function invoked by expat.
548//
549// This is called for entity declarations. Since Omaha is guaranteed
550// to never return any XML with entities our course of action is to
551// just stop parsing. This avoids potential resource exhaustion
552// problems AKA the "billion laughs". CVE-2013-0340.
553void ParserHandlerEntityDecl(void *user_data,
554 const XML_Char *entity_name,
555 int is_parameter_entity,
556 const XML_Char *value,
557 int value_length,
558 const XML_Char *base,
559 const XML_Char *system_id,
560 const XML_Char *public_id,
561 const XML_Char *notation_name) {
562 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
563
564 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
565 data->failed = true;
566 data->entity_decl = true;
567 XML_StopParser(data->xml_parser, false);
568}
569
David Zeuthene8ed8632014-07-24 13:38:10 -0400570} // namespace
571
Alex Deymob0d74eb2015-03-30 17:59:17 -0700572bool XmlEncode(const string& input, string* output) {
573 if (std::find_if(input.begin(), input.end(),
574 [](const char c){return c & 0x80;}) != input.end()) {
575 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
576 utils::HexDumpString(input);
577 return false;
578 }
Alex Deymocc457852015-06-18 18:35:50 -0700579 output->clear();
580 // We need at least input.size() space in the output, but the code below will
581 // handle it if we need more.
582 output->reserve(input.size());
583 for (char c : input) {
584 switch (c) {
585 case '\"':
586 output->append("&quot;");
587 break;
588 case '\'':
589 output->append("&apos;");
590 break;
591 case '&':
592 output->append("&amp;");
593 break;
594 case '<':
595 output->append("&lt;");
596 break;
597 case '>':
598 output->append("&gt;");
599 break;
600 default:
601 output->push_back(c);
602 }
603 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700604 return true;
605}
606
607string XmlEncodeWithDefault(const string& input, const string& default_value) {
608 string output;
609 if (XmlEncode(input, &output))
610 return output;
611 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000612}
613
Alex Deymoc1c17b42015-11-23 03:53:15 -0300614OmahaRequestAction::OmahaRequestAction(
615 SystemState* system_state,
616 OmahaEvent* event,
617 std::unique_ptr<HttpFetcher> http_fetcher,
618 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800619 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700620 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300621 http_fetcher_(std::move(http_fetcher)),
Thieu Le116fda32011-04-19 11:01:54 -0700622 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700623 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700624 ping_roll_call_days_(0) {
625 params_ = system_state->request_params();
626}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000627
Darin Petkov6a5b3222010-07-13 14:55:28 -0700628OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000629
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700630// Calculates the value to use for the ping days parameter.
631int OmahaRequestAction::CalculatePingDays(const string& key) {
632 int days = kNeverPinged;
633 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800634 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700635 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
636 if (days < 0) {
637 // If |days| is negative, then the system clock must have jumped
638 // back in time since the ping was sent. Mark the value so that
639 // it doesn't get sent to the server but we still update the
640 // last ping daystart preference. This way the next ping time
641 // will be correct, hopefully.
642 days = kPingTimeJump;
643 LOG(WARNING) <<
644 "System clock jumped back in time. Resetting ping daystarts.";
645 }
646 }
647 return days;
648}
649
650void OmahaRequestAction::InitPingDays() {
651 // We send pings only along with update checks, not with events.
652 if (IsEvent()) {
653 return;
654 }
655 // TODO(petkov): Figure a way to distinguish active use pings
656 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700657 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700658 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
659 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
660}
661
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700662bool OmahaRequestAction::ShouldPing() const {
663 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
664 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
665 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
666 if (powerwash_count > 0) {
667 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
668 << "powerwash_count is " << powerwash_count;
669 return false;
670 }
671 return true;
672 }
673 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
674}
675
David Zeuthen639aa362014-02-03 16:23:44 -0800676// static
677int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
678 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700679 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800680 return -1;
681
682 // If we have the value stored on disk, just return it.
683 int64_t stored_value;
684 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
685 // Convert and sanity-check.
686 int install_date_days = static_cast<int>(stored_value);
687 if (install_date_days >= 0)
688 return install_date_days;
689 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
690 << install_date_days << " looks suspicious.";
691 prefs->Delete(kPrefsInstallDateDays);
692 }
693
694 // Otherwise, if OOBE is not complete then do nothing and wait for
695 // ParseResponse() to call ParseInstallDate() and then
696 // PersistInstallDate() to set the kPrefsInstallDateDays state
697 // variable. Once that is done, we'll then report back in future
698 // Omaha requests. This works exactly because OOBE triggers an
699 // update check.
700 //
701 // However, if OOBE is complete and the kPrefsInstallDateDays state
702 // variable is not set, there are two possibilities
703 //
704 // 1. The update check in OOBE failed so we never got a response
705 // from Omaha (no network etc.); or
706 //
707 // 2. OOBE was done on an older version that didn't write to the
708 // kPrefsInstallDateDays state variable.
709 //
710 // In both cases, we approximate the install date by simply
711 // inspecting the timestamp of when OOBE happened.
712
713 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700714 if (!system_state->hardware()->IsOOBEEnabled() ||
715 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800716 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700717 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800718 return -1;
719 }
720
721 int num_days;
722 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
723 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
724 << "as its value '" << utils::ToString(time_of_oobe)
725 << "' looks suspicious.";
726 return -1;
727 }
728
729 // Persist this to disk, for future use.
730 if (!OmahaRequestAction::PersistInstallDate(system_state,
731 num_days,
732 kProvisionedFromOOBEMarker))
733 return -1;
734
735 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
736 << num_days << " days";
737
738 return num_days;
739}
740
Darin Petkov6a5b3222010-07-13 14:55:28 -0700741void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000742 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700743 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700744 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700745 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700746 return;
747 }
David Zeuthen639aa362014-02-03 16:23:44 -0800748
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700749 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700750 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700751 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700752 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700753 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800754 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800755 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700756 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700757
Alex Deymo14ad88e2016-06-29 12:30:14 -0700758 // Set X-GoogleUpdate headers.
759 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
760 params_->interactive() ? "fg" : "bg");
761 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
762 http_fetcher_->SetHeader(
763 kXGoogleUpdateUpdater,
764 base::StringPrintf(
765 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
766
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800767 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
768 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700769 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700770 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700771 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000772}
773
Darin Petkov6a5b3222010-07-13 14:55:28 -0700774void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000775 http_fetcher_->TerminateTransfer();
776}
777
778// We just store the response in the buffer. Once we've received all bytes,
779// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700780void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800781 const void* bytes,
782 size_t length) {
783 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
784 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000785}
786
787namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000788
789// Parses a 64 bit base-10 int from a string and returns it. Returns 0
790// on error. If the string contains "0", that's indistinguishable from
791// error.
792off_t ParseInt(const string& str) {
793 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700794 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000795 if (rc < 1) {
796 // failure
797 return 0;
798 }
799 return ret;
800}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700801
David Zeuthene8ed8632014-07-24 13:38:10 -0400802// Parses |str| and returns |true| if, and only if, its value is "true".
803bool ParseBool(const string& str) {
804 return str == "true";
805}
806
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700807// Update the last ping day preferences based on the server daystart
808// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400809bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700810 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400811 TEST_AND_RETURN_FALSE(
812 base::StringToInt64(parser_data->daystart_elapsed_seconds,
813 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700814 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
815
816 // Remember the local time that matches the server's last midnight
817 // time.
818 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
819 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
820 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
821 return true;
822}
Sen Jiang81259682017-03-30 15:11:30 -0700823
824// Parses the package node in the given XML document and populates
825// |output_object| if valid. Returns true if we should continue the parsing.
826// False otherwise, in which case it sets any error code using |completer|.
827bool ParsePackage(OmahaParserData::App* app,
828 OmahaResponse* output_object,
829 ScopedActionCompleter* completer) {
830 if (app->updatecheck_status == "noupdate") {
831 if (!app->packages.empty()) {
832 LOG(ERROR) << "No update in this <app> but <package> is not empty.";
833 completer->set_code(ErrorCode::kOmahaResponseInvalid);
834 return false;
835 }
836 return true;
837 }
838 if (app->packages.empty()) {
839 LOG(ERROR) << "Omaha Response has no packages";
840 completer->set_code(ErrorCode::kOmahaResponseInvalid);
841 return false;
842 }
843 if (app->url_codebase.empty()) {
844 LOG(ERROR) << "No Omaha Response URLs";
845 completer->set_code(ErrorCode::kOmahaResponseInvalid);
846 return false;
847 }
848 LOG(INFO) << "Found " << app->url_codebase.size() << " url(s)";
849 vector<string> metadata_sizes =
850 base::SplitString(app->action_postinstall_attrs[kTagMetadataSize],
851 ":",
852 base::TRIM_WHITESPACE,
853 base::SPLIT_WANT_ALL);
854 vector<string> metadata_signatures =
855 base::SplitString(app->action_postinstall_attrs[kTagMetadataSignatureRsa],
856 ":",
857 base::TRIM_WHITESPACE,
858 base::SPLIT_WANT_ALL);
Sen Jiangcdd52062017-05-18 15:33:10 -0700859 vector<string> is_delta_payloads =
860 base::SplitString(app->action_postinstall_attrs[kTagIsDeltaPayload],
861 ":",
862 base::TRIM_WHITESPACE,
863 base::SPLIT_WANT_ALL);
Sen Jiang81259682017-03-30 15:11:30 -0700864 for (size_t i = 0; i < app->packages.size(); i++) {
865 const auto& package = app->packages[i];
866 if (package.name.empty()) {
867 LOG(ERROR) << "Omaha Response has empty package name";
868 completer->set_code(ErrorCode::kOmahaResponseInvalid);
869 return false;
870 }
871 LOG(INFO) << "Found package " << package.name;
872
873 OmahaResponse::Package out_package;
874 for (const string& codebase : app->url_codebase) {
875 if (codebase.empty()) {
876 LOG(ERROR) << "Omaha Response URL has empty codebase";
877 completer->set_code(ErrorCode::kOmahaResponseInvalid);
878 return false;
879 }
880 out_package.payload_urls.push_back(codebase + package.name);
881 }
882 // Parse the payload size.
883 base::StringToUint64(package.size, &out_package.size);
884 if (out_package.size <= 0) {
885 LOG(ERROR) << "Omaha Response has invalid payload size: " << package.size;
886 completer->set_code(ErrorCode::kOmahaResponseInvalid);
887 return false;
888 }
889 LOG(INFO) << "Payload size = " << out_package.size << " bytes";
890
891 if (i < metadata_sizes.size())
892 base::StringToUint64(metadata_sizes[i], &out_package.metadata_size);
893 LOG(INFO) << "Payload metadata size = " << out_package.metadata_size
894 << " bytes";
895
896 if (i < metadata_signatures.size())
897 out_package.metadata_signature = metadata_signatures[i];
898 LOG(INFO) << "Payload metadata signature = "
899 << out_package.metadata_signature;
900
901 out_package.hash = package.hash;
902 if (out_package.hash.empty()) {
903 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
904 completer->set_code(ErrorCode::kOmahaResponseInvalid);
905 return false;
906 }
907 LOG(INFO) << "Payload hash = " << out_package.hash;
Sen Jiangcdd52062017-05-18 15:33:10 -0700908
909 if (i < is_delta_payloads.size())
910 out_package.is_delta = ParseBool(is_delta_payloads[i]);
911 LOG(INFO) << "Payload is delta = " << utils::ToString(out_package.is_delta);
912
Sen Jiang81259682017-03-30 15:11:30 -0700913 output_object->packages.push_back(std::move(out_package));
914 }
915
916 return true;
917}
918
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700919} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000920
David Zeuthene8ed8632014-07-24 13:38:10 -0400921bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700922 OmahaResponse* output_object,
923 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -0700924 if (parser_data->apps.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700925 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700926 return false;
927 }
Sen Jiang81259682017-03-30 15:11:30 -0700928 LOG(INFO) << "Found " << parser_data->apps.size() << " <app>.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700929
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800930 // chromium-os:37289: The PollInterval is not supported by Omaha server
931 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700932 // slow down the request rate from the server-side. Note that the PollInterval
933 // is not persisted, so it has to be sent by the server on every response to
934 // guarantee that the scheduler uses this value (otherwise, if the device got
935 // rebooted after the last server-indicated value, it'll revert to the default
936 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
937 // based on the assumption that we perform an update check every hour so that
938 // the max value of 8 will roughly be equivalent to one work day. If we decide
939 // to use PollInterval permanently, we should update the
940 // max_update_checks_allowed to take PollInterval into account. Note: The
941 // parsing for PollInterval happens even before parsing of the status because
942 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400943 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700944 &output_object->poll_interval);
945
David Zeuthen639aa362014-02-03 16:23:44 -0800946 // Check for the "elapsed_days" attribute in the "daystart"
947 // element. This is the number of days since Jan 1 2007, 0:00
948 // PST. If we don't have a persisted value of the Omaha InstallDate,
949 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400950 if (ParseInstallDate(parser_data, output_object) &&
951 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800952 // Since output_object->install_date_days is never negative, the
953 // elapsed_days -> install-date calculation is reduced to simply
954 // rounding down to the nearest number divisible by 7.
955 int remainder = output_object->install_date_days % 7;
956 int install_date_days_rounded =
957 output_object->install_date_days - remainder;
958 if (PersistInstallDate(system_state_,
959 install_date_days_rounded,
960 kProvisionedFromOmahaResponse)) {
961 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
962 << install_date_days_rounded << " days";
963 }
964 }
965
Alex Deymo00d79ac2015-06-29 15:41:49 -0700966 // We persist the cohorts sent by omaha even if the status is "noupdate".
Sen Jiangb1e063a2017-09-15 17:44:31 -0700967 for (const auto& app : parser_data->apps) {
968 if (app.id == params_->GetAppId()) {
969 if (app.cohort_set)
970 PersistCohortData(kPrefsOmahaCohort, app.cohort);
971 if (app.cohorthint_set)
972 PersistCohortData(kPrefsOmahaCohortHint, app.cohorthint);
973 if (app.cohortname_set)
974 PersistCohortData(kPrefsOmahaCohortName, app.cohortname);
975 break;
976 }
977 }
Alex Deymo00d79ac2015-06-29 15:41:49 -0700978
Alex Deymob3fa53b2016-04-18 19:57:58 -0700979 // Parse the updatecheck attributes.
980 PersistEolStatus(parser_data->updatecheck_attrs);
981
David Zeuthene8ed8632014-07-24 13:38:10 -0400982 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700983 return false;
984
David Zeuthene8ed8632014-07-24 13:38:10 -0400985 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700986 return false;
987
Sen Jiang0affc2c2017-02-10 15:55:05 -0800988 // Package has to be parsed after Params now because ParseParams need to make
989 // sure that postinstall action exists.
Sen Jiang81259682017-03-30 15:11:30 -0700990 for (auto& app : parser_data->apps)
991 if (!ParsePackage(&app, output_object, completer))
992 return false;
Sen Jiang0affc2c2017-02-10 15:55:05 -0800993
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700994 return true;
995}
996
David Zeuthene8ed8632014-07-24 13:38:10 -0400997bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700998 OmahaResponse* output_object,
999 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001000 output_object->update_exists = false;
1001 for (size_t i = 0; i < parser_data->apps.size(); i++) {
1002 const string& status = parser_data->apps[i].updatecheck_status;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001003 if (status == "noupdate") {
1004 // Don't update if any app has status="noupdate".
Sen Jiang81259682017-03-30 15:11:30 -07001005 LOG(INFO) << "No update for <app> " << i;
Sen Jiang00adf7b2017-06-26 15:57:29 -07001006 output_object->update_exists = false;
1007 break;
Sen Jiang81259682017-03-30 15:11:30 -07001008 } else if (status == "ok") {
Sen Jiang00adf7b2017-06-26 15:57:29 -07001009 if (parser_data->apps[i].action_postinstall_attrs["noupdate"] == "true") {
1010 // noupdate="true" in postinstall attributes means it's an update to
1011 // self, only update if there's at least one app really have update.
1012 LOG(INFO) << "Update to self for <app> " << i;
1013 } else {
1014 LOG(INFO) << "Update for <app> " << i;
1015 output_object->update_exists = true;
1016 }
Sen Jiang81259682017-03-30 15:11:30 -07001017 } else {
1018 LOG(ERROR) << "Unknown Omaha response status: " << status;
1019 completer->set_code(ErrorCode::kOmahaResponseInvalid);
1020 return false;
1021 }
1022 }
1023 if (!output_object->update_exists) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001024 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001025 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001026 }
1027
Sen Jiang81259682017-03-30 15:11:30 -07001028 return output_object->update_exists;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001029}
1030
David Zeuthene8ed8632014-07-24 13:38:10 -04001031bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001032 OmahaResponse* output_object,
1033 ScopedActionCompleter* completer) {
Sen Jiang81259682017-03-30 15:11:30 -07001034 map<string, string> attrs;
1035 for (auto& app : parser_data->apps) {
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001036 if (app.id == params_->GetAppId()) {
1037 // this is the app (potentially the only app)
Sen Jiang81259682017-03-30 15:11:30 -07001038 output_object->version = app.manifest_version;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001039 } else if (!params_->system_app_id().empty() &&
1040 app.id == params_->system_app_id()) {
1041 // this is the system app (this check is intentionally skipped if there is
1042 // no system_app_id set)
1043 output_object->system_version = app.manifest_version;
1044 }
1045 if (!app.action_postinstall_attrs.empty() && attrs.empty()) {
Sen Jiang81259682017-03-30 15:11:30 -07001046 attrs = app.action_postinstall_attrs;
Aaron Wood7dcdedf2017-09-06 17:17:41 -07001047 }
Sen Jiang81259682017-03-30 15:11:30 -07001048 }
Chris Sosa3b748432013-06-20 16:42:59 -07001049 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -07001050 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001051 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -07001052 return false;
1053 }
1054
1055 LOG(INFO) << "Received omaha response to update to version "
1056 << output_object->version;
1057
David Zeuthene8ed8632014-07-24 13:38:10 -04001058 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001059 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001060 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001061 return false;
1062 }
1063
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001064 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -04001065 output_object->more_info_url = attrs[kTagMoreInfo];
David Zeuthene8ed8632014-07-24 13:38:10 -04001066 output_object->prompt = ParseBool(attrs[kTagPrompt]);
1067 output_object->deadline = attrs[kTagDeadline];
1068 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001069 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -04001070 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -07001071 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -04001072 ParseBool(attrs[kTagDisableP2PForSharing]);
1073 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001074
David Zeuthene8ed8632014-07-24 13:38:10 -04001075 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -08001076 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -08001077 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001078
Jay Srinivasan08262882012-12-28 19:29:43 -08001079 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -04001080 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -08001081
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001082 return true;
1083}
1084
David Zeuthene8ed8632014-07-24 13:38:10 -04001085// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +00001086// and fill in the appropriate fields of the output object. Also, notifies
1087// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -07001088void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
1089 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +00001090 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001091 string current_response(response_buffer_.begin(), response_buffer_.end());
1092 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001093
Gilad Arnold74b5f552014-10-07 08:17:16 -07001094 PayloadStateInterface* const payload_state = system_state_->payload_state();
1095
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001096 // Events are best effort transactions -- assume they always succeed.
1097 if (IsEvent()) {
1098 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001099 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001100 return;
1101 }
1102
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001103 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -07001104 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -07001105 int code = GetHTTPResponseCode();
1106 // Makes sure we send sane error values.
1107 if (code < 0 || code >= 1000) {
1108 code = 999;
1109 }
David Zeuthena99981f2013-04-29 13:42:47 -07001110 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001111 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +00001112 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -07001113 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001114
David Zeuthene8ed8632014-07-24 13:38:10 -04001115 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -04001116 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -04001117 XML_SetUserData(parser, &parser_data);
1118 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -04001119 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -08001120 XML_Status res = XML_Parse(
1121 parser,
1122 reinterpret_cast<const char*>(response_buffer_.data()),
1123 response_buffer_.size(),
1124 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -04001125 XML_ParserFree(parser);
1126
1127 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -07001128 LOG(ERROR) << "Omaha response not valid XML: "
1129 << XML_ErrorString(XML_GetErrorCode(parser))
1130 << " at line " << XML_GetCurrentLineNumber(parser)
1131 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -04001132 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
1133 if (response_buffer_.empty()) {
1134 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
1135 } else if (parser_data.entity_decl) {
1136 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
1137 }
1138 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001139 return;
1140 }
1141
Alex Deymoebbe7ef2014-10-30 13:02:49 -07001142 // Update the last ping day preferences based on the server daystart response
1143 // even if we didn't send a ping. Omaha always includes the daystart in the
1144 // response, but log the error if it didn't.
1145 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
1146 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -07001147
Thieu Le116fda32011-04-19 11:01:54 -07001148 if (!HasOutputPipe()) {
1149 // Just set success to whether or not the http transfer succeeded,
1150 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001151 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -07001152 return;
1153 }
1154
Darin Petkov6a5b3222010-07-13 14:55:28 -07001155 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001156 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001157 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001158 output_object.update_exists = true;
1159 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001160
Tao Bao5688d162017-06-06 13:09:06 -07001161 if (ShouldIgnoreUpdate(output_object)) {
1162 output_object.update_exists = false;
1163 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001164 return;
1165 }
1166
David Zeuthen8f191b22013-08-06 12:27:50 -07001167 // If Omaha says to disable p2p, respect that
1168 if (output_object.disable_p2p_for_downloading) {
1169 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1170 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001171 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001172 }
1173 if (output_object.disable_p2p_for_sharing) {
1174 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1175 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001176 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001177 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001178
1179 // Update the payload state with the current response. The payload state
1180 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001181 // from what's stored already. We are updating the payload state as late
1182 // as possible in this method so that if a new release gets pushed and then
1183 // got pulled back due to some issues, we don't want to clear our internal
1184 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001185 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001186
David Zeuthen8f191b22013-08-06 12:27:50 -07001187 // It could be we've already exceeded the deadline for when p2p is
1188 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001189 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001190 payload_state->P2PNewAttempt();
1191 if (!payload_state->P2PAttemptAllowed()) {
1192 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1193 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001194 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001195 }
1196 }
1197
1198 // From here on, we'll complete stuff in CompleteProcessing() so
1199 // disable |completer| since we'll create a new one in that
1200 // function.
1201 completer.set_should_complete(false);
1202
1203 // If we're allowed to use p2p for downloading we do not pay
1204 // attention to wall-clock-based waiting if the URL is indeed
1205 // available via p2p. Therefore, check if the file is available via
1206 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001207 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001208 LookupPayloadViaP2P(output_object);
1209 } else {
1210 CompleteProcessing();
1211 }
1212}
1213
1214void OmahaRequestAction::CompleteProcessing() {
1215 ScopedActionCompleter completer(processor_, this);
1216 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1217 PayloadStateInterface* payload_state = system_state_->payload_state();
1218
Alex Deymo46a9aae2016-05-04 20:20:11 -07001219 if (system_state_->hardware()->IsOOBEEnabled() &&
1220 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001221 output_object.deadline.empty() &&
1222 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001223 output_object.update_exists = false;
1224 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1225 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1226 return;
1227 }
1228
David Zeuthen8f191b22013-08-06 12:27:50 -07001229 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001230 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001231 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001232 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001233 return;
1234 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001235
Chris Sosa20f005c2013-09-05 13:53:08 -07001236 if (payload_state->ShouldBackoffDownload()) {
1237 output_object.update_exists = false;
1238 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1239 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001240 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001241 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001242 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001243 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001244}
1245
1246void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1247 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1248 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001249 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001250 } else {
1251 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1252 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001253 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001254 }
1255 CompleteProcessing();
1256}
1257
1258void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001259 // If the device is in the middle of an update, the state variables
1260 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1261 // tracks the offset and length of the operation currently in
1262 // progress. The offset is based from the end of the manifest which
1263 // is kPrefsManifestMetadataSize bytes long.
1264 //
1265 // To make forward progress and avoid deadlocks, we need to find a
1266 // peer that has at least the entire operation we're currently
1267 // working on. Otherwise we may end up in a situation where two
1268 // devices bounce back and forth downloading from each other,
1269 // neither making any forward progress until one of them decides to
1270 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1271 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001272 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001273 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001274 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001275 int64_t next_data_offset = 0;
1276 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001277 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001278 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1279 &manifest_metadata_size) &&
1280 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001281 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1282 &manifest_signature_size) &&
1283 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001284 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001285 &next_data_offset) &&
1286 next_data_offset != -1 &&
1287 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1288 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001289 minimum_size = manifest_metadata_size + manifest_signature_size +
1290 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001291 }
1292
Sen Jiang0affc2c2017-02-10 15:55:05 -08001293 // TODO(senj): Fix P2P for multiple package.
Sen Jiang2703ef42017-03-16 13:36:21 -07001294 brillo::Blob raw_hash;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001295 if (!base::HexStringToBytes(response.packages[0].hash, &raw_hash))
Sen Jiang2703ef42017-03-16 13:36:21 -07001296 return;
Sen Jiang0affc2c2017-02-10 15:55:05 -08001297 string file_id =
1298 utils::CalculateP2PFileId(raw_hash, response.packages[0].size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001299 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001300 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1301 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001302 system_state_->p2p_manager()->LookupUrlForFile(
1303 file_id,
1304 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001305 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001306 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1307 base::Unretained(this)));
1308 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001309}
1310
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001311bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001312 if (params_->interactive()) {
1313 LOG(INFO) << "Not deferring download because update is interactive.";
1314 return false;
1315 }
1316
David Zeuthen8f191b22013-08-06 12:27:50 -07001317 // If we're using p2p to download _and_ we have a p2p URL, we never
1318 // defer the download. This is because the download will always
1319 // happen from a peer on the LAN and we've been waiting in line for
1320 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001321 const PayloadStateInterface* payload_state = system_state_->payload_state();
1322 if (payload_state->GetUsingP2PForDownloading() &&
1323 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001324 LOG(INFO) << "Download not deferred because download "
1325 << "will happen from a local peer (via p2p).";
1326 return false;
1327 }
1328
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001329 // We should defer the downloads only if we've first satisfied the
1330 // wall-clock-based-waiting period and then the update-check-based waiting
1331 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001332 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001333 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1334 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001335 return false;
1336 }
1337
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001338 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001339 case kWallClockWaitNotSatisfied:
1340 // We haven't even satisfied the first condition, passing the
1341 // wall-clock-based waiting period, so we should defer the downloads
1342 // until that happens.
1343 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1344 return true;
1345
1346 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1347 LOG(INFO) << "wall-clock-based-wait satisfied and "
1348 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001349 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001350
1351 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1352 // Wall-clock-based waiting period is satisfied, and it's determined
1353 // that we do not need the update-check-based wait. so no need to
1354 // defer downloads.
1355 LOG(INFO) << "wall-clock-based-wait satisfied and "
1356 << "update-check-based-wait is not required.";
1357 return false;
1358
1359 default:
1360 // Returning false for this default case so we err on the
1361 // side of downloading updates than deferring in case of any bugs.
1362 NOTREACHED();
1363 return false;
1364 }
1365}
1366
1367OmahaRequestAction::WallClockWaitResult
1368OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001369 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001370 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001371 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001372
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001373 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1374 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1375 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001376 // Note: This timestamp could be that of ANY update we saw in the past
1377 // (not necessarily this particular update we're considering to apply)
1378 // but never got to apply because of some reason (e.g. stop AU policy,
1379 // updates being pulled out from Omaha, changes in target version prefix,
1380 // new update being rolled out, etc.). But for the purposes of scattering
1381 // it doesn't matter which update the timestamp corresponds to. i.e.
1382 // the clock starts ticking the first time we see an update and we're
1383 // ready to apply when the random wait period is satisfied relative to
1384 // that first seen timestamp.
1385 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1386 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1387 << utils::ToString(update_first_seen_at);
1388 } else {
1389 // This seems like an unexpected error where the persisted value exists
1390 // but it's not readable for some reason. Just skip scattering in this
1391 // case to be safe.
1392 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1393 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1394 }
1395 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001396 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001397 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001398 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1399 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001400 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1401 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001402 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001403 // This seems like an unexpected error where the value cannot be
1404 // persisted for some reason. Just skip scattering in this
1405 // case to be safe.
1406 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1407 << utils::ToString(update_first_seen_at)
1408 << " cannot be persisted";
1409 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1410 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001411 }
1412
Sen Jiang7c1171e2016-06-23 11:35:40 -07001413 TimeDelta elapsed_time =
1414 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1415 TimeDelta max_scatter_period =
1416 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001417
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001418 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001419 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001420 << ", Time Elapsed = "
1421 << utils::FormatSecs(elapsed_time.InSeconds())
1422 << ", MaxDaysToScatter = "
1423 << max_scatter_period.InDays();
1424
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001425 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001426 // The deadline is set for all rules which serve a delta update from a
1427 // previous FSI, which means this update will be applied mostly in OOBE
1428 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1429 // quickly.
1430 LOG(INFO) << "Not scattering as deadline flag is set";
1431 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1432 }
1433
1434 if (max_scatter_period.InDays() == 0) {
1435 // This means the Omaha rule creator decides that this rule
1436 // should not be scattered irrespective of the policy.
1437 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1438 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1439 }
1440
1441 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001442 // This means we've waited more than the upperbound wait in the rule
1443 // from the time we first saw a valid update available to us.
1444 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001445 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1446 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1447 }
1448
1449 // This means we are required to participate in scattering.
1450 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001451 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001452 if (remaining_wait_time.InSeconds() <= 0) {
1453 // Yes, it's our turn now.
1454 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1455
1456 // But we can't download until the update-check-count-based wait is also
1457 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001458 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001459 kWallClockWaitDoneButUpdateCheckWaitRequired :
1460 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1461 }
1462
1463 // Not our turn yet, so we have to wait until our turn to
1464 // help scatter the downloads across all clients of the enterprise.
1465 LOG(INFO) << "Update deferred for another "
1466 << utils::FormatSecs(remaining_wait_time.InSeconds())
1467 << " per policy.";
1468 return kWallClockWaitNotSatisfied;
1469}
1470
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001471bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001472 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001473
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001474 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1475 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1476 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001477 // We are unable to read the update check count from file for some reason.
1478 // So let's proceed anyway so as to not stall the update.
1479 LOG(ERROR) << "Unable to read update check count. "
1480 << "Skipping update-check-count-based-wait.";
1481 return true;
1482 }
1483 } else {
1484 // This file does not exist. This means we haven't started our update
1485 // check count down yet, so this is the right time to start the count down.
1486 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001487 params_->min_update_checks_needed(),
1488 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001489
1490 LOG(INFO) << "Randomly picked update check count value = "
1491 << update_check_count_value;
1492
1493 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001494 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1495 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001496 // We weren't able to write the update check count file for some reason.
1497 // So let's proceed anyway so as to not stall the update.
1498 LOG(ERROR) << "Unable to write update check count. "
1499 << "Skipping update-check-count-based-wait.";
1500 return true;
1501 }
1502 }
1503
1504 if (update_check_count_value == 0) {
1505 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1506 return true;
1507 }
1508
1509 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001510 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001511 // We err on the side of skipping scattering logic instead of stalling
1512 // a machine from receiving any updates in case of any unexpected state.
1513 LOG(ERROR) << "Invalid value for update check count detected. "
1514 << "Skipping update-check-count-based-wait.";
1515 return true;
1516 }
1517
1518 // Legal value, we need to wait for more update checks to happen
1519 // until this becomes 0.
1520 LOG(INFO) << "Deferring Omaha updates for another "
1521 << update_check_count_value
1522 << " update checks per policy";
1523 return false;
1524}
1525
David Zeuthen639aa362014-02-03 16:23:44 -08001526// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001527bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001528 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001529 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001530 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001531 &elapsed_days))
1532 return false;
1533
1534 if (elapsed_days < 0)
1535 return false;
1536
1537 output_object->install_date_days = elapsed_days;
1538 return true;
1539}
1540
1541// static
1542bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1543 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001544 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001545 return false;
1546
1547 return prefs->Exists(kPrefsInstallDateDays);
1548}
1549
1550// static
1551bool OmahaRequestAction::PersistInstallDate(
1552 SystemState *system_state,
1553 int install_date_days,
1554 InstallDateProvisioningSource source) {
1555 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1556
1557 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001558 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001559 return false;
1560
1561 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1562 return false;
1563
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001564 system_state->metrics_reporter()->ReportInstallDateProvisioningSource(
David Zeuthen33bae492014-02-25 16:16:18 -08001565 static_cast<int>(source), // Sample.
1566 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001567 return true;
1568}
1569
Alex Deymo8e18f932015-03-27 16:16:59 -07001570bool OmahaRequestAction::PersistCohortData(
1571 const string& prefs_key,
1572 const string& new_value) {
1573 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1574 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1575 return system_state_->prefs()->Delete(prefs_key);
1576 } else if (!new_value.empty()) {
1577 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1578 return system_state_->prefs()->SetString(prefs_key, new_value);
1579 }
1580 return true;
1581}
1582
Alex Deymob3fa53b2016-04-18 19:57:58 -07001583bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1584 auto eol_attr = attrs.find(kEolAttr);
1585 if (eol_attr != attrs.end()) {
1586 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1587 eol_attr->second);
1588 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1589 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1590 }
1591 return true;
1592}
1593
David Zeuthen33bae492014-02-25 16:16:18 -08001594void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1595 // We only want to report this on "update check".
1596 if (ping_only_ || event_ != nullptr)
1597 return;
1598
1599 metrics::CheckResult result = metrics::CheckResult::kUnset;
1600 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1601 metrics::DownloadErrorCode download_error_code =
1602 metrics::DownloadErrorCode::kUnset;
1603
1604 // Regular update attempt.
1605 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001606 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001607 // OK, we parsed the response successfully but that does
1608 // necessarily mean that an update is available.
1609 if (HasOutputPipe()) {
1610 const OmahaResponse& response = GetOutputObject();
1611 if (response.update_exists) {
1612 result = metrics::CheckResult::kUpdateAvailable;
1613 reaction = metrics::CheckReaction::kUpdating;
1614 } else {
1615 result = metrics::CheckResult::kNoUpdateAvailable;
1616 }
1617 } else {
1618 result = metrics::CheckResult::kNoUpdateAvailable;
1619 }
1620 break;
1621
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001622 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001623 result = metrics::CheckResult::kUpdateAvailable;
1624 reaction = metrics::CheckReaction::kIgnored;
1625 break;
1626
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001627 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001628 result = metrics::CheckResult::kUpdateAvailable;
1629 reaction = metrics::CheckReaction::kDeferring;
1630 break;
1631
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001632 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001633 result = metrics::CheckResult::kUpdateAvailable;
1634 reaction = metrics::CheckReaction::kBackingOff;
1635 break;
1636
1637 default:
1638 // We report two flavors of errors, "Download errors" and "Parsing
1639 // error". Try to convert to the former and if that doesn't work
1640 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001641 metrics::DownloadErrorCode tmp_error =
1642 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001643 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1644 result = metrics::CheckResult::kDownloadError;
1645 download_error_code = tmp_error;
1646 } else {
1647 result = metrics::CheckResult::kParsingError;
1648 }
1649 break;
1650 }
1651
Tianjie Xu282aa1f2017-09-05 13:42:45 -07001652 system_state_->metrics_reporter()->ReportUpdateCheckMetrics(
1653 system_state_, result, reaction, download_error_code);
David Zeuthen33bae492014-02-25 16:16:18 -08001654}
1655
Chris Sosa77f79e82014-06-02 18:16:24 -07001656bool OmahaRequestAction::ShouldIgnoreUpdate(
Tao Bao5688d162017-06-06 13:09:06 -07001657 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001658 // Note: policy decision to not update to a version we rolled back from.
1659 string rollback_version =
1660 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001661 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001662 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001663 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001664 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1665 return true;
1666 }
1667 }
1668
Tao Bao5688d162017-06-06 13:09:06 -07001669 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001670 LOG(INFO) << "Update is not allowed over current connection.";
1671 return true;
1672 }
1673
1674 // Note: We could technically delete the UpdateFirstSeenAt state when we
1675 // return true. If we do, it'll mean a device has to restart the
1676 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1677 // turned on again. On the other hand, it also increases the chance of update
1678 // starvation if an admin turns AU on/off more frequently. We choose to err on
1679 // the side of preventing starvation at the cost of not applying scattering in
1680 // those cases.
1681 return false;
1682}
1683
Tao Bao5688d162017-06-06 13:09:06 -07001684bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001685 ConnectionType type;
1686 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001687 ConnectionManagerInterface* connection_manager =
1688 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001689 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001690 LOG(INFO) << "We could not determine our connection type. "
1691 << "Defaulting to allow updates.";
1692 return true;
1693 }
1694 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1695 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001696 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001697 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1698 return is_allowed;
1699}
1700
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001701} // namespace chromeos_update_engine