blob: 16338a8c35dae1d3db4edffbef849255a9bfb072 [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"
Alex Deymof6ee0162015-07-31 12:35:22 -070043#include "update_engine/connection_manager.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 Deymobccbc382014-04-03 13:38:55 -0700608 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800609 LOG(INFO) << "Not generating Omaha InstallData as we have "
610 << "no prefs file and OOBE is not complete.";
611 return -1;
612 }
613
614 int num_days;
615 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
616 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
617 << "as its value '" << utils::ToString(time_of_oobe)
618 << "' looks suspicious.";
619 return -1;
620 }
621
622 // Persist this to disk, for future use.
623 if (!OmahaRequestAction::PersistInstallDate(system_state,
624 num_days,
625 kProvisionedFromOOBEMarker))
626 return -1;
627
628 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
629 << num_days << " days";
630
631 return num_days;
632}
633
Darin Petkov6a5b3222010-07-13 14:55:28 -0700634void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000635 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700636 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700637 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700638 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700639 return;
640 }
David Zeuthen639aa362014-02-03 16:23:44 -0800641
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700642 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700643 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700644 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700645 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700646 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800647 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800648 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700649 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700650
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800651 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
652 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700653 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700654 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700655 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000656}
657
Darin Petkov6a5b3222010-07-13 14:55:28 -0700658void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000659 http_fetcher_->TerminateTransfer();
660}
661
662// We just store the response in the buffer. Once we've received all bytes,
663// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700664void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800665 const void* bytes,
666 size_t length) {
667 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
668 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000669}
670
671namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000672
673// Parses a 64 bit base-10 int from a string and returns it. Returns 0
674// on error. If the string contains "0", that's indistinguishable from
675// error.
676off_t ParseInt(const string& str) {
677 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700678 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000679 if (rc < 1) {
680 // failure
681 return 0;
682 }
683 return ret;
684}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700685
David Zeuthene8ed8632014-07-24 13:38:10 -0400686// Parses |str| and returns |true| if, and only if, its value is "true".
687bool ParseBool(const string& str) {
688 return str == "true";
689}
690
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700691// Update the last ping day preferences based on the server daystart
692// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400693bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700694 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400695 TEST_AND_RETURN_FALSE(
696 base::StringToInt64(parser_data->daystart_elapsed_seconds,
697 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700698 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
699
700 // Remember the local time that matches the server's last midnight
701 // time.
702 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
703 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
704 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
705 return true;
706}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700707} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000708
David Zeuthene8ed8632014-07-24 13:38:10 -0400709bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700710 OmahaResponse* output_object,
711 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400712 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700713 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700714 return false;
715 }
716
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800717 // chromium-os:37289: The PollInterval is not supported by Omaha server
718 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700719 // slow down the request rate from the server-side. Note that the PollInterval
720 // is not persisted, so it has to be sent by the server on every response to
721 // guarantee that the scheduler uses this value (otherwise, if the device got
722 // rebooted after the last server-indicated value, it'll revert to the default
723 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
724 // based on the assumption that we perform an update check every hour so that
725 // the max value of 8 will roughly be equivalent to one work day. If we decide
726 // to use PollInterval permanently, we should update the
727 // max_update_checks_allowed to take PollInterval into account. Note: The
728 // parsing for PollInterval happens even before parsing of the status because
729 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400730 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700731 &output_object->poll_interval);
732
David Zeuthen639aa362014-02-03 16:23:44 -0800733 // Check for the "elapsed_days" attribute in the "daystart"
734 // element. This is the number of days since Jan 1 2007, 0:00
735 // PST. If we don't have a persisted value of the Omaha InstallDate,
736 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400737 if (ParseInstallDate(parser_data, output_object) &&
738 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800739 // Since output_object->install_date_days is never negative, the
740 // elapsed_days -> install-date calculation is reduced to simply
741 // rounding down to the nearest number divisible by 7.
742 int remainder = output_object->install_date_days % 7;
743 int install_date_days_rounded =
744 output_object->install_date_days - remainder;
745 if (PersistInstallDate(system_state_,
746 install_date_days_rounded,
747 kProvisionedFromOmahaResponse)) {
748 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
749 << install_date_days_rounded << " days";
750 }
751 }
752
Alex Deymo00d79ac2015-06-29 15:41:49 -0700753 // We persist the cohorts sent by omaha even if the status is "noupdate".
754 if (parser_data->app_cohort_set)
755 PersistCohortData(kPrefsOmahaCohort, parser_data->app_cohort);
756 if (parser_data->app_cohorthint_set)
757 PersistCohortData(kPrefsOmahaCohortHint, parser_data->app_cohorthint);
758 if (parser_data->app_cohortname_set)
759 PersistCohortData(kPrefsOmahaCohortName, parser_data->app_cohortname);
760
Alex Deymob3fa53b2016-04-18 19:57:58 -0700761 // Parse the updatecheck attributes.
762 PersistEolStatus(parser_data->updatecheck_attrs);
763
David Zeuthene8ed8632014-07-24 13:38:10 -0400764 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700765 return false;
766
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800767 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
768 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400769 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700770 return false;
771
David Zeuthene8ed8632014-07-24 13:38:10 -0400772 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700773 return false;
774
David Zeuthene8ed8632014-07-24 13:38:10 -0400775 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700776 return false;
777
778 return true;
779}
780
David Zeuthene8ed8632014-07-24 13:38:10 -0400781bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700782 OmahaResponse* output_object,
783 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400784 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700785 if (status == "noupdate") {
786 LOG(INFO) << "No update.";
787 output_object->update_exists = false;
788 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700789 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700790 return false;
791 }
792
793 if (status != "ok") {
794 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700795 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700796 return false;
797 }
798
799 return true;
800}
801
David Zeuthene8ed8632014-07-24 13:38:10 -0400802bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700803 OmahaResponse* output_object,
804 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400805 if (parser_data->url_codebase.empty()) {
806 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700807 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700808 return false;
809 }
810
David Zeuthene8ed8632014-07-24 13:38:10 -0400811 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800812 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400813 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800814 if (codebase.empty()) {
815 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700816 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800817 return false;
818 }
819 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700820 }
821
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700822 return true;
823}
824
David Zeuthene8ed8632014-07-24 13:38:10 -0400825bool OmahaRequestAction::ParsePackage(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->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700829 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700830 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700831 return false;
832 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800833
834 // Append the package name to each URL in our list so that we don't
835 // propagate the urlBase vs packageName distinctions beyond this point.
836 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400837 for (auto& payload_url : output_object->payload_urls)
838 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700839
840 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400841 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700842 if (size <= 0) {
843 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700844 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700845 return false;
846 }
847 output_object->size = size;
848
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800849 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700850
851 return true;
852}
853
David Zeuthene8ed8632014-07-24 13:38:10 -0400854bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700855 OmahaResponse* output_object,
856 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400857 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700858 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700859 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700860 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700861 return false;
862 }
863
864 LOG(INFO) << "Received omaha response to update to version "
865 << output_object->version;
866
David Zeuthene8ed8632014-07-24 13:38:10 -0400867 map<string, string> attrs = parser_data->action_postinstall_attrs;
868 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700869 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700870 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700871 return false;
872 }
873
David Zeuthene8ed8632014-07-24 13:38:10 -0400874 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700875 if (output_object->hash.empty()) {
876 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700877 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700878 return false;
879 }
880
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800881 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400882 output_object->more_info_url = attrs[kTagMoreInfo];
883 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
884 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
885 output_object->prompt = ParseBool(attrs[kTagPrompt]);
886 output_object->deadline = attrs[kTagDeadline];
887 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700888 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400889 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700890 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400891 ParseBool(attrs[kTagDisableP2PForSharing]);
892 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800893
David Zeuthene8ed8632014-07-24 13:38:10 -0400894 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800895 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800896 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700897
David Zeuthene8ed8632014-07-24 13:38:10 -0400898 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800899
900 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400901 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800902
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700903 return true;
904}
905
David Zeuthene8ed8632014-07-24 13:38:10 -0400906// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000907// and fill in the appropriate fields of the output object. Also, notifies
908// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700909void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
910 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000911 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800912 string current_response(response_buffer_.begin(), response_buffer_.end());
913 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700914
Gilad Arnold74b5f552014-10-07 08:17:16 -0700915 PayloadStateInterface* const payload_state = system_state_->payload_state();
916
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700917 // Events are best effort transactions -- assume they always succeed.
918 if (IsEvent()) {
919 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700920 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700921 return;
922 }
923
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700924 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700925 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700926 int code = GetHTTPResponseCode();
927 // Makes sure we send sane error values.
928 if (code < 0 || code >= 1000) {
929 code = 999;
930 }
David Zeuthena99981f2013-04-29 13:42:47 -0700931 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700932 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000933 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700934 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000935
David Zeuthene8ed8632014-07-24 13:38:10 -0400936 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400937 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400938 XML_SetUserData(parser, &parser_data);
939 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400940 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800941 XML_Status res = XML_Parse(
942 parser,
943 reinterpret_cast<const char*>(response_buffer_.data()),
944 response_buffer_.size(),
945 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400946 XML_ParserFree(parser);
947
948 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700949 LOG(ERROR) << "Omaha response not valid XML: "
950 << XML_ErrorString(XML_GetErrorCode(parser))
951 << " at line " << XML_GetCurrentLineNumber(parser)
952 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400953 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
954 if (response_buffer_.empty()) {
955 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
956 } else if (parser_data.entity_decl) {
957 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
958 }
959 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000960 return;
961 }
962
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700963 // Update the last ping day preferences based on the server daystart response
964 // even if we didn't send a ping. Omaha always includes the daystart in the
965 // response, but log the error if it didn't.
966 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
967 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700968
Thieu Le116fda32011-04-19 11:01:54 -0700969 if (!HasOutputPipe()) {
970 // Just set success to whether or not the http transfer succeeded,
971 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700972 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700973 return;
974 }
975
Darin Petkov6a5b3222010-07-13 14:55:28 -0700976 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400977 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000978 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700979 output_object.update_exists = true;
980 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000981
Chris Sosa77f79e82014-06-02 18:16:24 -0700982 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700983 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700984 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700985 return;
986 }
987
David Zeuthen8f191b22013-08-06 12:27:50 -0700988 // If Omaha says to disable p2p, respect that
989 if (output_object.disable_p2p_for_downloading) {
990 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
991 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700992 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700993 }
994 if (output_object.disable_p2p_for_sharing) {
995 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
996 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700997 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700998 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800999
1000 // Update the payload state with the current response. The payload state
1001 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -08001002 // from what's stored already. We are updating the payload state as late
1003 // as possible in this method so that if a new release gets pushed and then
1004 // got pulled back due to some issues, we don't want to clear our internal
1005 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001006 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -08001007
David Zeuthen8f191b22013-08-06 12:27:50 -07001008 // It could be we've already exceeded the deadline for when p2p is
1009 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001010 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001011 payload_state->P2PNewAttempt();
1012 if (!payload_state->P2PAttemptAllowed()) {
1013 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1014 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001015 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001016 }
1017 }
1018
1019 // From here on, we'll complete stuff in CompleteProcessing() so
1020 // disable |completer| since we'll create a new one in that
1021 // function.
1022 completer.set_should_complete(false);
1023
1024 // If we're allowed to use p2p for downloading we do not pay
1025 // attention to wall-clock-based waiting if the URL is indeed
1026 // available via p2p. Therefore, check if the file is available via
1027 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001028 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001029 LookupPayloadViaP2P(output_object);
1030 } else {
1031 CompleteProcessing();
1032 }
1033}
1034
1035void OmahaRequestAction::CompleteProcessing() {
1036 ScopedActionCompleter completer(processor_, this);
1037 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1038 PayloadStateInterface* payload_state = system_state_->payload_state();
1039
Kevin Cernekee2494e282016-03-29 18:03:53 -07001040 if (!system_state_->hardware()->IsOOBEComplete(nullptr) &&
Kevin Cernekeec5081a82016-04-08 12:29:52 -07001041 output_object.deadline.empty() &&
1042 params_->app_version() != "ForcedUpdate") {
Kevin Cernekee2494e282016-03-29 18:03:53 -07001043 output_object.update_exists = false;
1044 LOG(INFO) << "Ignoring non-critical Omaha updates until OOBE is done.";
1045 completer.set_code(ErrorCode::kNonCriticalUpdateInOOBE);
1046 return;
1047 }
1048
David Zeuthen8f191b22013-08-06 12:27:50 -07001049 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001050 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001051 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001052 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001053 return;
1054 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001055
Chris Sosa20f005c2013-09-05 13:53:08 -07001056 if (payload_state->ShouldBackoffDownload()) {
1057 output_object.update_exists = false;
1058 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1059 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001060 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001061 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001062 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001063 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001064}
1065
1066void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1067 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1068 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001069 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001070 } else {
1071 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1072 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001073 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001074 }
1075 CompleteProcessing();
1076}
1077
1078void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001079 // If the device is in the middle of an update, the state variables
1080 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1081 // tracks the offset and length of the operation currently in
1082 // progress. The offset is based from the end of the manifest which
1083 // is kPrefsManifestMetadataSize bytes long.
1084 //
1085 // To make forward progress and avoid deadlocks, we need to find a
1086 // peer that has at least the entire operation we're currently
1087 // working on. Otherwise we may end up in a situation where two
1088 // devices bounce back and forth downloading from each other,
1089 // neither making any forward progress until one of them decides to
1090 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1091 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001092 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001093 int64_t manifest_metadata_size = 0;
Alex Deymof25eb492016-02-26 00:20:08 -08001094 int64_t manifest_signature_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001095 int64_t next_data_offset = 0;
1096 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001097 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001098 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1099 &manifest_metadata_size) &&
1100 manifest_metadata_size != -1 &&
Alex Deymof25eb492016-02-26 00:20:08 -08001101 system_state_->prefs()->GetInt64(kPrefsManifestSignatureSize,
1102 &manifest_signature_size) &&
1103 manifest_signature_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001104 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001105 &next_data_offset) &&
1106 next_data_offset != -1 &&
1107 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1108 &next_data_length)) {
Alex Deymof25eb492016-02-26 00:20:08 -08001109 minimum_size = manifest_metadata_size + manifest_signature_size +
1110 next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001111 }
1112
1113 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001114 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001115 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1116 << file_id << " minimum_size=" << minimum_size;
1117 system_state_->p2p_manager()->LookupUrlForFile(
1118 file_id,
1119 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001120 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001121 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1122 base::Unretained(this)));
1123 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001124}
1125
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001126bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001127 if (params_->interactive()) {
1128 LOG(INFO) << "Not deferring download because update is interactive.";
1129 return false;
1130 }
1131
David Zeuthen8f191b22013-08-06 12:27:50 -07001132 // If we're using p2p to download _and_ we have a p2p URL, we never
1133 // defer the download. This is because the download will always
1134 // happen from a peer on the LAN and we've been waiting in line for
1135 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001136 const PayloadStateInterface* payload_state = system_state_->payload_state();
1137 if (payload_state->GetUsingP2PForDownloading() &&
1138 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001139 LOG(INFO) << "Download not deferred because download "
1140 << "will happen from a local peer (via p2p).";
1141 return false;
1142 }
1143
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001144 // We should defer the downloads only if we've first satisfied the
1145 // wall-clock-based-waiting period and then the update-check-based waiting
1146 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001147 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001148 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1149 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001150 return false;
1151 }
1152
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001153 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001154 case kWallClockWaitNotSatisfied:
1155 // We haven't even satisfied the first condition, passing the
1156 // wall-clock-based waiting period, so we should defer the downloads
1157 // until that happens.
1158 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1159 return true;
1160
1161 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1162 LOG(INFO) << "wall-clock-based-wait satisfied and "
1163 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001164 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001165
1166 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1167 // Wall-clock-based waiting period is satisfied, and it's determined
1168 // that we do not need the update-check-based wait. so no need to
1169 // defer downloads.
1170 LOG(INFO) << "wall-clock-based-wait satisfied and "
1171 << "update-check-based-wait is not required.";
1172 return false;
1173
1174 default:
1175 // Returning false for this default case so we err on the
1176 // side of downloading updates than deferring in case of any bugs.
1177 NOTREACHED();
1178 return false;
1179 }
1180}
1181
1182OmahaRequestAction::WallClockWaitResult
1183OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001184 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001185 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001186 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001187
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001188 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1189 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1190 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001191 // Note: This timestamp could be that of ANY update we saw in the past
1192 // (not necessarily this particular update we're considering to apply)
1193 // but never got to apply because of some reason (e.g. stop AU policy,
1194 // updates being pulled out from Omaha, changes in target version prefix,
1195 // new update being rolled out, etc.). But for the purposes of scattering
1196 // it doesn't matter which update the timestamp corresponds to. i.e.
1197 // the clock starts ticking the first time we see an update and we're
1198 // ready to apply when the random wait period is satisfied relative to
1199 // that first seen timestamp.
1200 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1201 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1202 << utils::ToString(update_first_seen_at);
1203 } else {
1204 // This seems like an unexpected error where the persisted value exists
1205 // but it's not readable for some reason. Just skip scattering in this
1206 // case to be safe.
1207 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1208 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1209 }
1210 } else {
1211 update_first_seen_at = Time::Now();
1212 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001213 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1214 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001215 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1216 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001217 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001218 // This seems like an unexpected error where the value cannot be
1219 // persisted for some reason. Just skip scattering in this
1220 // case to be safe.
1221 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1222 << utils::ToString(update_first_seen_at)
1223 << " cannot be persisted";
1224 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1225 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001226 }
1227
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001228 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001229 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001230 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001231
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001232 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001233 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001234 << ", Time Elapsed = "
1235 << utils::FormatSecs(elapsed_time.InSeconds())
1236 << ", MaxDaysToScatter = "
1237 << max_scatter_period.InDays();
1238
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001239 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001240 // The deadline is set for all rules which serve a delta update from a
1241 // previous FSI, which means this update will be applied mostly in OOBE
1242 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1243 // quickly.
1244 LOG(INFO) << "Not scattering as deadline flag is set";
1245 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1246 }
1247
1248 if (max_scatter_period.InDays() == 0) {
1249 // This means the Omaha rule creator decides that this rule
1250 // should not be scattered irrespective of the policy.
1251 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1252 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1253 }
1254
1255 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001256 // This means we've waited more than the upperbound wait in the rule
1257 // from the time we first saw a valid update available to us.
1258 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001259 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1260 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1261 }
1262
1263 // This means we are required to participate in scattering.
1264 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001265 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001266 if (remaining_wait_time.InSeconds() <= 0) {
1267 // Yes, it's our turn now.
1268 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1269
1270 // But we can't download until the update-check-count-based wait is also
1271 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001272 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001273 kWallClockWaitDoneButUpdateCheckWaitRequired :
1274 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1275 }
1276
1277 // Not our turn yet, so we have to wait until our turn to
1278 // help scatter the downloads across all clients of the enterprise.
1279 LOG(INFO) << "Update deferred for another "
1280 << utils::FormatSecs(remaining_wait_time.InSeconds())
1281 << " per policy.";
1282 return kWallClockWaitNotSatisfied;
1283}
1284
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001285bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001286 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001287
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001288 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1289 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1290 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001291 // We are unable to read the update check count from file for some reason.
1292 // So let's proceed anyway so as to not stall the update.
1293 LOG(ERROR) << "Unable to read update check count. "
1294 << "Skipping update-check-count-based-wait.";
1295 return true;
1296 }
1297 } else {
1298 // This file does not exist. This means we haven't started our update
1299 // check count down yet, so this is the right time to start the count down.
1300 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001301 params_->min_update_checks_needed(),
1302 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001303
1304 LOG(INFO) << "Randomly picked update check count value = "
1305 << update_check_count_value;
1306
1307 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001308 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1309 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001310 // We weren't able to write the update check count file for some reason.
1311 // So let's proceed anyway so as to not stall the update.
1312 LOG(ERROR) << "Unable to write update check count. "
1313 << "Skipping update-check-count-based-wait.";
1314 return true;
1315 }
1316 }
1317
1318 if (update_check_count_value == 0) {
1319 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1320 return true;
1321 }
1322
1323 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001324 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001325 // We err on the side of skipping scattering logic instead of stalling
1326 // a machine from receiving any updates in case of any unexpected state.
1327 LOG(ERROR) << "Invalid value for update check count detected. "
1328 << "Skipping update-check-count-based-wait.";
1329 return true;
1330 }
1331
1332 // Legal value, we need to wait for more update checks to happen
1333 // until this becomes 0.
1334 LOG(INFO) << "Deferring Omaha updates for another "
1335 << update_check_count_value
1336 << " update checks per policy";
1337 return false;
1338}
1339
David Zeuthen639aa362014-02-03 16:23:44 -08001340// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001341bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001342 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001343 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001344 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001345 &elapsed_days))
1346 return false;
1347
1348 if (elapsed_days < 0)
1349 return false;
1350
1351 output_object->install_date_days = elapsed_days;
1352 return true;
1353}
1354
1355// static
1356bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1357 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001358 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001359 return false;
1360
1361 return prefs->Exists(kPrefsInstallDateDays);
1362}
1363
1364// static
1365bool OmahaRequestAction::PersistInstallDate(
1366 SystemState *system_state,
1367 int install_date_days,
1368 InstallDateProvisioningSource source) {
1369 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1370
1371 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001372 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001373 return false;
1374
1375 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1376 return false;
1377
Alex Deymoaf9a8632015-09-23 18:51:48 -07001378 string metric_name = metrics::kMetricInstallDateProvisioningSource;
David Zeuthen33bae492014-02-25 16:16:18 -08001379 system_state->metrics_lib()->SendEnumToUMA(
1380 metric_name,
1381 static_cast<int>(source), // Sample.
1382 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001383
1384 return true;
1385}
1386
Alex Deymo8e18f932015-03-27 16:16:59 -07001387bool OmahaRequestAction::PersistCohortData(
1388 const string& prefs_key,
1389 const string& new_value) {
1390 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1391 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1392 return system_state_->prefs()->Delete(prefs_key);
1393 } else if (!new_value.empty()) {
1394 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1395 return system_state_->prefs()->SetString(prefs_key, new_value);
1396 }
1397 return true;
1398}
1399
Alex Deymob3fa53b2016-04-18 19:57:58 -07001400bool OmahaRequestAction::PersistEolStatus(const map<string, string>& attrs) {
1401 auto eol_attr = attrs.find(kEolAttr);
1402 if (eol_attr != attrs.end()) {
1403 return system_state_->prefs()->SetString(kPrefsOmahaEolStatus,
1404 eol_attr->second);
1405 } else if (system_state_->prefs()->Exists(kPrefsOmahaEolStatus)) {
1406 return system_state_->prefs()->Delete(kPrefsOmahaEolStatus);
1407 }
1408 return true;
1409}
1410
David Zeuthen33bae492014-02-25 16:16:18 -08001411void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1412 // We only want to report this on "update check".
1413 if (ping_only_ || event_ != nullptr)
1414 return;
1415
1416 metrics::CheckResult result = metrics::CheckResult::kUnset;
1417 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1418 metrics::DownloadErrorCode download_error_code =
1419 metrics::DownloadErrorCode::kUnset;
1420
1421 // Regular update attempt.
1422 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001423 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001424 // OK, we parsed the response successfully but that does
1425 // necessarily mean that an update is available.
1426 if (HasOutputPipe()) {
1427 const OmahaResponse& response = GetOutputObject();
1428 if (response.update_exists) {
1429 result = metrics::CheckResult::kUpdateAvailable;
1430 reaction = metrics::CheckReaction::kUpdating;
1431 } else {
1432 result = metrics::CheckResult::kNoUpdateAvailable;
1433 }
1434 } else {
1435 result = metrics::CheckResult::kNoUpdateAvailable;
1436 }
1437 break;
1438
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001439 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001440 result = metrics::CheckResult::kUpdateAvailable;
1441 reaction = metrics::CheckReaction::kIgnored;
1442 break;
1443
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001444 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001445 result = metrics::CheckResult::kUpdateAvailable;
1446 reaction = metrics::CheckReaction::kDeferring;
1447 break;
1448
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001449 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001450 result = metrics::CheckResult::kUpdateAvailable;
1451 reaction = metrics::CheckReaction::kBackingOff;
1452 break;
1453
1454 default:
1455 // We report two flavors of errors, "Download errors" and "Parsing
1456 // error". Try to convert to the former and if that doesn't work
1457 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001458 metrics::DownloadErrorCode tmp_error =
1459 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001460 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1461 result = metrics::CheckResult::kDownloadError;
1462 download_error_code = tmp_error;
1463 } else {
1464 result = metrics::CheckResult::kParsingError;
1465 }
1466 break;
1467 }
1468
1469 metrics::ReportUpdateCheckMetrics(system_state_,
1470 result, reaction, download_error_code);
1471}
1472
Chris Sosa77f79e82014-06-02 18:16:24 -07001473bool OmahaRequestAction::ShouldIgnoreUpdate(
1474 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001475 // Note: policy decision to not update to a version we rolled back from.
1476 string rollback_version =
1477 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001478 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001479 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001480 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001481 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1482 return true;
1483 }
1484 }
1485
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001486 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001487 LOG(INFO) << "Update is not allowed over current connection.";
1488 return true;
1489 }
1490
1491 // Note: We could technically delete the UpdateFirstSeenAt state when we
1492 // return true. If we do, it'll mean a device has to restart the
1493 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1494 // turned on again. On the other hand, it also increases the chance of update
1495 // starvation if an admin turns AU on/off more frequently. We choose to err on
1496 // the side of preventing starvation at the cost of not applying scattering in
1497 // those cases.
1498 return false;
1499}
1500
1501bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
1502 NetworkConnectionType type;
1503 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001504 ConnectionManagerInterface* connection_manager =
1505 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001506 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001507 LOG(INFO) << "We could not determine our connection type. "
1508 << "Defaulting to allow updates.";
1509 return true;
1510 }
1511 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1512 LOG(INFO) << "We are connected via "
Alex Deymof6ee0162015-07-31 12:35:22 -07001513 << ConnectionManager::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001514 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1515 return is_allowed;
1516}
1517
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001518} // namespace chromeos_update_engine