blob: 7f18cc4adb78237988199a661fde17861f9f6158 [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";
73static const char* kTagSha256 = "sha256";
David Zeuthen8f191b22013-08-06 12:27:50 -070074static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
75static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070076static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080077
Alex Deymoac41a822015-09-15 20:52:53 -070078static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000079
Alex Deymob3fa53b2016-04-18 19:57:58 -070080// updatecheck attributes (without the underscore prefix).
81static const char* kEolAttr = "eol";
82
Alex Deymoac41a822015-09-15 20:52:53 -070083namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000084
Darin Petkov1cbd78f2010-07-29 12:38:34 -070085// Returns an XML ping element attribute assignment with attribute
86// |name| and value |ping_days| if |ping_days| has a value that needs
87// to be sent, or an empty string otherwise.
88string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070089 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070090 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070091 return "";
92}
93
94// Returns an XML ping element if any of the elapsed days need to be
95// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -070096string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -070097 string ping_active = GetPingAttribute("a", ping_active_days);
98 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
99 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700100 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700101 ping_active.c_str(),
102 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700103 }
104 return "";
105}
106
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700107// Returns an XML that goes into the body of the <app> element of the Omaha
108// request based on the given parameters.
109string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700110 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700111 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700112 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700113 int ping_active_days,
114 int ping_roll_call_days,
115 PrefsInterface* prefs) {
116 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700117 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700118 if (include_ping)
119 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700120 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700121 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700122 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700123 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700124 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700125
Darin Petkov265f2902011-05-09 15:17:40 -0700126 // If this is the first update check after a reboot following a previous
127 // update, generate an event containing the previous version number. If
128 // the previous version preference file doesn't exist the event is still
129 // generated with a previous version of 0.0.0.0 -- this is relevant for
130 // older clients or new installs. The previous version event is not sent
131 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700132 // rebooted. The previous version event is also not sent if it was already
133 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700134 string prev_version;
135 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
136 prev_version = "0.0.0.0";
137 }
Alex Deymo87c08862015-10-30 21:56:55 -0700138 // We only store a non-empty previous version value after a successful
139 // update in the previous boot. After reporting it back to the server,
140 // we clear the previous version value so it doesn't get reported again.
141 if (!prev_version.empty()) {
142 app_body += base::StringPrintf(
143 " <event eventtype=\"%d\" eventresult=\"%d\" "
144 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800145 OmahaEvent::kTypeRebootedAfterUpdate,
146 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700147 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
148 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
149 << "Unable to reset the previous version.";
150 }
Darin Petkov95508da2011-01-05 12:42:29 -0800151 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700152 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800153 // The error code is an optional attribute so append it only if the result
154 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700155 string error_code;
156 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700157 error_code = base::StringPrintf(" errorcode=\"%d\"",
158 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700159 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700160 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700161 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700162 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700163 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700164
165 return app_body;
166}
167
Alex Deymo8e18f932015-03-27 16:16:59 -0700168// Returns the cohort* argument to include in the <app> tag for the passed
169// |arg_name| and |prefs_key|, if any. The return value is suitable to
170// concatenate to the list of arguments and includes a space at the end.
171string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700172 const string arg_name,
173 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700174 // There's nothing wrong with not having a given cohort setting, so we check
175 // existance first to avoid the warning log message.
176 if (!prefs->Exists(prefs_key))
177 return "";
178 string cohort_value;
179 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
180 return "";
181 // This is a sanity check to avoid sending a huge XML file back to Ohama due
182 // to a compromised stateful partition making the update check fail in low
183 // network environments envent after a reboot.
184 if (cohort_value.size() > 1024) {
185 LOG(WARNING) << "The omaha cohort setting " << arg_name
186 << " has a too big value, which must be an error or an "
187 "attacker trying to inhibit updates.";
188 return "";
189 }
190
Alex Deymob0d74eb2015-03-30 17:59:17 -0700191 string escaped_xml_value;
192 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
193 LOG(WARNING) << "The omaha cohort setting " << arg_name
194 << " is ASCII-7 invalid, ignoring it.";
195 return "";
196 }
197
Alex Deymo8e18f932015-03-27 16:16:59 -0700198 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700199 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700200}
201
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700202// Returns an XML that corresponds to the entire <app> node of the Omaha
203// request based on the given parameters.
204string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700205 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700206 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700207 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700208 int ping_active_days,
209 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800210 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700211 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700212 string app_body = GetAppBody(event, params, ping_only, include_ping,
213 ping_active_days, ping_roll_call_days,
214 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700215 string app_versions;
216
217 // If we are upgrading to a more stable channel and we are allowed to do
218 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
219 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700220 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700221 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
222 << "on downgrading to the version in the more stable channel";
223 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700224 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700225 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700226 app_versions = "version=\"" +
227 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700228 }
229
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700230 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700231 string app_channels =
232 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
233 if (params->current_channel() != download_channel) {
234 app_channels += "from_track=\"" + XmlEncodeWithDefault(
235 params->current_channel(), "") + "\" ";
236 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700237
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700238 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700239
David Zeuthen639aa362014-02-03 16:23:44 -0800240 // If install_date_days is not set (e.g. its value is -1 ), don't
241 // include the attribute.
242 string install_date_in_days_str = "";
243 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700244 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
245 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800246 }
247
Alex Deymo8e18f932015-03-27 16:16:59 -0700248 string app_cohort_args;
249 app_cohort_args += GetCohortArgXml(system_state->prefs(),
250 "cohort", kPrefsOmahaCohort);
251 app_cohort_args += GetCohortArgXml(system_state->prefs(),
252 "cohorthint", kPrefsOmahaCohortHint);
253 app_cohort_args += GetCohortArgXml(system_state->prefs(),
254 "cohortname", kPrefsOmahaCohortName);
255
Alex Deymob0d74eb2015-03-30 17:59:17 -0700256 string app_xml = " <app "
257 "appid=\"" + XmlEncodeWithDefault(params->GetAppId(), "") + "\" " +
258 app_cohort_args +
259 app_versions +
260 app_channels +
261 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
262 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
263 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
264 "delta_okay=\"" + delta_okay_str + "\" "
265 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
266 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
267 install_date_in_days_str +
268 ">\n" +
269 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700270 " </app>\n";
271
272 return app_xml;
273}
274
275// Returns an XML that corresponds to the entire <os> node of the Omaha
276// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700277string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700278 string os_xml =" <os "
279 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
280 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
281 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
282 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700283 return os_xml;
284}
285
286// Returns an XML that corresponds to the entire Omaha request based on the
287// given parameters.
288string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700289 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700290 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700291 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700292 int ping_active_days,
293 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800294 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700295 SystemState* system_state) {
296 string os_xml = GetOsXml(params);
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700297 string app_xml = GetAppXml(event, params, ping_only, include_ping,
298 ping_active_days, ping_roll_call_days,
299 install_date_in_days, system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700300
Alex Vakulenko75039d72014-03-25 12:36:28 -0700301 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700302 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700303
Alex Deymoac41a822015-09-15 20:52:53 -0700304 string updater_version = XmlEncodeWithDefault(
305 base::StringPrintf("%s-%s",
306 constants::kOmahaUpdaterID,
307 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700308 string request_xml =
309 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700310 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700311 "version=\"" + updater_version + "\" "
312 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700313 install_source +
314 "ismachine=\"1\">\n") +
315 os_xml +
316 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700317 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700318
319 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000320}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700321
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700322} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000323
David Zeuthene8ed8632014-07-24 13:38:10 -0400324// Struct used for holding data obtained when parsing the XML.
325struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400326 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
327
328 // Pointer to the expat XML_Parser object.
329 XML_Parser xml_parser;
330
David Zeuthene8ed8632014-07-24 13:38:10 -0400331 // This is the state of the parser as it's processing the XML.
332 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400333 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400334 string current_path;
335
336 // These are the values extracted from the XML.
Alex Deymo8e18f932015-03-27 16:16:59 -0700337 string app_cohort;
338 string app_cohorthint;
339 string app_cohortname;
340 bool app_cohort_set = false;
341 bool app_cohorthint_set = false;
342 bool app_cohortname_set = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400343 string updatecheck_status;
344 string updatecheck_poll_interval;
Alex Deymob3fa53b2016-04-18 19:57:58 -0700345 map<string, string> updatecheck_attrs;
David Zeuthene8ed8632014-07-24 13:38:10 -0400346 string daystart_elapsed_days;
347 string daystart_elapsed_seconds;
348 vector<string> url_codebase;
349 string package_name;
350 string package_size;
351 string manifest_version;
352 map<string, string> action_postinstall_attrs;
353};
354
355namespace {
356
357// Callback function invoked by expat.
358void ParserHandlerStart(void* user_data, const XML_Char* element,
359 const XML_Char** attr) {
360 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
361
362 if (data->failed)
363 return;
364
365 data->current_path += string("/") + element;
366
367 map<string, string> attrs;
368 if (attr != nullptr) {
369 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
370 string key = attr[n];
371 string value = attr[n + 1];
372 attrs[key] = value;
373 }
374 }
375
Alex Deymo8e18f932015-03-27 16:16:59 -0700376 if (data->current_path == "/response/app") {
377 if (attrs.find("cohort") != attrs.end()) {
378 data->app_cohort_set = true;
379 data->app_cohort = attrs["cohort"];
380 }
381 if (attrs.find("cohorthint") != attrs.end()) {
382 data->app_cohorthint_set = true;
383 data->app_cohorthint = attrs["cohorthint"];
384 }
385 if (attrs.find("cohortname") != attrs.end()) {
386 data->app_cohortname_set = true;
387 data->app_cohortname = attrs["cohortname"];
388 }
389 } else if (data->current_path == "/response/app/updatecheck") {
David Zeuthene8ed8632014-07-24 13:38:10 -0400390 // There is only supposed to be a single <updatecheck> element.
391 data->updatecheck_status = attrs["status"];
392 data->updatecheck_poll_interval = attrs["PollInterval"];
Alex Deymob3fa53b2016-04-18 19:57:58 -0700393 // Omaha sends arbitrary key-value pairs as extra attributes starting with
394 // an underscore.
395 for (const auto& attr : attrs) {
396 if (!attr.first.empty() && attr.first[0] == '_')
397 data->updatecheck_attrs[attr.first.substr(1)] = attr.second;
398 }
David Zeuthene8ed8632014-07-24 13:38:10 -0400399 } else if (data->current_path == "/response/daystart") {
400 // Get the install-date.
401 data->daystart_elapsed_days = attrs["elapsed_days"];
402 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
403 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
404 // Look at all <url> elements.
405 data->url_codebase.push_back(attrs["codebase"]);
406 } else if (data->package_name.empty() && data->current_path ==
407 "/response/app/updatecheck/manifest/packages/package") {
408 // Only look at the first <package>.
409 data->package_name = attrs["name"];
410 data->package_size = attrs["size"];
411 } else if (data->current_path == "/response/app/updatecheck/manifest") {
412 // Get the version.
413 data->manifest_version = attrs[kTagVersion];
414 } else if (data->current_path ==
415 "/response/app/updatecheck/manifest/actions/action") {
416 // We only care about the postinstall action.
417 if (attrs["event"] == "postinstall") {
418 data->action_postinstall_attrs = attrs;
419 }
420 }
421}
422
423// Callback function invoked by expat.
424void ParserHandlerEnd(void* user_data, const XML_Char* element) {
425 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
426 if (data->failed)
427 return;
428
429 const string path_suffix = string("/") + element;
430
Alex Vakulenko0103c362016-01-20 07:56:15 -0800431 if (!base::EndsWith(data->current_path, path_suffix,
432 base::CompareCase::SENSITIVE)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400433 LOG(ERROR) << "Unexpected end element '" << element
434 << "' with current_path='" << data->current_path << "'";
435 data->failed = true;
436 return;
437 }
438 data->current_path.resize(data->current_path.size() - path_suffix.size());
439}
440
David Zeuthenf3e28012014-08-26 18:23:52 -0400441// Callback function invoked by expat.
442//
443// This is called for entity declarations. Since Omaha is guaranteed
444// to never return any XML with entities our course of action is to
445// just stop parsing. This avoids potential resource exhaustion
446// problems AKA the "billion laughs". CVE-2013-0340.
447void ParserHandlerEntityDecl(void *user_data,
448 const XML_Char *entity_name,
449 int is_parameter_entity,
450 const XML_Char *value,
451 int value_length,
452 const XML_Char *base,
453 const XML_Char *system_id,
454 const XML_Char *public_id,
455 const XML_Char *notation_name) {
456 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
457
458 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
459 data->failed = true;
460 data->entity_decl = true;
461 XML_StopParser(data->xml_parser, false);
462}
463
David Zeuthene8ed8632014-07-24 13:38:10 -0400464} // namespace
465
Alex Deymob0d74eb2015-03-30 17:59:17 -0700466bool XmlEncode(const string& input, string* output) {
467 if (std::find_if(input.begin(), input.end(),
468 [](const char c){return c & 0x80;}) != input.end()) {
469 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
470 utils::HexDumpString(input);
471 return false;
472 }
Alex Deymocc457852015-06-18 18:35:50 -0700473 output->clear();
474 // We need at least input.size() space in the output, but the code below will
475 // handle it if we need more.
476 output->reserve(input.size());
477 for (char c : input) {
478 switch (c) {
479 case '\"':
480 output->append("&quot;");
481 break;
482 case '\'':
483 output->append("&apos;");
484 break;
485 case '&':
486 output->append("&amp;");
487 break;
488 case '<':
489 output->append("&lt;");
490 break;
491 case '>':
492 output->append("&gt;");
493 break;
494 default:
495 output->push_back(c);
496 }
497 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700498 return true;
499}
500
501string XmlEncodeWithDefault(const string& input, const string& default_value) {
502 string output;
503 if (XmlEncode(input, &output))
504 return output;
505 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000506}
507
Alex Deymoc1c17b42015-11-23 03:53:15 -0300508OmahaRequestAction::OmahaRequestAction(
509 SystemState* system_state,
510 OmahaEvent* event,
511 std::unique_ptr<HttpFetcher> http_fetcher,
512 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800513 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700514 event_(event),
Alex Deymoc1c17b42015-11-23 03:53:15 -0300515 http_fetcher_(std::move(http_fetcher)),
Thieu Le116fda32011-04-19 11:01:54 -0700516 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700517 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700518 ping_roll_call_days_(0) {
519 params_ = system_state->request_params();
520}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000521
Darin Petkov6a5b3222010-07-13 14:55:28 -0700522OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000523
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700524// Calculates the value to use for the ping days parameter.
525int OmahaRequestAction::CalculatePingDays(const string& key) {
526 int days = kNeverPinged;
527 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800528 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700529 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
530 if (days < 0) {
531 // If |days| is negative, then the system clock must have jumped
532 // back in time since the ping was sent. Mark the value so that
533 // it doesn't get sent to the server but we still update the
534 // last ping daystart preference. This way the next ping time
535 // will be correct, hopefully.
536 days = kPingTimeJump;
537 LOG(WARNING) <<
538 "System clock jumped back in time. Resetting ping daystarts.";
539 }
540 }
541 return days;
542}
543
544void OmahaRequestAction::InitPingDays() {
545 // We send pings only along with update checks, not with events.
546 if (IsEvent()) {
547 return;
548 }
549 // TODO(petkov): Figure a way to distinguish active use pings
550 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700551 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700552 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
553 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
554}
555
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700556bool OmahaRequestAction::ShouldPing() const {
557 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
558 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
559 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
560 if (powerwash_count > 0) {
561 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
562 << "powerwash_count is " << powerwash_count;
563 return false;
564 }
565 return true;
566 }
567 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
568}
569
David Zeuthen639aa362014-02-03 16:23:44 -0800570// static
571int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
572 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700573 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800574 return -1;
575
576 // If we have the value stored on disk, just return it.
577 int64_t stored_value;
578 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
579 // Convert and sanity-check.
580 int install_date_days = static_cast<int>(stored_value);
581 if (install_date_days >= 0)
582 return install_date_days;
583 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
584 << install_date_days << " looks suspicious.";
585 prefs->Delete(kPrefsInstallDateDays);
586 }
587
588 // Otherwise, if OOBE is not complete then do nothing and wait for
589 // ParseResponse() to call ParseInstallDate() and then
590 // PersistInstallDate() to set the kPrefsInstallDateDays state
591 // variable. Once that is done, we'll then report back in future
592 // Omaha requests. This works exactly because OOBE triggers an
593 // update check.
594 //
595 // However, if OOBE is complete and the kPrefsInstallDateDays state
596 // variable is not set, there are two possibilities
597 //
598 // 1. The update check in OOBE failed so we never got a response
599 // from Omaha (no network etc.); or
600 //
601 // 2. OOBE was done on an older version that didn't write to the
602 // kPrefsInstallDateDays state variable.
603 //
604 // In both cases, we approximate the install date by simply
605 // inspecting the timestamp of when OOBE happened.
606
607 Time time_of_oobe;
Alex Deymo46a9aae2016-05-04 20:20:11 -0700608 if (!system_state->hardware()->IsOOBEEnabled() ||
609 !system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800610 LOG(INFO) << "Not generating Omaha InstallData as we have "
Alex Deymo46a9aae2016-05-04 20:20:11 -0700611 << "no prefs file and OOBE is not complete or not enabled.";
David Zeuthen639aa362014-02-03 16:23:44 -0800612 return -1;
613 }
614
615 int num_days;
616 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
617 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
618 << "as its value '" << utils::ToString(time_of_oobe)
619 << "' looks suspicious.";
620 return -1;
621 }
622
623 // Persist this to disk, for future use.
624 if (!OmahaRequestAction::PersistInstallDate(system_state,
625 num_days,
626 kProvisionedFromOOBEMarker))
627 return -1;
628
629 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
630 << num_days << " days";
631
632 return num_days;
633}
634
Darin Petkov6a5b3222010-07-13 14:55:28 -0700635void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000636 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700637 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700638 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700639 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700640 return;
641 }
David Zeuthen639aa362014-02-03 16:23:44 -0800642
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700643 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700644 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700645 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700646 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700647 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800648 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800649 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700650 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700651
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800652 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
653 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700654 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700655 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700656 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000657}
658
Darin Petkov6a5b3222010-07-13 14:55:28 -0700659void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000660 http_fetcher_->TerminateTransfer();
661}
662
663// We just store the response in the buffer. Once we've received all bytes,
664// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700665void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800666 const void* bytes,
667 size_t length) {
668 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
669 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000670}
671
672namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000673
674// Parses a 64 bit base-10 int from a string and returns it. Returns 0
675// on error. If the string contains "0", that's indistinguishable from
676// error.
677off_t ParseInt(const string& str) {
678 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700679 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000680 if (rc < 1) {
681 // failure
682 return 0;
683 }
684 return ret;
685}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700686
David Zeuthene8ed8632014-07-24 13:38:10 -0400687// Parses |str| and returns |true| if, and only if, its value is "true".
688bool ParseBool(const string& str) {
689 return str == "true";
690}
691
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700692// Update the last ping day preferences based on the server daystart
693// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400694bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700695 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400696 TEST_AND_RETURN_FALSE(
697 base::StringToInt64(parser_data->daystart_elapsed_seconds,
698 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700699 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
700
701 // Remember the local time that matches the server's last midnight
702 // time.
703 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
704 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
705 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
706 return true;
707}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700708} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000709
David Zeuthene8ed8632014-07-24 13:38:10 -0400710bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700711 OmahaResponse* output_object,
712 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400713 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700714 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700715 return false;
716 }
717
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800718 // chromium-os:37289: The PollInterval is not supported by Omaha server
719 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700720 // slow down the request rate from the server-side. Note that the PollInterval
721 // is not persisted, so it has to be sent by the server on every response to
722 // guarantee that the scheduler uses this value (otherwise, if the device got
723 // rebooted after the last server-indicated value, it'll revert to the default
724 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
725 // based on the assumption that we perform an update check every hour so that
726 // the max value of 8 will roughly be equivalent to one work day. If we decide
727 // to use PollInterval permanently, we should update the
728 // max_update_checks_allowed to take PollInterval into account. Note: The
729 // parsing for PollInterval happens even before parsing of the status because
730 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400731 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700732 &output_object->poll_interval);
733
David Zeuthen639aa362014-02-03 16:23:44 -0800734 // Check for the "elapsed_days" attribute in the "daystart"
735 // element. This is the number of days since Jan 1 2007, 0:00
736 // PST. If we don't have a persisted value of the Omaha InstallDate,
737 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400738 if (ParseInstallDate(parser_data, output_object) &&
739 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800740 // Since output_object->install_date_days is never negative, the
741 // elapsed_days -> install-date calculation is reduced to simply
742 // rounding down to the nearest number divisible by 7.
743 int remainder = output_object->install_date_days % 7;
744 int install_date_days_rounded =
745 output_object->install_date_days - remainder;
746 if (PersistInstallDate(system_state_,
747 install_date_days_rounded,
748 kProvisionedFromOmahaResponse)) {
749 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
750 << install_date_days_rounded << " days";
751 }
752 }
753
Alex Deymo00d79ac2015-06-29 15:41:49 -0700754 // We persist the cohorts sent by omaha even if the status is "noupdate".
755 if (parser_data->app_cohort_set)
756 PersistCohortData(kPrefsOmahaCohort, parser_data->app_cohort);
757 if (parser_data->app_cohorthint_set)
758 PersistCohortData(kPrefsOmahaCohortHint, parser_data->app_cohorthint);
759 if (parser_data->app_cohortname_set)
760 PersistCohortData(kPrefsOmahaCohortName, parser_data->app_cohortname);
761
Alex Deymob3fa53b2016-04-18 19:57:58 -0700762 // Parse the updatecheck attributes.
763 PersistEolStatus(parser_data->updatecheck_attrs);
764
David Zeuthene8ed8632014-07-24 13:38:10 -0400765 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700766 return false;
767
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800768 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
769 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400770 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700771 return false;
772
David Zeuthene8ed8632014-07-24 13:38:10 -0400773 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700774 return false;
775
David Zeuthene8ed8632014-07-24 13:38:10 -0400776 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700777 return false;
778
779 return true;
780}
781
David Zeuthene8ed8632014-07-24 13:38:10 -0400782bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700783 OmahaResponse* output_object,
784 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400785 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700786 if (status == "noupdate") {
787 LOG(INFO) << "No update.";
788 output_object->update_exists = false;
789 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700790 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700791 return false;
792 }
793
794 if (status != "ok") {
795 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700796 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700797 return false;
798 }
799
800 return true;
801}
802
David Zeuthene8ed8632014-07-24 13:38:10 -0400803bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700804 OmahaResponse* output_object,
805 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400806 if (parser_data->url_codebase.empty()) {
807 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700808 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700809 return false;
810 }
811
David Zeuthene8ed8632014-07-24 13:38:10 -0400812 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800813 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400814 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800815 if (codebase.empty()) {
816 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700817 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800818 return false;
819 }
820 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700821 }
822
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700823 return true;
824}
825
David Zeuthene8ed8632014-07-24 13:38:10 -0400826bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700827 OmahaResponse* output_object,
828 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400829 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700830 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700831 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700832 return false;
833 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800834
835 // Append the package name to each URL in our list so that we don't
836 // propagate the urlBase vs packageName distinctions beyond this point.
837 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400838 for (auto& payload_url : output_object->payload_urls)
839 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700840
841 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400842 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700843 if (size <= 0) {
844 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700845 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700846 return false;
847 }
848 output_object->size = size;
849
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800850 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700851
852 return true;
853}
854
David Zeuthene8ed8632014-07-24 13:38:10 -0400855bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700856 OmahaResponse* output_object,
857 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400858 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700859 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700860 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700861 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700862 return false;
863 }
864
865 LOG(INFO) << "Received omaha response to update to version "
866 << output_object->version;
867
David Zeuthene8ed8632014-07-24 13:38:10 -0400868 map<string, string> attrs = parser_data->action_postinstall_attrs;
869 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700870 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700871 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700872 return false;
873 }
874
David Zeuthene8ed8632014-07-24 13:38:10 -0400875 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700876 if (output_object->hash.empty()) {
877 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700878 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700879 return false;
880 }
881
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800882 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400883 output_object->more_info_url = attrs[kTagMoreInfo];
884 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
885 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
886 output_object->prompt = ParseBool(attrs[kTagPrompt]);
887 output_object->deadline = attrs[kTagDeadline];
888 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700889 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400890 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700891 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400892 ParseBool(attrs[kTagDisableP2PForSharing]);
893 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800894
David Zeuthene8ed8632014-07-24 13:38:10 -0400895 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800896 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800897 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700898
David Zeuthene8ed8632014-07-24 13:38:10 -0400899 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800900
901 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400902 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800903
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700904 return true;
905}
906
David Zeuthene8ed8632014-07-24 13:38:10 -0400907// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000908// and fill in the appropriate fields of the output object. Also, notifies
909// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700910void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
911 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000912 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800913 string current_response(response_buffer_.begin(), response_buffer_.end());
914 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700915
Gilad Arnold74b5f552014-10-07 08:17:16 -0700916 PayloadStateInterface* const payload_state = system_state_->payload_state();
917
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700918 // Events are best effort transactions -- assume they always succeed.
919 if (IsEvent()) {
920 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700921 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700922 return;
923 }
924
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700925 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700926 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700927 int code = GetHTTPResponseCode();
928 // Makes sure we send sane error values.
929 if (code < 0 || code >= 1000) {
930 code = 999;
931 }
David Zeuthena99981f2013-04-29 13:42:47 -0700932 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700933 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000934 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700935 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000936
David Zeuthene8ed8632014-07-24 13:38:10 -0400937 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400938 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400939 XML_SetUserData(parser, &parser_data);
940 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400941 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800942 XML_Status res = XML_Parse(
943 parser,
944 reinterpret_cast<const char*>(response_buffer_.data()),
945 response_buffer_.size(),
946 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400947 XML_ParserFree(parser);
948
949 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700950 LOG(ERROR) << "Omaha response not valid XML: "
951 << XML_ErrorString(XML_GetErrorCode(parser))
952 << " at line " << XML_GetCurrentLineNumber(parser)
953 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400954 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
955 if (response_buffer_.empty()) {
956 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
957 } else if (parser_data.entity_decl) {
958 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
959 }
960 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000961 return;
962 }
963
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700964 // Update the last ping day preferences based on the server daystart response
965 // even if we didn't send a ping. Omaha always includes the daystart in the
966 // response, but log the error if it didn't.
967 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
968 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700969
Thieu Le116fda32011-04-19 11:01:54 -0700970 if (!HasOutputPipe()) {
971 // Just set success to whether or not the http transfer succeeded,
972 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700973 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700974 return;
975 }
976
Darin Petkov6a5b3222010-07-13 14:55:28 -0700977 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400978 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000979 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700980 output_object.update_exists = true;
981 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000982
Chris Sosa77f79e82014-06-02 18:16:24 -0700983 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700984 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700985 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700986 return;
987 }
988
David Zeuthen8f191b22013-08-06 12:27:50 -0700989 // If Omaha says to disable p2p, respect that
990 if (output_object.disable_p2p_for_downloading) {
991 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
992 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700993 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700994 }
995 if (output_object.disable_p2p_for_sharing) {
996 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
997 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700998 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700999 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001000
1001 // Update the payload state with the current response. The payload state
1002 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001003 // from what's stored already. We are updating the payload state as late
1004 // as possible in this method so that if a new release gets pushed and then
1005 // got pulled back due to some issues, we don't want to clear our internal
1006 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001007 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001008
David Zeuthen8f191b22013-08-06 12:27:50 -07001009 // It could be we've already exceeded the deadline for when p2p is
1010 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001011 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001012 payload_state->P2PNewAttempt();
1013 if (!payload_state->P2PAttemptAllowed()) {
1014 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1015 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001016 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001017 }
1018 }
1019
1020 // From here on, we'll complete stuff in CompleteProcessing() so
1021 // disable |completer| since we'll create a new one in that
1022 // function.
1023 completer.set_should_complete(false);
1024
1025 // If we're allowed to use p2p for downloading we do not pay
1026 // attention to wall-clock-based waiting if the URL is indeed
1027 // available via p2p. Therefore, check if the file is available via
1028 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001029 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001030 LookupPayloadViaP2P(output_object);
1031 } else {
1032 CompleteProcessing();
1033 }
1034}
1035
1036void OmahaRequestAction::CompleteProcessing() {
1037 ScopedActionCompleter completer(processor_, this);
1038 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1039 PayloadStateInterface* payload_state = system_state_->payload_state();
1040
Alex Deymo46a9aae2016-05-04 20:20:11 -07001041 if (system_state_->hardware()->IsOOBEEnabled() &&
1042 !system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001043 output_object.deadline.empty() &&
1044 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001045 output_object.update_exists = false;
1046 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1047 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1048 return;
1049 }
1050
David Zeuthen8f191b22013-08-06 12:27:50 -07001051 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001052 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001053 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001054 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001055 return;
1056 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001057
Chris Sosa20f005c2013-09-05 13:53:08 -07001058 if (payload_state->ShouldBackoffDownload()) {
1059 output_object.update_exists = false;
1060 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1061 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001062 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001063 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001064 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001065 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001066}
1067
1068void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1069 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1070 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001071 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001072 } else {
1073 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1074 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001075 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001076 }
1077 CompleteProcessing();
1078}
1079
1080void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001081 // If the device is in the middle of an update, the state variables
1082 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1083 // tracks the offset and length of the operation currently in
1084 // progress. The offset is based from the end of the manifest which
1085 // is kPrefsManifestMetadataSize bytes long.
1086 //
1087 // To make forward progress and avoid deadlocks, we need to find a
1088 // peer that has at least the entire operation we're currently
1089 // working on. Otherwise we may end up in a situation where two
1090 // devices bounce back and forth downloading from each other,
1091 // neither making any forward progress until one of them decides to
1092 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1093 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001094 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001095 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001096 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001097 int64_t next_data_offset = 0;
1098 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001099 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001100 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1101 &manifest_metadata_size) &&
1102 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001103 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1104 &manifest_signature_size) &&
1105 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001106 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001107 &next_data_offset) &&
1108 next_data_offset != -1 &&
1109 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1110 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001111 minimum_size = manifest_metadata_size + manifest_signature_size +
1112 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001113 }
1114
1115 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001116 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001117 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1118 << file_id << " minimum_size=" << minimum_size;
1119 system_state_->p2p_manager()->LookupUrlForFile(
1120 file_id,
1121 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001122 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001123 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1124 base::Unretained(this)));
1125 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001126}
1127
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001128bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001129 if (params_->interactive()) {
1130 LOG(INFO) << "Not deferring download because update is interactive.";
1131 return false;
1132 }
1133
David Zeuthen8f191b22013-08-06 12:27:50 -07001134 // If we're using p2p to download _and_ we have a p2p URL, we never
1135 // defer the download. This is because the download will always
1136 // happen from a peer on the LAN and we've been waiting in line for
1137 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001138 const PayloadStateInterface* payload_state = system_state_->payload_state();
1139 if (payload_state->GetUsingP2PForDownloading() &&
1140 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001141 LOG(INFO) << "Download not deferred because download "
1142 << "will happen from a local peer (via p2p).";
1143 return false;
1144 }
1145
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001146 // We should defer the downloads only if we've first satisfied the
1147 // wall-clock-based-waiting period and then the update-check-based waiting
1148 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001149 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001150 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1151 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001152 return false;
1153 }
1154
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001155 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001156 case kWallClockWaitNotSatisfied:
1157 // We haven't even satisfied the first condition, passing the
1158 // wall-clock-based waiting period, so we should defer the downloads
1159 // until that happens.
1160 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1161 return true;
1162
1163 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1164 LOG(INFO) << "wall-clock-based-wait satisfied and "
1165 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001166 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001167
1168 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1169 // Wall-clock-based waiting period is satisfied, and it's determined
1170 // that we do not need the update-check-based wait. so no need to
1171 // defer downloads.
1172 LOG(INFO) << "wall-clock-based-wait satisfied and "
1173 << "update-check-based-wait is not required.";
1174 return false;
1175
1176 default:
1177 // Returning false for this default case so we err on the
1178 // side of downloading updates than deferring in case of any bugs.
1179 NOTREACHED();
1180 return false;
1181 }
1182}
1183
1184OmahaRequestAction::WallClockWaitResult
1185OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001186 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001187 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001188 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001189
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001190 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1191 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1192 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001193 // Note: This timestamp could be that of ANY update we saw in the past
1194 // (not necessarily this particular update we're considering to apply)
1195 // but never got to apply because of some reason (e.g. stop AU policy,
1196 // updates being pulled out from Omaha, changes in target version prefix,
1197 // new update being rolled out, etc.). But for the purposes of scattering
1198 // it doesn't matter which update the timestamp corresponds to. i.e.
1199 // the clock starts ticking the first time we see an update and we're
1200 // ready to apply when the random wait period is satisfied relative to
1201 // that first seen timestamp.
1202 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1203 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1204 << utils::ToString(update_first_seen_at);
1205 } else {
1206 // This seems like an unexpected error where the persisted value exists
1207 // but it's not readable for some reason. Just skip scattering in this
1208 // case to be safe.
1209 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1210 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1211 }
1212 } else {
1213 update_first_seen_at = Time::Now();
1214 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001215 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1216 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001217 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1218 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001219 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001220 // This seems like an unexpected error where the value cannot be
1221 // persisted for some reason. Just skip scattering in this
1222 // case to be safe.
1223 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1224 << utils::ToString(update_first_seen_at)
1225 << " cannot be persisted";
1226 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1227 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001228 }
1229
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001230 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001231 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001232 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001233
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001234 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001235 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001236 << ", Time Elapsed = "
1237 << utils::FormatSecs(elapsed_time.InSeconds())
1238 << ", MaxDaysToScatter = "
1239 << max_scatter_period.InDays();
1240
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001241 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001242 // The deadline is set for all rules which serve a delta update from a
1243 // previous FSI, which means this update will be applied mostly in OOBE
1244 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1245 // quickly.
1246 LOG(INFO) << "Not scattering as deadline flag is set";
1247 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1248 }
1249
1250 if (max_scatter_period.InDays() == 0) {
1251 // This means the Omaha rule creator decides that this rule
1252 // should not be scattered irrespective of the policy.
1253 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1254 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1255 }
1256
1257 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001258 // This means we've waited more than the upperbound wait in the rule
1259 // from the time we first saw a valid update available to us.
1260 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001261 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1262 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1263 }
1264
1265 // This means we are required to participate in scattering.
1266 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001267 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001268 if (remaining_wait_time.InSeconds() <= 0) {
1269 // Yes, it's our turn now.
1270 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1271
1272 // But we can't download until the update-check-count-based wait is also
1273 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001274 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001275 kWallClockWaitDoneButUpdateCheckWaitRequired :
1276 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1277 }
1278
1279 // Not our turn yet, so we have to wait until our turn to
1280 // help scatter the downloads across all clients of the enterprise.
1281 LOG(INFO) << "Update deferred for another "
1282 << utils::FormatSecs(remaining_wait_time.InSeconds())
1283 << " per policy.";
1284 return kWallClockWaitNotSatisfied;
1285}
1286
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001287bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001288 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001289
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001290 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1291 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1292 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001293 // We are unable to read the update check count from file for some reason.
1294 // So let's proceed anyway so as to not stall the update.
1295 LOG(ERROR) << "Unable to read update check count. "
1296 << "Skipping update-check-count-based-wait.";
1297 return true;
1298 }
1299 } else {
1300 // This file does not exist. This means we haven't started our update
1301 // check count down yet, so this is the right time to start the count down.
1302 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001303 params_->min_update_checks_needed(),
1304 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001305
1306 LOG(INFO) << "Randomly picked update check count value = "
1307 << update_check_count_value;
1308
1309 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001310 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1311 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001312 // We weren't able to write the update check count file for some reason.
1313 // So let's proceed anyway so as to not stall the update.
1314 LOG(ERROR) << "Unable to write update check count. "
1315 << "Skipping update-check-count-based-wait.";
1316 return true;
1317 }
1318 }
1319
1320 if (update_check_count_value == 0) {
1321 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1322 return true;
1323 }
1324
1325 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001326 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001327 // We err on the side of skipping scattering logic instead of stalling
1328 // a machine from receiving any updates in case of any unexpected state.
1329 LOG(ERROR) << "Invalid value for update check count detected. "
1330 << "Skipping update-check-count-based-wait.";
1331 return true;
1332 }
1333
1334 // Legal value, we need to wait for more update checks to happen
1335 // until this becomes 0.
1336 LOG(INFO) << "Deferring Omaha updates for another "
1337 << update_check_count_value
1338 << " update checks per policy";
1339 return false;
1340}
1341
David Zeuthen639aa362014-02-03 16:23:44 -08001342// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001343bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001344 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001345 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001346 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001347 &elapsed_days))
1348 return false;
1349
1350 if (elapsed_days < 0)
1351 return false;
1352
1353 output_object->install_date_days = elapsed_days;
1354 return true;
1355}
1356
1357// static
1358bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1359 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001360 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001361 return false;
1362
1363 return prefs->Exists(kPrefsInstallDateDays);
1364}
1365
1366// static
1367bool OmahaRequestAction::PersistInstallDate(
1368 SystemState *system_state,
1369 int install_date_days,
1370 InstallDateProvisioningSource source) {
1371 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1372
1373 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001374 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001375 return false;
1376
1377 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1378 return false;
1379
Alex Deymoaf9a8632015-09-23 18:51:48 -07001380 string metric_name = metrics::kMetricInstallDateProvisioningSource;
David Zeuthen33bae492014-02-25 16:16:18 -08001381 system_state->metrics_lib()->SendEnumToUMA(
1382 metric_name,
1383 static_cast<int>(source), // Sample.
1384 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001385
1386 return true;
1387}
1388
Alex Deymo8e18f932015-03-27 16:16:59 -07001389bool OmahaRequestAction::PersistCohortData(
1390 const string& prefs_key,
1391 const string& new_value) {
1392 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1393 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1394 return system_state_->prefs()->Delete(prefs_key);
1395 } else if (!new_value.empty()) {
1396 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1397 return system_state_->prefs()->SetString(prefs_key, new_value);
1398 }
1399 return true;
1400}
1401
Alex Deymob3fa53b2016-04-18 19:57:58 -07001402bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1403 auto eol_attr = attrs.find(kEolAttr);
1404 if (eol_attr != attrs.end()) {
1405 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1406 eol_attr->second);
1407 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1408 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1409 }
1410 return true;
1411}
1412
David Zeuthen33bae492014-02-25 16:16:18 -08001413void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1414 // We only want to report this on "update check".
1415 if (ping_only_ || event_ != nullptr)
1416 return;
1417
1418 metrics::CheckResult result = metrics::CheckResult::kUnset;
1419 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1420 metrics::DownloadErrorCode download_error_code =
1421 metrics::DownloadErrorCode::kUnset;
1422
1423 // Regular update attempt.
1424 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001425 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001426 // OK, we parsed the response successfully but that does
1427 // necessarily mean that an update is available.
1428 if (HasOutputPipe()) {
1429 const OmahaResponse& response = GetOutputObject();
1430 if (response.update_exists) {
1431 result = metrics::CheckResult::kUpdateAvailable;
1432 reaction = metrics::CheckReaction::kUpdating;
1433 } else {
1434 result = metrics::CheckResult::kNoUpdateAvailable;
1435 }
1436 } else {
1437 result = metrics::CheckResult::kNoUpdateAvailable;
1438 }
1439 break;
1440
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001441 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001442 result = metrics::CheckResult::kUpdateAvailable;
1443 reaction = metrics::CheckReaction::kIgnored;
1444 break;
1445
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001446 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001447 result = metrics::CheckResult::kUpdateAvailable;
1448 reaction = metrics::CheckReaction::kDeferring;
1449 break;
1450
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001451 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001452 result = metrics::CheckResult::kUpdateAvailable;
1453 reaction = metrics::CheckReaction::kBackingOff;
1454 break;
1455
1456 default:
1457 // We report two flavors of errors, "Download errors" and "Parsing
1458 // error". Try to convert to the former and if that doesn't work
1459 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001460 metrics::DownloadErrorCode tmp_error =
1461 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001462 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1463 result = metrics::CheckResult::kDownloadError;
1464 download_error_code = tmp_error;
1465 } else {
1466 result = metrics::CheckResult::kParsingError;
1467 }
1468 break;
1469 }
1470
1471 metrics::ReportUpdateCheckMetrics(system_state_,
1472 result, reaction, download_error_code);
1473}
1474
Chris Sosa77f79e82014-06-02 18:16:24 -07001475bool OmahaRequestAction::ShouldIgnoreUpdate(
1476 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001477 // Note: policy decision to not update to a version we rolled back from.
1478 string rollback_version =
1479 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001480 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001481 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001482 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001483 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1484 return true;
1485 }
1486 }
1487
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001488 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001489 LOG(INFO) << "Update is not allowed over current connection.";
1490 return true;
1491 }
1492
1493 // Note: We could technically delete the UpdateFirstSeenAt state when we
1494 // return true. If we do, it'll mean a device has to restart the
1495 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1496 // turned on again. On the other hand, it also increases the chance of update
1497 // starvation if an admin turns AU on/off more frequently. We choose to err on
1498 // the side of preventing starvation at the cost of not applying scattering in
1499 // those cases.
1500 return false;
1501}
1502
1503bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
Sen Jiang255e22b2016-05-20 16:15:29 -07001504 ConnectionType type;
1505 ConnectionTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001506 ConnectionManagerInterface* connection_manager =
1507 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001508 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001509 LOG(INFO) << "We could not determine our connection type. "
1510 << "Defaulting to allow updates.";
1511 return true;
1512 }
1513 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1514 LOG(INFO) << "We are connected via "
Sen Jiang255e22b2016-05-20 16:15:29 -07001515 << connection_utils::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001516 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1517 return is_allowed;
1518}
1519
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001520} // namespace chromeos_update_engine