blob: 94e615d6de9db70e709f303151408c8eaa63dc61 [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>
30#include <base/strings/string_util.h>
31#include <base/strings/stringprintf.h>
32#include <base/time/time.h>
David Zeuthene8ed8632014-07-24 13:38:10 -040033#include <expat.h>
Alex Deymoa2591792015-11-17 00:39:40 -030034#include <metrics/metrics_library.h>
rspangler@google.com49fdf182009-10-10 00:57:34 +000035
Alex Deymo39910dc2015-11-09 17:04:30 -080036#include "update_engine/common/action_pipe.h"
37#include "update_engine/common/constants.h"
38#include "update_engine/common/hardware_interface.h"
39#include "update_engine/common/hash_calculator.h"
40#include "update_engine/common/platform_constants.h"
41#include "update_engine/common/prefs_interface.h"
42#include "update_engine/common/utils.h"
Sen Jiang255e22b2016-05-20 16:15:29 -070043#include "update_engine/connection_manager_interface.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080044#include "update_engine/metrics.h"
45#include "update_engine/metrics_utils.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070046#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070047#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080048#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000049
Darin Petkov1cbd78f2010-07-29 12:38:34 -070050using base::Time;
51using base::TimeDelta;
David Zeuthene8ed8632014-07-24 13:38:10 -040052using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000053using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040054using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000055
56namespace chromeos_update_engine {
57
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080058// List of custom pair tags that we interpret in the Omaha Response:
59static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080060static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070061static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080062// Deprecated: "IsDelta"
63static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080064static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
65static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
66// Deprecated: "ManifestSignatureRsa"
67// Deprecated: "ManifestSize"
68static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
69static const char* kTagMetadataSize = "MetadataSize";
70static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070071// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080072static const char* kTagPrompt = "Prompt";
David Zeuthen8f191b22013-08-06 12:27:50 -070073static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
74static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070075static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080076
Alex Deymoac41a822015-09-15 20:52:53 -070077static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000078
Alex Deymo14ad88e2016-06-29 12:30:14 -070079// X-GoogleUpdate headers.
80static const char* kXGoogleUpdateInteractivity = "X-GoogleUpdate-Interactivity";
81static const char* kXGoogleUpdateAppId = "X-GoogleUpdate-AppId";
82static const char* kXGoogleUpdateUpdater = "X-GoogleUpdate-Updater";
83
Alex Deymob3fa53b2016-04-18 19:57:58 -070084// updatecheck attributes (without the underscore prefix).
85static const char* kEolAttr = "eol";
86
Alex Deymoac41a822015-09-15 20:52:53 -070087namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000088
Darin Petkov1cbd78f2010-07-29 12:38:34 -070089// Returns an XML ping element attribute assignment with attribute
90// |name| and value |ping_days| if |ping_days| has a value that needs
91// to be sent, or an empty string otherwise.
92string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070093 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070094 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070095 return "";
96}
97
98// Returns an XML ping element if any of the elapsed days need to be
99// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700100string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700101 string ping_active = GetPingAttribute("a", ping_active_days);
102 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
103 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700104 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700105 ping_active.c_str(),
106 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700107 }
108 return "";
109}
110
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700111// Returns an XML that goes into the body of the <app> element of the Omaha
112// request based on the given parameters.
113string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700114 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700115 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700116 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700117 int ping_active_days,
118 int ping_roll_call_days,
119 PrefsInterface* prefs) {
120 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700121 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700122 if (include_ping)
123 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700124 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700125 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700126 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700127 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700128 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700129
Darin Petkov265f2902011-05-09 15:17:40 -0700130 // If this is the first update check after a reboot following a previous
131 // update, generate an event containing the previous version number. If
132 // the previous version preference file doesn't exist the event is still
133 // generated with a previous version of 0.0.0.0 -- this is relevant for
134 // older clients or new installs. The previous version event is not sent
135 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700136 // rebooted. The previous version event is also not sent if it was already
137 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700138 string prev_version;
139 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
140 prev_version = "0.0.0.0";
141 }
Alex Deymo87c08862015-10-30 21:56:55 -0700142 // We only store a non-empty previous version value after a successful
143 // update in the previous boot. After reporting it back to the server,
144 // we clear the previous version value so it doesn't get reported again.
145 if (!prev_version.empty()) {
146 app_body += base::StringPrintf(
147 " <event eventtype=\"%d\" eventresult=\"%d\" "
148 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800149 OmahaEvent::kTypeRebootedAfterUpdate,
150 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700151 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
152 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
153 << "Unable to reset the previous version.";
154 }
Darin Petkov95508da2011-01-05 12:42:29 -0800155 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700156 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800157 // The error code is an optional attribute so append it only if the result
158 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700159 string error_code;
160 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700161 error_code = base::StringPrintf(" errorcode=\"%d\"",
162 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700163 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700164 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700165 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700166 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700167 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700168
169 return app_body;
170}
171
Alex Deymo8e18f932015-03-27 16:16:59 -0700172// Returns the cohort* argument to include in the <app> tag for the passed
173// |arg_name| and |prefs_key|, if any. The return value is suitable to
174// concatenate to the list of arguments and includes a space at the end.
175string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700176 const string arg_name,
177 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700178 // There's nothing wrong with not having a given cohort setting, so we check
179 // existance first to avoid the warning log message.
180 if (!prefs->Exists(prefs_key))
181 return "";
182 string cohort_value;
183 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
184 return "";
185 // This is a sanity check to avoid sending a huge XML file back to Ohama due
186 // to a compromised stateful partition making the update check fail in low
187 // network environments envent after a reboot.
188 if (cohort_value.size() > 1024) {
189 LOG(WARNING) << "The omaha cohort setting " << arg_name
190 << " has a too big value, which must be an error or an "
191 "attacker trying to inhibit updates.";
192 return "";
193 }
194
Alex Deymob0d74eb2015-03-30 17:59:17 -0700195 string escaped_xml_value;
196 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
197 LOG(WARNING) << "The omaha cohort setting " << arg_name
198 << " is ASCII-7 invalid, ignoring it.";
199 return "";
200 }
201
Alex Deymo8e18f932015-03-27 16:16:59 -0700202 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700203 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700204}
205
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700206// Returns an XML that corresponds to the entire <app> node of the Omaha
207// request based on the given parameters.
208string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700209 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700210 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700211 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700212 int ping_active_days,
213 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800214 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700215 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700216 string app_body = GetAppBody(event, params, ping_only, include_ping,
217 ping_active_days, ping_roll_call_days,
218 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700219 string app_versions;
220
221 // If we are upgrading to a more stable channel and we are allowed to do
222 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
223 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700224 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700225 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
226 << "on downgrading to the version in the more stable channel";
227 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700228 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700229 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700230 app_versions = "version=\"" +
231 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700232 }
233
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700234 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700235 string app_channels =
236 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
237 if (params->current_channel() != download_channel) {
238 app_channels += "from_track=\"" + XmlEncodeWithDefault(
239 params->current_channel(), "") + "\" ";
240 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700241
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700242 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700243
David Zeuthen639aa362014-02-03 16:23:44 -0800244 // If install_date_days is not set (e.g. its value is -1 ), don't
245 // include the attribute.
246 string install_date_in_days_str = "";
247 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700248 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
249 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800250 }
251
Alex Deymo8e18f932015-03-27 16:16:59 -0700252 string app_cohort_args;
253 app_cohort_args += GetCohortArgXml(system_state->prefs(),
254 "cohort", kPrefsOmahaCohort);
255 app_cohort_args += GetCohortArgXml(system_state->prefs(),
256 "cohorthint", kPrefsOmahaCohortHint);
257 app_cohort_args += GetCohortArgXml(system_state->prefs(),
258 "cohortname", kPrefsOmahaCohortName);
259
Alex Deymoebf6e122017-03-10 16:12:01 -0800260 string fingerprint_arg;
261 if (!params->os_build_fingerprint().empty()) {
262 fingerprint_arg =
263 "fingerprint=\"" + XmlEncodeWithDefault(params->os_build_fingerprint(), "") + "\" ";
264 }
265
Alex Deymob0d74eb2015-03-30 17:59:17 -0700266 string app_xml = " <app "
267 "appid=\"" + XmlEncodeWithDefault(params->GetAppId(), "") + "\" " +
268 app_cohort_args +
269 app_versions +
270 app_channels +
Alex Deymoebf6e122017-03-10 16:12:01 -0800271 fingerprint_arg +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700272 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
273 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
274 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
275 "delta_okay=\"" + delta_okay_str + "\" "
276 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
277 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
278 install_date_in_days_str +
279 ">\n" +
280 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700281 " </app>\n";
282
283 return app_xml;
284}
285
286// Returns an XML that corresponds to the entire <os> node of the Omaha
287// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700288string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700289 string os_xml =" <os "
290 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
291 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
292 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
293 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700294 return os_xml;
295}
296
297// Returns an XML that corresponds to the entire Omaha request based on the
298// given parameters.
299string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700300 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700301 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700302 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700303 int ping_active_days,
304 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800305 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700306 SystemState* system_state) {
307 string os_xml = GetOsXml(params);
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700308 string app_xml = GetAppXml(event, params, ping_only, include_ping,
309 ping_active_days, ping_roll_call_days,
310 install_date_in_days, system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700311
Alex Vakulenko75039d72014-03-25 12:36:28 -0700312 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700313 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700314
Alex Deymoac41a822015-09-15 20:52:53 -0700315 string updater_version = XmlEncodeWithDefault(
316 base::StringPrintf("%s-%s",
317 constants::kOmahaUpdaterID,
318 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700319 string request_xml =
320 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700321 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700322 "version=\"" + updater_version + "\" "
323 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700324 install_source +
325 "ismachine=\"1\">\n") +
326 os_xml +
327 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700328 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700329
330 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000331}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700332
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700333} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000334
David Zeuthene8ed8632014-07-24 13:38:10 -0400335// Struct used for holding data obtained when parsing the XML.
336struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400337 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
338
339 // Pointer to the expat XML_Parser object.
340 XML_Parser xml_parser;
341
David Zeuthene8ed8632014-07-24 13:38:10 -0400342 // This is the state of the parser as it's processing the XML.
343 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400344 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400345 string current_path;
346
347 // These are the values extracted from the XML.
Alex Deymo8e18f932015-03-27 16:16:59 -0700348 string app_cohort;
349 string app_cohorthint;
350 string app_cohortname;
351 bool app_cohort_set = false;
352 bool app_cohorthint_set = false;
353 bool app_cohortname_set = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400354 string updatecheck_status;
355 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700356 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400357 string daystart_elapsed_days;
358 string daystart_elapsed_seconds;
359 vector<string> url_codebase;
360 string package_name;
361 string package_size;
Sen Jiang2703ef42017-03-16 13:36:21 -0700362 string package_hash;
David Zeuthene8ed8632014-07-24 13:38:10 -0400363 string manifest_version;
364 map<string, string> action_postinstall_attrs;
365};
366
367namespace {
368
369// Callback function invoked by expat.
370void ParserHandlerStart(void* user_data, const XML_Char* element,
371 const XML_Char** attr) {
372 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
373
374 if (data->failed)
375 return;
376
377 data->current_path += string("/") + element;
378
379 map<string, string> attrs;
380 if (attr != nullptr) {
381 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
382 string key = attr[n];
383 string value = attr[n + 1];
384 attrs[key] = value;
385 }
386 }
387
Alex Deymo8e18f932015-03-27 16:16:59 -0700388 if (data->current_path == "/response/app") {
389 if (attrs.find("cohort") != attrs.end()) {
390 data->app_cohort_set = true;
391 data->app_cohort = attrs["cohort"];
392 }
393 if (attrs.find("cohorthint") != attrs.end()) {
394 data->app_cohorthint_set = true;
395 data->app_cohorthint = attrs["cohorthint"];
396 }
397 if (attrs.find("cohortname") != attrs.end()) {
398 data->app_cohortname_set = true;
399 data->app_cohortname = attrs["cohortname"];
400 }
401 } else if (data->current_path == "/response/app/updatecheck") {
David Zeuthene8ed8632014-07-24 13:38:10 -0400402 // There is only supposed to be a single <updatecheck> element.
403 data->updatecheck_status = attrs["status"];
404 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700405 // Omaha sends arbitrary key-value pairs as extra attributes starting with
406 // an underscore.
407 for (const auto& attr : attrs) {
408 if (!attr.first.empty() && attr.first[0] == '_')
409 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
410 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400411 } else if (data->current_path == "/response/daystart") {
412 // Get the install-date.
413 data->daystart_elapsed_days = attrs["elapsed_days"];
414 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
415 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
416 // Look at all <url> elements.
417 data->url_codebase.push_back(attrs["codebase"]);
418 } else if (data->package_name.empty() && data->current_path ==
419 "/response/app/updatecheck/manifest/packages/package") {
420 // Only look at the first <package>.
421 data->package_name = attrs["name"];
422 data->package_size = attrs["size"];
Sen Jiang2703ef42017-03-16 13:36:21 -0700423 data->package_hash = attrs["hash_sha256"];
David Zeuthene8ed8632014-07-24 13:38:10 -0400424 } else if (data->current_path == "/response/app/updatecheck/manifest") {
425 // Get the version.
426 data->manifest_version = attrs[kTagVersion];
427 } else if (data->current_path ==
428 "/response/app/updatecheck/manifest/actions/action") {
429 // We only care about the postinstall action.
430 if (attrs["event"] == "postinstall") {
431 data->action_postinstall_attrs = attrs;
432 }
433 }
434}
435
436// Callback function invoked by expat.
437void ParserHandlerEnd(void* user_data, const XML_Char* element) {
438 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
439 if (data->failed)
440 return;
441
442 const string path_suffix = string("/") + element;
443
Alex Vakulenko0103c362016-01-20 07:56:15 -0800444 if (!base::EndsWith(data->current_path, path_suffix,
445 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400446 LOG(ERROR) << "Unexpected end element '" << element
447 << "' with current_path='" << data->current_path << "'";
448 data->failed = true;
449 return;
450 }
451 data->current_path.resize(data->current_path.size() - path_suffix.size());
452}
453
David Zeuthenf3e28012014-08-26 18:23:52 -0400454// Callback function invoked by expat.
455//
456// This is called for entity declarations. Since Omaha is guaranteed
457// to never return any XML with entities our course of action is to
458// just stop parsing. This avoids potential resource exhaustion
459// problems AKA the "billion laughs". CVE-2013-0340.
460void ParserHandlerEntityDecl(void *user_data,
461 const XML_Char *entity_name,
462 int is_parameter_entity,
463 const XML_Char *value,
464 int value_length,
465 const XML_Char *base,
466 const XML_Char *system_id,
467 const XML_Char *public_id,
468 const XML_Char *notation_name) {
469 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
470
471 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
472 data->failed = true;
473 data->entity_decl = true;
474 XML_StopParser(data->xml_parser, false);
475}
476
David Zeuthene8ed8632014-07-24 13:38:10 -0400477} // namespace
478
Alex Deymob0d74eb2015-03-30 17:59:17 -0700479bool XmlEncode(const string& input, string* output) {
480 if (std::find_if(input.begin(), input.end(),
481 [](const char c){return c & 0x80;}) != input.end()) {
482 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
483 utils::HexDumpString(input);
484 return false;
485 }
Alex Deymocc457852015-06-18 18:35:50 -0700486 output->clear();
487 // We need at least input.size() space in the output, but the code below will
488 // handle it if we need more.
489 output->reserve(input.size());
490 for (char c : input) {
491 switch (c) {
492 case '\"':
493 output->append("&quot;");
494 break;
495 case '\'':
496 output->append("&apos;");
497 break;
498 case '&':
499 output->append("&amp;");
500 break;
501 case '<':
502 output->append("&lt;");
503 break;
504 case '>':
505 output->append("&gt;");
506 break;
507 default:
508 output->push_back(c);
509 }
510 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700511 return true;
512}
513
514string XmlEncodeWithDefault(const string& input, const string& default_value) {
515 string output;
516 if (XmlEncode(input, &output))
517 return output;
518 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000519}
520
Alex Deymoc1c17b42015-11-23 03:53:15 -0300521OmahaRequestAction::OmahaRequestAction(
522 SystemState* system_state,
523 OmahaEvent* event,
524 std::unique_ptr<HttpFetcher> http_fetcher,
525 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800526 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700527 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300528 http_fetcher_(std::move(http_fetcher)),
Thieu Le116fda32011-04-19 11:01:54 -0700529 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700530 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700531 ping_roll_call_days_(0) {
532 params_ = system_state->request_params();
533}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000534
Darin Petkov6a5b3222010-07-13 14:55:28 -0700535OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000536
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700537// Calculates the value to use for the ping days parameter.
538int OmahaRequestAction::CalculatePingDays(const string& key) {
539 int days = kNeverPinged;
540 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800541 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700542 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
543 if (days < 0) {
544 // If |days| is negative, then the system clock must have jumped
545 // back in time since the ping was sent. Mark the value so that
546 // it doesn't get sent to the server but we still update the
547 // last ping daystart preference. This way the next ping time
548 // will be correct, hopefully.
549 days = kPingTimeJump;
550 LOG(WARNING) <<
551 "System clock jumped back in time. Resetting ping daystarts.";
552 }
553 }
554 return days;
555}
556
557void OmahaRequestAction::InitPingDays() {
558 // We send pings only along with update checks, not with events.
559 if (IsEvent()) {
560 return;
561 }
562 // TODO(petkov): Figure a way to distinguish active use pings
563 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700564 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700565 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
566 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
567}
568
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700569bool OmahaRequestAction::ShouldPing() const {
570 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
571 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
572 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
573 if (powerwash_count > 0) {
574 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
575 << "powerwash_count is " << powerwash_count;
576 return false;
577 }
578 return true;
579 }
580 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
581}
582
David Zeuthen639aa362014-02-03 16:23:44 -0800583// static
584int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
585 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700586 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800587 return -1;
588
589 // If we have the value stored on disk, just return it.
590 int64_t stored_value;
591 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
592 // Convert and sanity-check.
593 int install_date_days = static_cast<int>(stored_value);
594 if (install_date_days >= 0)
595 return install_date_days;
596 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
597 << install_date_days << " looks suspicious.";
598 prefs->Delete(kPrefsInstallDateDays);
599 }
600
601 // Otherwise, if OOBE is not complete then do nothing and wait for
602 // ParseResponse() to call ParseInstallDate() and then
603 // PersistInstallDate() to set the kPrefsInstallDateDays state
604 // variable. Once that is done, we'll then report back in future
605 // Omaha requests. This works exactly because OOBE triggers an
606 // update check.
607 //
608 // However, if OOBE is complete and the kPrefsInstallDateDays state
609 // variable is not set, there are two possibilities
610 //
611 // 1. The update check in OOBE failed so we never got a response
612 // from Omaha (no network etc.); or
613 //
614 // 2. OOBE was done on an older version that didn't write to the
615 // kPrefsInstallDateDays state variable.
616 //
617 // In both cases, we approximate the install date by simply
618 // inspecting the timestamp of when OOBE happened.
619
620 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700621 if (!system_state->hardware()->IsOOBEEnabled() ||
622 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800623 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700624 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800625 return -1;
626 }
627
628 int num_days;
629 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
630 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
631 << "as its value '" << utils::ToString(time_of_oobe)
632 << "' looks suspicious.";
633 return -1;
634 }
635
636 // Persist this to disk, for future use.
637 if (!OmahaRequestAction::PersistInstallDate(system_state,
638 num_days,
639 kProvisionedFromOOBEMarker))
640 return -1;
641
642 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
643 << num_days << " days";
644
645 return num_days;
646}
647
Darin Petkov6a5b3222010-07-13 14:55:28 -0700648void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000649 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700650 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700651 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700652 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700653 return;
654 }
David Zeuthen639aa362014-02-03 16:23:44 -0800655
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700656 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700657 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700658 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700659 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700660 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800661 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800662 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700663 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700664
Alex Deymo14ad88e2016-06-29 12:30:14 -0700665 // Set X-GoogleUpdate headers.
666 http_fetcher_->SetHeader(kXGoogleUpdateInteractivity,
667 params_->interactive() ? "fg" : "bg");
668 http_fetcher_->SetHeader(kXGoogleUpdateAppId, params_->GetAppId());
669 http_fetcher_->SetHeader(
670 kXGoogleUpdateUpdater,
671 base::StringPrintf(
672 "%s-%s", constants::kOmahaUpdaterID, kOmahaUpdaterVersion));
673
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800674 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
675 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700676 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700677 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700678 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000679}
680
Darin Petkov6a5b3222010-07-13 14:55:28 -0700681void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000682 http_fetcher_->TerminateTransfer();
683}
684
685// We just store the response in the buffer. Once we've received all bytes,
686// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700687void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800688 const void* bytes,
689 size_t length) {
690 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
691 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000692}
693
694namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000695
696// Parses a 64 bit base-10 int from a string and returns it. Returns 0
697// on error. If the string contains "0", that's indistinguishable from
698// error.
699off_t ParseInt(const string& str) {
700 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700701 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000702 if (rc < 1) {
703 // failure
704 return 0;
705 }
706 return ret;
707}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700708
David Zeuthene8ed8632014-07-24 13:38:10 -0400709// Parses |str| and returns |true| if, and only if, its value is "true".
710bool ParseBool(const string& str) {
711 return str == "true";
712}
713
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700714// Update the last ping day preferences based on the server daystart
715// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400716bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700717 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400718 TEST_AND_RETURN_FALSE(
719 base::StringToInt64(parser_data->daystart_elapsed_seconds,
720 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700721 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
722
723 // Remember the local time that matches the server's last midnight
724 // time.
725 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
726 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
727 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
728 return true;
729}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700730} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000731
David Zeuthene8ed8632014-07-24 13:38:10 -0400732bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700733 OmahaResponse* output_object,
734 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400735 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700736 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700737 return false;
738 }
739
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800740 // chromium-os:37289: The PollInterval is not supported by Omaha server
741 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700742 // slow down the request rate from the server-side. Note that the PollInterval
743 // is not persisted, so it has to be sent by the server on every response to
744 // guarantee that the scheduler uses this value (otherwise, if the device got
745 // rebooted after the last server-indicated value, it'll revert to the default
746 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
747 // based on the assumption that we perform an update check every hour so that
748 // the max value of 8 will roughly be equivalent to one work day. If we decide
749 // to use PollInterval permanently, we should update the
750 // max_update_checks_allowed to take PollInterval into account. Note: The
751 // parsing for PollInterval happens even before parsing of the status because
752 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400753 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700754 &output_object->poll_interval);
755
David Zeuthen639aa362014-02-03 16:23:44 -0800756 // Check for the "elapsed_days" attribute in the "daystart"
757 // element. This is the number of days since Jan 1 2007, 0:00
758 // PST. If we don't have a persisted value of the Omaha InstallDate,
759 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400760 if (ParseInstallDate(parser_data, output_object) &&
761 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800762 // Since output_object->install_date_days is never negative, the
763 // elapsed_days -> install-date calculation is reduced to simply
764 // rounding down to the nearest number divisible by 7.
765 int remainder = output_object->install_date_days % 7;
766 int install_date_days_rounded =
767 output_object->install_date_days - remainder;
768 if (PersistInstallDate(system_state_,
769 install_date_days_rounded,
770 kProvisionedFromOmahaResponse)) {
771 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
772 << install_date_days_rounded << " days";
773 }
774 }
775
Alex Deymo00d79ac2015-06-29 15:41:49 -0700776 // We persist the cohorts sent by omaha even if the status is "noupdate".
777 if (parser_data->app_cohort_set)
778 PersistCohortData(kPrefsOmahaCohort, parser_data->app_cohort);
779 if (parser_data->app_cohorthint_set)
780 PersistCohortData(kPrefsOmahaCohortHint, parser_data->app_cohorthint);
781 if (parser_data->app_cohortname_set)
782 PersistCohortData(kPrefsOmahaCohortName, parser_data->app_cohortname);
783
Alex Deymob3fa53b2016-04-18 19:57:58 -0700784 // Parse the updatecheck attributes.
785 PersistEolStatus(parser_data->updatecheck_attrs);
786
David Zeuthene8ed8632014-07-24 13:38:10 -0400787 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700788 return false;
789
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800790 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
791 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400792 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700793 return false;
794
David Zeuthene8ed8632014-07-24 13:38:10 -0400795 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700796 return false;
797
David Zeuthene8ed8632014-07-24 13:38:10 -0400798 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700799 return false;
800
801 return true;
802}
803
David Zeuthene8ed8632014-07-24 13:38:10 -0400804bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700805 OmahaResponse* output_object,
806 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400807 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700808 if (status == "noupdate") {
809 LOG(INFO) << "No update.";
810 output_object->update_exists = false;
811 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700812 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700813 return false;
814 }
815
816 if (status != "ok") {
817 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700818 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700819 return false;
820 }
821
822 return true;
823}
824
David Zeuthene8ed8632014-07-24 13:38:10 -0400825bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700826 OmahaResponse* output_object,
827 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400828 if (parser_data->url_codebase.empty()) {
829 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700830 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700831 return false;
832 }
833
David Zeuthene8ed8632014-07-24 13:38:10 -0400834 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800835 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400836 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800837 if (codebase.empty()) {
838 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700839 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800840 return false;
841 }
842 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700843 }
844
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700845 return true;
846}
847
David Zeuthene8ed8632014-07-24 13:38:10 -0400848bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700849 OmahaResponse* output_object,
850 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400851 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700852 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700853 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700854 return false;
855 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800856
857 // Append the package name to each URL in our list so that we don't
858 // propagate the urlBase vs packageName distinctions beyond this point.
859 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400860 for (auto& payload_url : output_object->payload_urls)
861 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700862
863 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400864 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700865 if (size <= 0) {
866 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700867 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700868 return false;
869 }
870 output_object->size = size;
871
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800872 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700873
Sen Jiang2703ef42017-03-16 13:36:21 -0700874 output_object->hash = parser_data->package_hash;
875 if (output_object->hash.empty()) {
876 LOG(ERROR) << "Omaha Response has empty hash_sha256 value";
877 completer->set_code(ErrorCode::kOmahaResponseInvalid);
878 return false;
879 }
880
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700881 return true;
882}
883
David Zeuthene8ed8632014-07-24 13:38:10 -0400884bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700885 OmahaResponse* output_object,
886 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400887 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700888 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700889 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700890 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700891 return false;
892 }
893
894 LOG(INFO) << "Received omaha response to update to version "
895 << output_object->version;
896
David Zeuthene8ed8632014-07-24 13:38:10 -0400897 map<string, string> attrs = parser_data->action_postinstall_attrs;
898 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700899 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700900 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700901 return false;
902 }
903
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800904 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400905 output_object->more_info_url = attrs[kTagMoreInfo];
906 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
907 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
908 output_object->prompt = ParseBool(attrs[kTagPrompt]);
909 output_object->deadline = attrs[kTagDeadline];
910 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700911 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400912 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700913 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400914 ParseBool(attrs[kTagDisableP2PForSharing]);
915 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800916
David Zeuthene8ed8632014-07-24 13:38:10 -0400917 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800918 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800919 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700920
David Zeuthene8ed8632014-07-24 13:38:10 -0400921 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800922
923 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400924 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800925
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700926 return true;
927}
928
David Zeuthene8ed8632014-07-24 13:38:10 -0400929// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000930// and fill in the appropriate fields of the output object. Also, notifies
931// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700932void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
933 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000934 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800935 string current_response(response_buffer_.begin(), response_buffer_.end());
936 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700937
Gilad Arnold74b5f552014-10-07 08:17:16 -0700938 PayloadStateInterface* const payload_state = system_state_->payload_state();
939
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700940 // Events are best effort transactions -- assume they always succeed.
941 if (IsEvent()) {
942 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700943 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700944 return;
945 }
946
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700947 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700948 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700949 int code = GetHTTPResponseCode();
950 // Makes sure we send sane error values.
951 if (code < 0 || code >= 1000) {
952 code = 999;
953 }
David Zeuthena99981f2013-04-29 13:42:47 -0700954 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700955 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000956 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700957 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000958
David Zeuthene8ed8632014-07-24 13:38:10 -0400959 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400960 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400961 XML_SetUserData(parser, &parser_data);
962 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400963 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800964 XML_Status res = XML_Parse(
965 parser,
966 reinterpret_cast<const char*>(response_buffer_.data()),
967 response_buffer_.size(),
968 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400969 XML_ParserFree(parser);
970
971 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700972 LOG(ERROR) << "Omaha response not valid XML: "
973 << XML_ErrorString(XML_GetErrorCode(parser))
974 << " at line " << XML_GetCurrentLineNumber(parser)
975 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400976 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
977 if (response_buffer_.empty()) {
978 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
979 } else if (parser_data.entity_decl) {
980 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
981 }
982 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000983 return;
984 }
985
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700986 // Update the last ping day preferences based on the server daystart response
987 // even if we didn't send a ping. Omaha always includes the daystart in the
988 // response, but log the error if it didn't.
989 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
990 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700991
Thieu Le116fda32011-04-19 11:01:54 -0700992 if (!HasOutputPipe()) {
993 // Just set success to whether or not the http transfer succeeded,
994 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700995 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700996 return;
997 }
998
Darin Petkov6a5b3222010-07-13 14:55:28 -0700999 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -04001000 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +00001001 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001002 output_object.update_exists = true;
1003 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +00001004
Tao Bao5688d162017-06-06 13:09:06 -07001005 if (ShouldIgnoreUpdate(output_object)) {
1006 output_object.update_exists = false;
1007 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -07001008 return;
1009 }
1010
David Zeuthen8f191b22013-08-06 12:27:50 -07001011 // If Omaha says to disable p2p, respect that
1012 if (output_object.disable_p2p_for_downloading) {
1013 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
1014 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001015 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001016 }
1017 if (output_object.disable_p2p_for_sharing) {
1018 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
1019 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001020 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001021 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001022
1023 // Update the payload state with the current response. The payload state
1024 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001025 // from what's stored already. We are updating the payload state as late
1026 // as possible in this method so that if a new release gets pushed and then
1027 // got pulled back due to some issues, we don't want to clear our internal
1028 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001029 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001030
David Zeuthen8f191b22013-08-06 12:27:50 -07001031 // It could be we've already exceeded the deadline for when p2p is
1032 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001033 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001034 payload_state->P2PNewAttempt();
1035 if (!payload_state->P2PAttemptAllowed()) {
1036 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1037 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001038 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001039 }
1040 }
1041
1042 // From here on, we'll complete stuff in CompleteProcessing() so
1043 // disable |completer| since we'll create a new one in that
1044 // function.
1045 completer.set_should_complete(false);
1046
1047 // If we're allowed to use p2p for downloading we do not pay
1048 // attention to wall-clock-based waiting if the URL is indeed
1049 // available via p2p. Therefore, check if the file is available via
1050 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001051 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001052 LookupPayloadViaP2P(output_object);
1053 } else {
1054 CompleteProcessing();
1055 }
1056}
1057
1058void OmahaRequestAction::CompleteProcessing() {
1059 ScopedActionCompleter completer(processor_, this);
1060 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1061 PayloadStateInterface* payload_state = system_state_->payload_state();
1062
Alex Deymo46a9aae2016-05-04 20:20:11 -07001063 if (system_state_->hardware()->IsOOBEEnabled() &&
1064 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001065 output_object.deadline.empty() &&
1066 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001067 output_object.update_exists = false;
1068 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1069 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1070 return;
1071 }
1072
David Zeuthen8f191b22013-08-06 12:27:50 -07001073 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001074 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001075 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001076 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001077 return;
1078 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001079
Chris Sosa20f005c2013-09-05 13:53:08 -07001080 if (payload_state->ShouldBackoffDownload()) {
1081 output_object.update_exists = false;
1082 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1083 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001084 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001085 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001086 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001087 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001088}
1089
1090void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1091 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1092 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001093 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001094 } else {
1095 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1096 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001097 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001098 }
1099 CompleteProcessing();
1100}
1101
1102void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001103 // If the device is in the middle of an update, the state variables
1104 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1105 // tracks the offset and length of the operation currently in
1106 // progress. The offset is based from the end of the manifest which
1107 // is kPrefsManifestMetadataSize bytes long.
1108 //
1109 // To make forward progress and avoid deadlocks, we need to find a
1110 // peer that has at least the entire operation we're currently
1111 // working on. Otherwise we may end up in a situation where two
1112 // devices bounce back and forth downloading from each other,
1113 // neither making any forward progress until one of them decides to
1114 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1115 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001116 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001117 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001118 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001119 int64_t next_data_offset = 0;
1120 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001121 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001122 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1123 &manifest_metadata_size) &&
1124 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001125 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1126 &manifest_signature_size) &&
1127 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001128 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001129 &next_data_offset) &&
1130 next_data_offset != -1 &&
1131 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1132 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001133 minimum_size = manifest_metadata_size + manifest_signature_size +
1134 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001135 }
1136
Sen Jiang2703ef42017-03-16 13:36:21 -07001137 brillo::Blob raw_hash;
1138 if (!base::HexStringToBytes(response.hash, &raw_hash))
1139 return;
1140 string file_id = utils::CalculateP2PFileId(raw_hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001141 if (system_state_->p2p_manager()) {
Sen Jiang2703ef42017-03-16 13:36:21 -07001142 LOG(INFO) << "Checking if payload is available via p2p, file_id=" << file_id
1143 << " minimum_size=" << minimum_size;
David Zeuthen8f191b22013-08-06 12:27:50 -07001144 system_state_->p2p_manager()->LookupUrlForFile(
1145 file_id,
1146 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001147 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001148 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1149 base::Unretained(this)));
1150 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001151}
1152
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001153bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001154 if (params_->interactive()) {
1155 LOG(INFO) << "Not deferring download because update is interactive.";
1156 return false;
1157 }
1158
David Zeuthen8f191b22013-08-06 12:27:50 -07001159 // If we're using p2p to download _and_ we have a p2p URL, we never
1160 // defer the download. This is because the download will always
1161 // happen from a peer on the LAN and we've been waiting in line for
1162 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001163 const PayloadStateInterface* payload_state = system_state_->payload_state();
1164 if (payload_state->GetUsingP2PForDownloading() &&
1165 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001166 LOG(INFO) << "Download not deferred because download "
1167 << "will happen from a local peer (via p2p).";
1168 return false;
1169 }
1170
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001171 // We should defer the downloads only if we've first satisfied the
1172 // wall-clock-based-waiting period and then the update-check-based waiting
1173 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001174 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001175 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1176 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001177 return false;
1178 }
1179
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001180 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001181 case kWallClockWaitNotSatisfied:
1182 // We haven't even satisfied the first condition, passing the
1183 // wall-clock-based waiting period, so we should defer the downloads
1184 // until that happens.
1185 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1186 return true;
1187
1188 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1189 LOG(INFO) << "wall-clock-based-wait satisfied and "
1190 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001191 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001192
1193 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1194 // Wall-clock-based waiting period is satisfied, and it's determined
1195 // that we do not need the update-check-based wait. so no need to
1196 // defer downloads.
1197 LOG(INFO) << "wall-clock-based-wait satisfied and "
1198 << "update-check-based-wait is not required.";
1199 return false;
1200
1201 default:
1202 // Returning false for this default case so we err on the
1203 // side of downloading updates than deferring in case of any bugs.
1204 NOTREACHED();
1205 return false;
1206 }
1207}
1208
1209OmahaRequestAction::WallClockWaitResult
1210OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001211 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001212 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001213 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001214
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001215 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1216 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1217 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001218 // Note: This timestamp could be that of ANY update we saw in the past
1219 // (not necessarily this particular update we're considering to apply)
1220 // but never got to apply because of some reason (e.g. stop AU policy,
1221 // updates being pulled out from Omaha, changes in target version prefix,
1222 // new update being rolled out, etc.). But for the purposes of scattering
1223 // it doesn't matter which update the timestamp corresponds to. i.e.
1224 // the clock starts ticking the first time we see an update and we're
1225 // ready to apply when the random wait period is satisfied relative to
1226 // that first seen timestamp.
1227 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1228 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1229 << utils::ToString(update_first_seen_at);
1230 } else {
1231 // This seems like an unexpected error where the persisted value exists
1232 // but it's not readable for some reason. Just skip scattering in this
1233 // case to be safe.
1234 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1235 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1236 }
1237 } else {
Sen Jiang7c1171e2016-06-23 11:35:40 -07001238 update_first_seen_at = system_state_->clock()->GetWallclockTime();
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001239 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001240 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1241 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001242 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1243 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001244 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001245 // This seems like an unexpected error where the value cannot be
1246 // persisted for some reason. Just skip scattering in this
1247 // case to be safe.
1248 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1249 << utils::ToString(update_first_seen_at)
1250 << " cannot be persisted";
1251 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1252 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001253 }
1254
Sen Jiang7c1171e2016-06-23 11:35:40 -07001255 TimeDelta elapsed_time =
1256 system_state_->clock()->GetWallclockTime() - update_first_seen_at;
1257 TimeDelta max_scatter_period =
1258 TimeDelta::FromDays(output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001259
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001260 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001261 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001262 << ", Time Elapsed = "
1263 << utils::FormatSecs(elapsed_time.InSeconds())
1264 << ", MaxDaysToScatter = "
1265 << max_scatter_period.InDays();
1266
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001267 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001268 // The deadline is set for all rules which serve a delta update from a
1269 // previous FSI, which means this update will be applied mostly in OOBE
1270 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1271 // quickly.
1272 LOG(INFO) << "Not scattering as deadline flag is set";
1273 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1274 }
1275
1276 if (max_scatter_period.InDays() == 0) {
1277 // This means the Omaha rule creator decides that this rule
1278 // should not be scattered irrespective of the policy.
1279 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1280 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1281 }
1282
1283 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001284 // This means we've waited more than the upperbound wait in the rule
1285 // from the time we first saw a valid update available to us.
1286 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001287 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1288 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1289 }
1290
1291 // This means we are required to participate in scattering.
1292 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001293 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001294 if (remaining_wait_time.InSeconds() <= 0) {
1295 // Yes, it's our turn now.
1296 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1297
1298 // But we can't download until the update-check-count-based wait is also
1299 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001300 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001301 kWallClockWaitDoneButUpdateCheckWaitRequired :
1302 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1303 }
1304
1305 // Not our turn yet, so we have to wait until our turn to
1306 // help scatter the downloads across all clients of the enterprise.
1307 LOG(INFO) << "Update deferred for another "
1308 << utils::FormatSecs(remaining_wait_time.InSeconds())
1309 << " per policy.";
1310 return kWallClockWaitNotSatisfied;
1311}
1312
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001313bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001314 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001315
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001316 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1317 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1318 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001319 // We are unable to read the update check count from file for some reason.
1320 // So let's proceed anyway so as to not stall the update.
1321 LOG(ERROR) << "Unable to read update check count. "
1322 << "Skipping update-check-count-based-wait.";
1323 return true;
1324 }
1325 } else {
1326 // This file does not exist. This means we haven't started our update
1327 // check count down yet, so this is the right time to start the count down.
1328 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001329 params_->min_update_checks_needed(),
1330 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001331
1332 LOG(INFO) << "Randomly picked update check count value = "
1333 << update_check_count_value;
1334
1335 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001336 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1337 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001338 // We weren't able to write the update check count file for some reason.
1339 // So let's proceed anyway so as to not stall the update.
1340 LOG(ERROR) << "Unable to write update check count. "
1341 << "Skipping update-check-count-based-wait.";
1342 return true;
1343 }
1344 }
1345
1346 if (update_check_count_value == 0) {
1347 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1348 return true;
1349 }
1350
1351 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001352 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001353 // We err on the side of skipping scattering logic instead of stalling
1354 // a machine from receiving any updates in case of any unexpected state.
1355 LOG(ERROR) << "Invalid value for update check count detected. "
1356 << "Skipping update-check-count-based-wait.";
1357 return true;
1358 }
1359
1360 // Legal value, we need to wait for more update checks to happen
1361 // until this becomes 0.
1362 LOG(INFO) << "Deferring Omaha updates for another "
1363 << update_check_count_value
1364 << " update checks per policy";
1365 return false;
1366}
1367
David Zeuthen639aa362014-02-03 16:23:44 -08001368// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001369bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001370 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001371 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001372 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001373 &elapsed_days))
1374 return false;
1375
1376 if (elapsed_days < 0)
1377 return false;
1378
1379 output_object->install_date_days = elapsed_days;
1380 return true;
1381}
1382
1383// static
1384bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1385 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001386 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001387 return false;
1388
1389 return prefs->Exists(kPrefsInstallDateDays);
1390}
1391
1392// static
1393bool OmahaRequestAction::PersistInstallDate(
1394 SystemState *system_state,
1395 int install_date_days,
1396 InstallDateProvisioningSource source) {
1397 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1398
1399 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001400 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001401 return false;
1402
1403 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1404 return false;
1405
Alex Deymoaf9a8632015-09-23 18:51:48 -07001406 string metric_name = metrics::kMetricInstallDateProvisioningSource;
David Zeuthen33bae492014-02-25 16:16:18 -08001407 system_state->metrics_lib()->SendEnumToUMA(
1408 metric_name,
1409 static_cast<int>(source), // Sample.
1410 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001411
1412 return true;
1413}
1414
Alex Deymo8e18f932015-03-27 16:16:59 -07001415bool OmahaRequestAction::PersistCohortData(
1416 const string& prefs_key,
1417 const string& new_value) {
1418 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1419 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1420 return system_state_->prefs()->Delete(prefs_key);
1421 } else if (!new_value.empty()) {
1422 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1423 return system_state_->prefs()->SetString(prefs_key, new_value);
1424 }
1425 return true;
1426}
1427
Alex Deymob3fa53b2016-04-18 19:57:58 -07001428bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1429 auto eol_attr = attrs.find(kEolAttr);
1430 if (eol_attr != attrs.end()) {
1431 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1432 eol_attr->second);
1433 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1434 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1435 }
1436 return true;
1437}
1438
David Zeuthen33bae492014-02-25 16:16:18 -08001439void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1440 // We only want to report this on "update check".
1441 if (ping_only_ || event_ != nullptr)
1442 return;
1443
1444 metrics::CheckResult result = metrics::CheckResult::kUnset;
1445 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1446 metrics::DownloadErrorCode download_error_code =
1447 metrics::DownloadErrorCode::kUnset;
1448
1449 // Regular update attempt.
1450 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001451 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001452 // OK, we parsed the response successfully but that does
1453 // necessarily mean that an update is available.
1454 if (HasOutputPipe()) {
1455 const OmahaResponse& response = GetOutputObject();
1456 if (response.update_exists) {
1457 result = metrics::CheckResult::kUpdateAvailable;
1458 reaction = metrics::CheckReaction::kUpdating;
1459 } else {
1460 result = metrics::CheckResult::kNoUpdateAvailable;
1461 }
1462 } else {
1463 result = metrics::CheckResult::kNoUpdateAvailable;
1464 }
1465 break;
1466
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001467 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001468 result = metrics::CheckResult::kUpdateAvailable;
1469 reaction = metrics::CheckReaction::kIgnored;
1470 break;
1471
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001472 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001473 result = metrics::CheckResult::kUpdateAvailable;
1474 reaction = metrics::CheckReaction::kDeferring;
1475 break;
1476
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001477 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001478 result = metrics::CheckResult::kUpdateAvailable;
1479 reaction = metrics::CheckReaction::kBackingOff;
1480 break;
1481
1482 default:
1483 // We report two flavors of errors, "Download errors" and "Parsing
1484 // error". Try to convert to the former and if that doesn't work
1485 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001486 metrics::DownloadErrorCode tmp_error =
1487 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001488 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1489 result = metrics::CheckResult::kDownloadError;
1490 download_error_code = tmp_error;
1491 } else {
1492 result = metrics::CheckResult::kParsingError;
1493 }
1494 break;
1495 }
1496
1497 metrics::ReportUpdateCheckMetrics(system_state_,
1498 result, reaction, download_error_code);
1499}
1500
Chris Sosa77f79e82014-06-02 18:16:24 -07001501bool OmahaRequestAction::ShouldIgnoreUpdate(
Tao Bao5688d162017-06-06 13:09:06 -07001502 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001503 // Note: policy decision to not update to a version we rolled back from.
1504 string rollback_version =
1505 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001506 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001507 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001508 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001509 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1510 return true;
1511 }
1512 }
1513
Tao Bao5688d162017-06-06 13:09:06 -07001514 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001515 LOG(INFO) << "Update is not allowed over current connection.";
1516 return true;
1517 }
1518
1519 // Note: We could technically delete the UpdateFirstSeenAt state when we
1520 // return true. If we do, it'll mean a device has to restart the
1521 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1522 // turned on again. On the other hand, it also increases the chance of update
1523 // starvation if an admin turns AU on/off more frequently. We choose to err on
1524 // the side of preventing starvation at the cost of not applying scattering in
1525 // those cases.
1526 return false;
1527}
1528
Tao Bao5688d162017-06-06 13:09:06 -07001529bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001530 ConnectionType type;
1531 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001532 ConnectionManagerInterface* connection_manager =
1533 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001534 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001535 LOG(INFO) << "We could not determine our connection type. "
1536 << "Defaulting to allow updates.";
1537 return true;
1538 }
1539 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1540 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001541 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001542 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1543 return is_allowed;
1544}
1545
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001546} // namespace chromeos_update_engine