blob: 17aa62b8ca974250e13d1f5429f74c1b2306a42d [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>
rspangler@google.com49fdf182009-10-10 00:57:34 +000034
Alex Deymo39910dc2015-11-09 17:04:30 -080035#include "update_engine/common/action_pipe.h"
36#include "update_engine/common/constants.h"
37#include "update_engine/common/hardware_interface.h"
38#include "update_engine/common/hash_calculator.h"
39#include "update_engine/common/platform_constants.h"
40#include "update_engine/common/prefs_interface.h"
41#include "update_engine/common/utils.h"
Alex Deymof6ee0162015-07-31 12:35:22 -070042#include "update_engine/connection_manager.h"
Alex Deymo38429cf2015-11-11 18:27:22 -080043#include "update_engine/metrics.h"
44#include "update_engine/metrics_utils.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070045#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070046#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080047#include "update_engine/payload_state_interface.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000048
Darin Petkov1cbd78f2010-07-29 12:38:34 -070049using base::Time;
50using base::TimeDelta;
David Zeuthene8ed8632014-07-24 13:38:10 -040051using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000052using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040053using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000054
55namespace chromeos_update_engine {
56
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080057// List of custom pair tags that we interpret in the Omaha Response:
58static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080059static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070060static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080061// Deprecated: "IsDelta"
62static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080063static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
64static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
65// Deprecated: "ManifestSignatureRsa"
66// Deprecated: "ManifestSize"
67static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
68static const char* kTagMetadataSize = "MetadataSize";
69static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070070// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080071static const char* kTagPrompt = "Prompt";
72static const char* kTagSha256 = "sha256";
David Zeuthen8f191b22013-08-06 12:27:50 -070073static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
74static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070075static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080076
Alex Deymoac41a822015-09-15 20:52:53 -070077static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000078
Alex Deymoac41a822015-09-15 20:52:53 -070079namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000080
Darin Petkov1cbd78f2010-07-29 12:38:34 -070081// Returns an XML ping element attribute assignment with attribute
82// |name| and value |ping_days| if |ping_days| has a value that needs
83// to be sent, or an empty string otherwise.
84string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070085 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070086 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070087 return "";
88}
89
90// Returns an XML ping element if any of the elapsed days need to be
91// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -070092string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -070093 string ping_active = GetPingAttribute("a", ping_active_days);
94 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
95 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -070096 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -070097 ping_active.c_str(),
98 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -070099 }
100 return "";
101}
102
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700103// Returns an XML that goes into the body of the <app> element of the Omaha
104// request based on the given parameters.
105string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700106 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700107 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700108 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700109 int ping_active_days,
110 int ping_roll_call_days,
111 PrefsInterface* prefs) {
112 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700113 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700114 if (include_ping)
115 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700116 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700117 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700118 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700119 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700120 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700121
Darin Petkov265f2902011-05-09 15:17:40 -0700122 // If this is the first update check after a reboot following a previous
123 // update, generate an event containing the previous version number. If
124 // the previous version preference file doesn't exist the event is still
125 // generated with a previous version of 0.0.0.0 -- this is relevant for
126 // older clients or new installs. The previous version event is not sent
127 // for ping-only requests because they come before the client has
Alex Deymo87c08862015-10-30 21:56:55 -0700128 // rebooted. The previous version event is also not sent if it was already
129 // sent for this new version with a previous updatecheck.
Darin Petkov265f2902011-05-09 15:17:40 -0700130 string prev_version;
131 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
132 prev_version = "0.0.0.0";
133 }
Alex Deymo87c08862015-10-30 21:56:55 -0700134 // We only store a non-empty previous version value after a successful
135 // update in the previous boot. After reporting it back to the server,
136 // we clear the previous version value so it doesn't get reported again.
137 if (!prev_version.empty()) {
138 app_body += base::StringPrintf(
139 " <event eventtype=\"%d\" eventresult=\"%d\" "
140 "previousversion=\"%s\"></event>\n",
Alex Deymo9fded1e2015-11-05 12:31:19 -0800141 OmahaEvent::kTypeRebootedAfterUpdate,
142 OmahaEvent::kResultSuccess,
Alex Deymo87c08862015-10-30 21:56:55 -0700143 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
144 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
145 << "Unable to reset the previous version.";
146 }
Darin Petkov95508da2011-01-05 12:42:29 -0800147 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700148 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800149 // The error code is an optional attribute so append it only if the result
150 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700151 string error_code;
152 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700153 error_code = base::StringPrintf(" errorcode=\"%d\"",
154 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700155 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700156 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700157 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700158 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700159 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700160
161 return app_body;
162}
163
Alex Deymo8e18f932015-03-27 16:16:59 -0700164// Returns the cohort* argument to include in the <app> tag for the passed
165// |arg_name| and |prefs_key|, if any. The return value is suitable to
166// concatenate to the list of arguments and includes a space at the end.
167string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700168 const string arg_name,
169 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700170 // There's nothing wrong with not having a given cohort setting, so we check
171 // existance first to avoid the warning log message.
172 if (!prefs->Exists(prefs_key))
173 return "";
174 string cohort_value;
175 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
176 return "";
177 // This is a sanity check to avoid sending a huge XML file back to Ohama due
178 // to a compromised stateful partition making the update check fail in low
179 // network environments envent after a reboot.
180 if (cohort_value.size() > 1024) {
181 LOG(WARNING) << "The omaha cohort setting " << arg_name
182 << " has a too big value, which must be an error or an "
183 "attacker trying to inhibit updates.";
184 return "";
185 }
186
Alex Deymob0d74eb2015-03-30 17:59:17 -0700187 string escaped_xml_value;
188 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
189 LOG(WARNING) << "The omaha cohort setting " << arg_name
190 << " is ASCII-7 invalid, ignoring it.";
191 return "";
192 }
193
Alex Deymo8e18f932015-03-27 16:16:59 -0700194 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700195 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700196}
197
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700198// Returns an XML that corresponds to the entire <app> node of the Omaha
199// request based on the given parameters.
200string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700201 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700202 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700203 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700204 int ping_active_days,
205 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800206 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700207 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700208 string app_body = GetAppBody(event, params, ping_only, include_ping,
209 ping_active_days, ping_roll_call_days,
210 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700211 string app_versions;
212
213 // If we are upgrading to a more stable channel and we are allowed to do
214 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
215 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700216 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700217 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
218 << "on downgrading to the version in the more stable channel";
219 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700220 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700221 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700222 app_versions = "version=\"" +
223 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700224 }
225
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700226 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700227 string app_channels =
228 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
229 if (params->current_channel() != download_channel) {
230 app_channels += "from_track=\"" + XmlEncodeWithDefault(
231 params->current_channel(), "") + "\" ";
232 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700233
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700234 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700235
David Zeuthen639aa362014-02-03 16:23:44 -0800236 // If install_date_days is not set (e.g. its value is -1 ), don't
237 // include the attribute.
238 string install_date_in_days_str = "";
239 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700240 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
241 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800242 }
243
Alex Deymo8e18f932015-03-27 16:16:59 -0700244 string app_cohort_args;
245 app_cohort_args += GetCohortArgXml(system_state->prefs(),
246 "cohort", kPrefsOmahaCohort);
247 app_cohort_args += GetCohortArgXml(system_state->prefs(),
248 "cohorthint", kPrefsOmahaCohortHint);
249 app_cohort_args += GetCohortArgXml(system_state->prefs(),
250 "cohortname", kPrefsOmahaCohortName);
251
Alex Deymob0d74eb2015-03-30 17:59:17 -0700252 string app_xml = " <app "
253 "appid=\"" + XmlEncodeWithDefault(params->GetAppId(), "") + "\" " +
254 app_cohort_args +
255 app_versions +
256 app_channels +
257 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
258 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
259 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
260 "delta_okay=\"" + delta_okay_str + "\" "
261 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
262 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
263 install_date_in_days_str +
264 ">\n" +
265 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700266 " </app>\n";
267
268 return app_xml;
269}
270
271// Returns an XML that corresponds to the entire <os> node of the Omaha
272// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700273string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700274 string os_xml =" <os "
275 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
276 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
277 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
278 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700279 return os_xml;
280}
281
282// Returns an XML that corresponds to the entire Omaha request based on the
283// given parameters.
284string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700285 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700286 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700287 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700288 int ping_active_days,
289 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800290 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700291 SystemState* system_state) {
292 string os_xml = GetOsXml(params);
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700293 string app_xml = GetAppXml(event, params, ping_only, include_ping,
294 ping_active_days, ping_roll_call_days,
295 install_date_in_days, system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700296
Alex Vakulenko75039d72014-03-25 12:36:28 -0700297 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700298 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700299
Alex Deymoac41a822015-09-15 20:52:53 -0700300 string updater_version = XmlEncodeWithDefault(
301 base::StringPrintf("%s-%s",
302 constants::kOmahaUpdaterID,
303 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700304 string request_xml =
305 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700306 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700307 "version=\"" + updater_version + "\" "
308 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700309 install_source +
310 "ismachine=\"1\">\n") +
311 os_xml +
312 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700313 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700314
315 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000316}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700317
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700318} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000319
David Zeuthene8ed8632014-07-24 13:38:10 -0400320// Struct used for holding data obtained when parsing the XML.
321struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400322 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
323
324 // Pointer to the expat XML_Parser object.
325 XML_Parser xml_parser;
326
David Zeuthene8ed8632014-07-24 13:38:10 -0400327 // This is the state of the parser as it's processing the XML.
328 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400329 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400330 string current_path;
331
332 // These are the values extracted from the XML.
Alex Deymo8e18f932015-03-27 16:16:59 -0700333 string app_cohort;
334 string app_cohorthint;
335 string app_cohortname;
336 bool app_cohort_set = false;
337 bool app_cohorthint_set = false;
338 bool app_cohortname_set = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400339 string updatecheck_status;
340 string updatecheck_poll_interval;
341 string daystart_elapsed_days;
342 string daystart_elapsed_seconds;
343 vector<string> url_codebase;
344 string package_name;
345 string package_size;
346 string manifest_version;
347 map<string, string> action_postinstall_attrs;
348};
349
350namespace {
351
352// Callback function invoked by expat.
353void ParserHandlerStart(void* user_data, const XML_Char* element,
354 const XML_Char** attr) {
355 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
356
357 if (data->failed)
358 return;
359
360 data->current_path += string("/") + element;
361
362 map<string, string> attrs;
363 if (attr != nullptr) {
364 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
365 string key = attr[n];
366 string value = attr[n + 1];
367 attrs[key] = value;
368 }
369 }
370
Alex Deymo8e18f932015-03-27 16:16:59 -0700371 if (data->current_path == "/response/app") {
372 if (attrs.find("cohort") != attrs.end()) {
373 data->app_cohort_set = true;
374 data->app_cohort = attrs["cohort"];
375 }
376 if (attrs.find("cohorthint") != attrs.end()) {
377 data->app_cohorthint_set = true;
378 data->app_cohorthint = attrs["cohorthint"];
379 }
380 if (attrs.find("cohortname") != attrs.end()) {
381 data->app_cohortname_set = true;
382 data->app_cohortname = attrs["cohortname"];
383 }
384 } else if (data->current_path == "/response/app/updatecheck") {
David Zeuthene8ed8632014-07-24 13:38:10 -0400385 // There is only supposed to be a single <updatecheck> element.
386 data->updatecheck_status = attrs["status"];
387 data->updatecheck_poll_interval = attrs["PollInterval"];
388 } else if (data->current_path == "/response/daystart") {
389 // Get the install-date.
390 data->daystart_elapsed_days = attrs["elapsed_days"];
391 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
392 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
393 // Look at all <url> elements.
394 data->url_codebase.push_back(attrs["codebase"]);
395 } else if (data->package_name.empty() && data->current_path ==
396 "/response/app/updatecheck/manifest/packages/package") {
397 // Only look at the first <package>.
398 data->package_name = attrs["name"];
399 data->package_size = attrs["size"];
400 } else if (data->current_path == "/response/app/updatecheck/manifest") {
401 // Get the version.
402 data->manifest_version = attrs[kTagVersion];
403 } else if (data->current_path ==
404 "/response/app/updatecheck/manifest/actions/action") {
405 // We only care about the postinstall action.
406 if (attrs["event"] == "postinstall") {
407 data->action_postinstall_attrs = attrs;
408 }
409 }
410}
411
412// Callback function invoked by expat.
413void ParserHandlerEnd(void* user_data, const XML_Char* element) {
414 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
415 if (data->failed)
416 return;
417
418 const string path_suffix = string("/") + element;
419
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700420 if (!base::EndsWith(data->current_path, path_suffix, true)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400421 LOG(ERROR) << "Unexpected end element '" << element
422 << "' with current_path='" << data->current_path << "'";
423 data->failed = true;
424 return;
425 }
426 data->current_path.resize(data->current_path.size() - path_suffix.size());
427}
428
David Zeuthenf3e28012014-08-26 18:23:52 -0400429// Callback function invoked by expat.
430//
431// This is called for entity declarations. Since Omaha is guaranteed
432// to never return any XML with entities our course of action is to
433// just stop parsing. This avoids potential resource exhaustion
434// problems AKA the "billion laughs". CVE-2013-0340.
435void ParserHandlerEntityDecl(void *user_data,
436 const XML_Char *entity_name,
437 int is_parameter_entity,
438 const XML_Char *value,
439 int value_length,
440 const XML_Char *base,
441 const XML_Char *system_id,
442 const XML_Char *public_id,
443 const XML_Char *notation_name) {
444 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
445
446 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
447 data->failed = true;
448 data->entity_decl = true;
449 XML_StopParser(data->xml_parser, false);
450}
451
David Zeuthene8ed8632014-07-24 13:38:10 -0400452} // namespace
453
Alex Deymob0d74eb2015-03-30 17:59:17 -0700454bool XmlEncode(const string& input, string* output) {
455 if (std::find_if(input.begin(), input.end(),
456 [](const char c){return c & 0x80;}) != input.end()) {
457 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
458 utils::HexDumpString(input);
459 return false;
460 }
Alex Deymocc457852015-06-18 18:35:50 -0700461 output->clear();
462 // We need at least input.size() space in the output, but the code below will
463 // handle it if we need more.
464 output->reserve(input.size());
465 for (char c : input) {
466 switch (c) {
467 case '\"':
468 output->append("&quot;");
469 break;
470 case '\'':
471 output->append("&apos;");
472 break;
473 case '&':
474 output->append("&amp;");
475 break;
476 case '<':
477 output->append("&lt;");
478 break;
479 case '>':
480 output->append("&gt;");
481 break;
482 default:
483 output->push_back(c);
484 }
485 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700486 return true;
487}
488
489string XmlEncodeWithDefault(const string& input, const string& default_value) {
490 string output;
491 if (XmlEncode(input, &output))
492 return output;
493 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000494}
495
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800496OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700497 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700498 HttpFetcher* http_fetcher,
499 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800500 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700501 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700502 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700503 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700504 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700505 ping_roll_call_days_(0) {
506 params_ = system_state->request_params();
507}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000508
Darin Petkov6a5b3222010-07-13 14:55:28 -0700509OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000510
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700511// Calculates the value to use for the ping days parameter.
512int OmahaRequestAction::CalculatePingDays(const string& key) {
513 int days = kNeverPinged;
514 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800515 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700516 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
517 if (days < 0) {
518 // If |days| is negative, then the system clock must have jumped
519 // back in time since the ping was sent. Mark the value so that
520 // it doesn't get sent to the server but we still update the
521 // last ping daystart preference. This way the next ping time
522 // will be correct, hopefully.
523 days = kPingTimeJump;
524 LOG(WARNING) <<
525 "System clock jumped back in time. Resetting ping daystarts.";
526 }
527 }
528 return days;
529}
530
531void OmahaRequestAction::InitPingDays() {
532 // We send pings only along with update checks, not with events.
533 if (IsEvent()) {
534 return;
535 }
536 // TODO(petkov): Figure a way to distinguish active use pings
537 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700538 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700539 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
540 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
541}
542
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700543bool OmahaRequestAction::ShouldPing() const {
544 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
545 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
546 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
547 if (powerwash_count > 0) {
548 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
549 << "powerwash_count is " << powerwash_count;
550 return false;
551 }
552 return true;
553 }
554 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
555}
556
David Zeuthen639aa362014-02-03 16:23:44 -0800557// static
558int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
559 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700560 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800561 return -1;
562
563 // If we have the value stored on disk, just return it.
564 int64_t stored_value;
565 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
566 // Convert and sanity-check.
567 int install_date_days = static_cast<int>(stored_value);
568 if (install_date_days >= 0)
569 return install_date_days;
570 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
571 << install_date_days << " looks suspicious.";
572 prefs->Delete(kPrefsInstallDateDays);
573 }
574
575 // Otherwise, if OOBE is not complete then do nothing and wait for
576 // ParseResponse() to call ParseInstallDate() and then
577 // PersistInstallDate() to set the kPrefsInstallDateDays state
578 // variable. Once that is done, we'll then report back in future
579 // Omaha requests. This works exactly because OOBE triggers an
580 // update check.
581 //
582 // However, if OOBE is complete and the kPrefsInstallDateDays state
583 // variable is not set, there are two possibilities
584 //
585 // 1. The update check in OOBE failed so we never got a response
586 // from Omaha (no network etc.); or
587 //
588 // 2. OOBE was done on an older version that didn't write to the
589 // kPrefsInstallDateDays state variable.
590 //
591 // In both cases, we approximate the install date by simply
592 // inspecting the timestamp of when OOBE happened.
593
594 Time time_of_oobe;
Alex Deymobccbc382014-04-03 13:38:55 -0700595 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800596 LOG(INFO) << "Not generating Omaha InstallData as we have "
597 << "no prefs file and OOBE is not complete.";
598 return -1;
599 }
600
601 int num_days;
602 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
603 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
604 << "as its value '" << utils::ToString(time_of_oobe)
605 << "' looks suspicious.";
606 return -1;
607 }
608
609 // Persist this to disk, for future use.
610 if (!OmahaRequestAction::PersistInstallDate(system_state,
611 num_days,
612 kProvisionedFromOOBEMarker))
613 return -1;
614
615 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
616 << num_days << " days";
617
618 return num_days;
619}
620
Darin Petkov6a5b3222010-07-13 14:55:28 -0700621void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000622 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700623 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700624 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700625 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700626 return;
627 }
David Zeuthen639aa362014-02-03 16:23:44 -0800628
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700629 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700630 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700631 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700632 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700633 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800634 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800635 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700636 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700637
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800638 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
639 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700640 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700641 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700642 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000643}
644
Darin Petkov6a5b3222010-07-13 14:55:28 -0700645void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000646 http_fetcher_->TerminateTransfer();
647}
648
649// We just store the response in the buffer. Once we've received all bytes,
650// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700651void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800652 const void* bytes,
653 size_t length) {
654 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
655 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000656}
657
658namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000659
660// Parses a 64 bit base-10 int from a string and returns it. Returns 0
661// on error. If the string contains "0", that's indistinguishable from
662// error.
663off_t ParseInt(const string& str) {
664 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700665 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000666 if (rc < 1) {
667 // failure
668 return 0;
669 }
670 return ret;
671}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700672
David Zeuthene8ed8632014-07-24 13:38:10 -0400673// Parses |str| and returns |true| if, and only if, its value is "true".
674bool ParseBool(const string& str) {
675 return str == "true";
676}
677
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700678// Update the last ping day preferences based on the server daystart
679// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400680bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700681 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400682 TEST_AND_RETURN_FALSE(
683 base::StringToInt64(parser_data->daystart_elapsed_seconds,
684 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700685 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
686
687 // Remember the local time that matches the server's last midnight
688 // time.
689 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
690 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
691 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
692 return true;
693}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700694} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000695
David Zeuthene8ed8632014-07-24 13:38:10 -0400696bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700697 OmahaResponse* output_object,
698 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400699 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700700 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700701 return false;
702 }
703
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800704 // chromium-os:37289: The PollInterval is not supported by Omaha server
705 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700706 // slow down the request rate from the server-side. Note that the PollInterval
707 // is not persisted, so it has to be sent by the server on every response to
708 // guarantee that the scheduler uses this value (otherwise, if the device got
709 // rebooted after the last server-indicated value, it'll revert to the default
710 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
711 // based on the assumption that we perform an update check every hour so that
712 // the max value of 8 will roughly be equivalent to one work day. If we decide
713 // to use PollInterval permanently, we should update the
714 // max_update_checks_allowed to take PollInterval into account. Note: The
715 // parsing for PollInterval happens even before parsing of the status because
716 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400717 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700718 &output_object->poll_interval);
719
David Zeuthen639aa362014-02-03 16:23:44 -0800720 // Check for the "elapsed_days" attribute in the "daystart"
721 // element. This is the number of days since Jan 1 2007, 0:00
722 // PST. If we don't have a persisted value of the Omaha InstallDate,
723 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400724 if (ParseInstallDate(parser_data, output_object) &&
725 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800726 // Since output_object->install_date_days is never negative, the
727 // elapsed_days -> install-date calculation is reduced to simply
728 // rounding down to the nearest number divisible by 7.
729 int remainder = output_object->install_date_days % 7;
730 int install_date_days_rounded =
731 output_object->install_date_days - remainder;
732 if (PersistInstallDate(system_state_,
733 install_date_days_rounded,
734 kProvisionedFromOmahaResponse)) {
735 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
736 << install_date_days_rounded << " days";
737 }
738 }
739
Alex Deymo00d79ac2015-06-29 15:41:49 -0700740 // We persist the cohorts sent by omaha even if the status is "noupdate".
741 if (parser_data->app_cohort_set)
742 PersistCohortData(kPrefsOmahaCohort, parser_data->app_cohort);
743 if (parser_data->app_cohorthint_set)
744 PersistCohortData(kPrefsOmahaCohortHint, parser_data->app_cohorthint);
745 if (parser_data->app_cohortname_set)
746 PersistCohortData(kPrefsOmahaCohortName, parser_data->app_cohortname);
747
David Zeuthene8ed8632014-07-24 13:38:10 -0400748 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700749 return false;
750
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800751 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
752 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400753 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700754 return false;
755
David Zeuthene8ed8632014-07-24 13:38:10 -0400756 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700757 return false;
758
David Zeuthene8ed8632014-07-24 13:38:10 -0400759 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700760 return false;
761
762 return true;
763}
764
David Zeuthene8ed8632014-07-24 13:38:10 -0400765bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700766 OmahaResponse* output_object,
767 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400768 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700769 if (status == "noupdate") {
770 LOG(INFO) << "No update.";
771 output_object->update_exists = false;
772 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700773 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700774 return false;
775 }
776
777 if (status != "ok") {
778 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700779 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700780 return false;
781 }
782
783 return true;
784}
785
David Zeuthene8ed8632014-07-24 13:38:10 -0400786bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700787 OmahaResponse* output_object,
788 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400789 if (parser_data->url_codebase.empty()) {
790 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700791 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700792 return false;
793 }
794
David Zeuthene8ed8632014-07-24 13:38:10 -0400795 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800796 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400797 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800798 if (codebase.empty()) {
799 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700800 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800801 return false;
802 }
803 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700804 }
805
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700806 return true;
807}
808
David Zeuthene8ed8632014-07-24 13:38:10 -0400809bool OmahaRequestAction::ParsePackage(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700810 OmahaResponse* output_object,
811 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400812 if (parser_data->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700813 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700814 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700815 return false;
816 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800817
818 // Append the package name to each URL in our list so that we don't
819 // propagate the urlBase vs packageName distinctions beyond this point.
820 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400821 for (auto& payload_url : output_object->payload_urls)
822 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700823
824 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400825 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700826 if (size <= 0) {
827 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700828 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700829 return false;
830 }
831 output_object->size = size;
832
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800833 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700834
835 return true;
836}
837
David Zeuthene8ed8632014-07-24 13:38:10 -0400838bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700839 OmahaResponse* output_object,
840 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400841 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700842 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700843 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700844 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700845 return false;
846 }
847
848 LOG(INFO) << "Received omaha response to update to version "
849 << output_object->version;
850
David Zeuthene8ed8632014-07-24 13:38:10 -0400851 map<string, string> attrs = parser_data->action_postinstall_attrs;
852 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700853 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700854 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700855 return false;
856 }
857
David Zeuthene8ed8632014-07-24 13:38:10 -0400858 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700859 if (output_object->hash.empty()) {
860 LOG(ERROR) << "Omaha Response has empty sha256 value";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700861 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700862 return false;
863 }
864
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800865 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400866 output_object->more_info_url = attrs[kTagMoreInfo];
867 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
868 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
869 output_object->prompt = ParseBool(attrs[kTagPrompt]);
870 output_object->deadline = attrs[kTagDeadline];
871 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700872 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400873 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700874 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400875 ParseBool(attrs[kTagDisableP2PForSharing]);
876 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800877
David Zeuthene8ed8632014-07-24 13:38:10 -0400878 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800879 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800880 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700881
David Zeuthene8ed8632014-07-24 13:38:10 -0400882 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800883
884 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400885 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800886
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700887 return true;
888}
889
David Zeuthene8ed8632014-07-24 13:38:10 -0400890// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000891// and fill in the appropriate fields of the output object. Also, notifies
892// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700893void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
894 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000895 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800896 string current_response(response_buffer_.begin(), response_buffer_.end());
897 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700898
Gilad Arnold74b5f552014-10-07 08:17:16 -0700899 PayloadStateInterface* const payload_state = system_state_->payload_state();
900
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700901 // Events are best effort transactions -- assume they always succeed.
902 if (IsEvent()) {
903 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800904 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700905 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800906 LOG(INFO) << "Signalling Crash Reporter.";
907 utils::ScheduleCrashReporterUpload();
908 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700909 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700910 return;
911 }
912
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700913 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700914 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700915 int code = GetHTTPResponseCode();
916 // Makes sure we send sane error values.
917 if (code < 0 || code >= 1000) {
918 code = 999;
919 }
David Zeuthena99981f2013-04-29 13:42:47 -0700920 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700921 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000922 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700923 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000924
David Zeuthene8ed8632014-07-24 13:38:10 -0400925 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400926 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400927 XML_SetUserData(parser, &parser_data);
928 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400929 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800930 XML_Status res = XML_Parse(
931 parser,
932 reinterpret_cast<const char*>(response_buffer_.data()),
933 response_buffer_.size(),
934 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400935 XML_ParserFree(parser);
936
937 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700938 LOG(ERROR) << "Omaha response not valid XML: "
939 << XML_ErrorString(XML_GetErrorCode(parser))
940 << " at line " << XML_GetCurrentLineNumber(parser)
941 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400942 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
943 if (response_buffer_.empty()) {
944 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
945 } else if (parser_data.entity_decl) {
946 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
947 }
948 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000949 return;
950 }
951
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700952 // Update the last ping day preferences based on the server daystart response
953 // even if we didn't send a ping. Omaha always includes the daystart in the
954 // response, but log the error if it didn't.
955 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
956 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700957
Thieu Le116fda32011-04-19 11:01:54 -0700958 if (!HasOutputPipe()) {
959 // Just set success to whether or not the http transfer succeeded,
960 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700961 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700962 return;
963 }
964
Darin Petkov6a5b3222010-07-13 14:55:28 -0700965 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400966 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000967 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700968 output_object.update_exists = true;
969 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000970
Chris Sosa77f79e82014-06-02 18:16:24 -0700971 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700972 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700973 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700974 return;
975 }
976
David Zeuthen8f191b22013-08-06 12:27:50 -0700977 // If Omaha says to disable p2p, respect that
978 if (output_object.disable_p2p_for_downloading) {
979 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
980 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700981 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700982 }
983 if (output_object.disable_p2p_for_sharing) {
984 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
985 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700986 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700987 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800988
989 // Update the payload state with the current response. The payload state
990 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800991 // from what's stored already. We are updating the payload state as late
992 // as possible in this method so that if a new release gets pushed and then
993 // got pulled back due to some issues, we don't want to clear our internal
994 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800995 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800996
David Zeuthen8f191b22013-08-06 12:27:50 -0700997 // It could be we've already exceeded the deadline for when p2p is
998 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700999 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001000 payload_state->P2PNewAttempt();
1001 if (!payload_state->P2PAttemptAllowed()) {
1002 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
1003 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001004 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001005 }
1006 }
1007
1008 // From here on, we'll complete stuff in CompleteProcessing() so
1009 // disable |completer| since we'll create a new one in that
1010 // function.
1011 completer.set_should_complete(false);
1012
1013 // If we're allowed to use p2p for downloading we do not pay
1014 // attention to wall-clock-based waiting if the URL is indeed
1015 // available via p2p. Therefore, check if the file is available via
1016 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001017 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001018 LookupPayloadViaP2P(output_object);
1019 } else {
1020 CompleteProcessing();
1021 }
1022}
1023
1024void OmahaRequestAction::CompleteProcessing() {
1025 ScopedActionCompleter completer(processor_, this);
1026 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1027 PayloadStateInterface* payload_state = system_state_->payload_state();
1028
1029 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001030 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001031 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001032 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001033 return;
1034 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001035
Chris Sosa20f005c2013-09-05 13:53:08 -07001036 if (payload_state->ShouldBackoffDownload()) {
1037 output_object.update_exists = false;
1038 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1039 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001040 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001041 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001042 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001043 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001044}
1045
1046void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1047 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1048 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001049 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001050 } else {
1051 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1052 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001053 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001054 }
1055 CompleteProcessing();
1056}
1057
1058void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001059 // If the device is in the middle of an update, the state variables
1060 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1061 // tracks the offset and length of the operation currently in
1062 // progress. The offset is based from the end of the manifest which
1063 // is kPrefsManifestMetadataSize bytes long.
1064 //
1065 // To make forward progress and avoid deadlocks, we need to find a
1066 // peer that has at least the entire operation we're currently
1067 // working on. Otherwise we may end up in a situation where two
1068 // devices bounce back and forth downloading from each other,
1069 // neither making any forward progress until one of them decides to
1070 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1071 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001072 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001073 int64_t manifest_metadata_size = 0;
1074 int64_t next_data_offset = 0;
1075 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001076 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001077 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1078 &manifest_metadata_size) &&
1079 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001080 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001081 &next_data_offset) &&
1082 next_data_offset != -1 &&
1083 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1084 &next_data_length)) {
1085 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001086 }
1087
1088 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001089 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001090 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1091 << file_id << " minimum_size=" << minimum_size;
1092 system_state_->p2p_manager()->LookupUrlForFile(
1093 file_id,
1094 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001095 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001096 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1097 base::Unretained(this)));
1098 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001099}
1100
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001101bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001102 if (params_->interactive()) {
1103 LOG(INFO) << "Not deferring download because update is interactive.";
1104 return false;
1105 }
1106
David Zeuthen8f191b22013-08-06 12:27:50 -07001107 // If we're using p2p to download _and_ we have a p2p URL, we never
1108 // defer the download. This is because the download will always
1109 // happen from a peer on the LAN and we've been waiting in line for
1110 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001111 const PayloadStateInterface* payload_state = system_state_->payload_state();
1112 if (payload_state->GetUsingP2PForDownloading() &&
1113 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001114 LOG(INFO) << "Download not deferred because download "
1115 << "will happen from a local peer (via p2p).";
1116 return false;
1117 }
1118
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001119 // We should defer the downloads only if we've first satisfied the
1120 // wall-clock-based-waiting period and then the update-check-based waiting
1121 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001122 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001123 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1124 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001125 return false;
1126 }
1127
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001128 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001129 case kWallClockWaitNotSatisfied:
1130 // We haven't even satisfied the first condition, passing the
1131 // wall-clock-based waiting period, so we should defer the downloads
1132 // until that happens.
1133 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1134 return true;
1135
1136 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1137 LOG(INFO) << "wall-clock-based-wait satisfied and "
1138 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001139 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001140
1141 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1142 // Wall-clock-based waiting period is satisfied, and it's determined
1143 // that we do not need the update-check-based wait. so no need to
1144 // defer downloads.
1145 LOG(INFO) << "wall-clock-based-wait satisfied and "
1146 << "update-check-based-wait is not required.";
1147 return false;
1148
1149 default:
1150 // Returning false for this default case so we err on the
1151 // side of downloading updates than deferring in case of any bugs.
1152 NOTREACHED();
1153 return false;
1154 }
1155}
1156
1157OmahaRequestAction::WallClockWaitResult
1158OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001159 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001160 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001161 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001162
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001163 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1164 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1165 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001166 // Note: This timestamp could be that of ANY update we saw in the past
1167 // (not necessarily this particular update we're considering to apply)
1168 // but never got to apply because of some reason (e.g. stop AU policy,
1169 // updates being pulled out from Omaha, changes in target version prefix,
1170 // new update being rolled out, etc.). But for the purposes of scattering
1171 // it doesn't matter which update the timestamp corresponds to. i.e.
1172 // the clock starts ticking the first time we see an update and we're
1173 // ready to apply when the random wait period is satisfied relative to
1174 // that first seen timestamp.
1175 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1176 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1177 << utils::ToString(update_first_seen_at);
1178 } else {
1179 // This seems like an unexpected error where the persisted value exists
1180 // but it's not readable for some reason. Just skip scattering in this
1181 // case to be safe.
1182 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1183 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1184 }
1185 } else {
1186 update_first_seen_at = Time::Now();
1187 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001188 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1189 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001190 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1191 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001192 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001193 // This seems like an unexpected error where the value cannot be
1194 // persisted for some reason. Just skip scattering in this
1195 // case to be safe.
1196 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1197 << utils::ToString(update_first_seen_at)
1198 << " cannot be persisted";
1199 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1200 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001201 }
1202
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001203 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001204 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001205 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001206
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001207 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001208 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001209 << ", Time Elapsed = "
1210 << utils::FormatSecs(elapsed_time.InSeconds())
1211 << ", MaxDaysToScatter = "
1212 << max_scatter_period.InDays();
1213
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001214 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001215 // The deadline is set for all rules which serve a delta update from a
1216 // previous FSI, which means this update will be applied mostly in OOBE
1217 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1218 // quickly.
1219 LOG(INFO) << "Not scattering as deadline flag is set";
1220 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1221 }
1222
1223 if (max_scatter_period.InDays() == 0) {
1224 // This means the Omaha rule creator decides that this rule
1225 // should not be scattered irrespective of the policy.
1226 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1227 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1228 }
1229
1230 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001231 // This means we've waited more than the upperbound wait in the rule
1232 // from the time we first saw a valid update available to us.
1233 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001234 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1235 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1236 }
1237
1238 // This means we are required to participate in scattering.
1239 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001240 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001241 if (remaining_wait_time.InSeconds() <= 0) {
1242 // Yes, it's our turn now.
1243 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1244
1245 // But we can't download until the update-check-count-based wait is also
1246 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001247 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001248 kWallClockWaitDoneButUpdateCheckWaitRequired :
1249 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1250 }
1251
1252 // Not our turn yet, so we have to wait until our turn to
1253 // help scatter the downloads across all clients of the enterprise.
1254 LOG(INFO) << "Update deferred for another "
1255 << utils::FormatSecs(remaining_wait_time.InSeconds())
1256 << " per policy.";
1257 return kWallClockWaitNotSatisfied;
1258}
1259
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001260bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001261 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001262
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001263 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1264 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1265 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001266 // We are unable to read the update check count from file for some reason.
1267 // So let's proceed anyway so as to not stall the update.
1268 LOG(ERROR) << "Unable to read update check count. "
1269 << "Skipping update-check-count-based-wait.";
1270 return true;
1271 }
1272 } else {
1273 // This file does not exist. This means we haven't started our update
1274 // check count down yet, so this is the right time to start the count down.
1275 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001276 params_->min_update_checks_needed(),
1277 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001278
1279 LOG(INFO) << "Randomly picked update check count value = "
1280 << update_check_count_value;
1281
1282 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001283 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1284 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001285 // We weren't able to write the update check count file for some reason.
1286 // So let's proceed anyway so as to not stall the update.
1287 LOG(ERROR) << "Unable to write update check count. "
1288 << "Skipping update-check-count-based-wait.";
1289 return true;
1290 }
1291 }
1292
1293 if (update_check_count_value == 0) {
1294 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1295 return true;
1296 }
1297
1298 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001299 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001300 // We err on the side of skipping scattering logic instead of stalling
1301 // a machine from receiving any updates in case of any unexpected state.
1302 LOG(ERROR) << "Invalid value for update check count detected. "
1303 << "Skipping update-check-count-based-wait.";
1304 return true;
1305 }
1306
1307 // Legal value, we need to wait for more update checks to happen
1308 // until this becomes 0.
1309 LOG(INFO) << "Deferring Omaha updates for another "
1310 << update_check_count_value
1311 << " update checks per policy";
1312 return false;
1313}
1314
David Zeuthen639aa362014-02-03 16:23:44 -08001315// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001316bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001317 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001318 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001319 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001320 &elapsed_days))
1321 return false;
1322
1323 if (elapsed_days < 0)
1324 return false;
1325
1326 output_object->install_date_days = elapsed_days;
1327 return true;
1328}
1329
1330// static
1331bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1332 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001333 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001334 return false;
1335
1336 return prefs->Exists(kPrefsInstallDateDays);
1337}
1338
1339// static
1340bool OmahaRequestAction::PersistInstallDate(
1341 SystemState *system_state,
1342 int install_date_days,
1343 InstallDateProvisioningSource source) {
1344 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1345
1346 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001347 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001348 return false;
1349
1350 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1351 return false;
1352
Alex Deymoaf9a8632015-09-23 18:51:48 -07001353 string metric_name = metrics::kMetricInstallDateProvisioningSource;
David Zeuthen33bae492014-02-25 16:16:18 -08001354 system_state->metrics_lib()->SendEnumToUMA(
1355 metric_name,
1356 static_cast<int>(source), // Sample.
1357 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001358
1359 return true;
1360}
1361
Alex Deymo8e18f932015-03-27 16:16:59 -07001362bool OmahaRequestAction::PersistCohortData(
1363 const string& prefs_key,
1364 const string& new_value) {
1365 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1366 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1367 return system_state_->prefs()->Delete(prefs_key);
1368 } else if (!new_value.empty()) {
1369 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1370 return system_state_->prefs()->SetString(prefs_key, new_value);
1371 }
1372 return true;
1373}
1374
David Zeuthen33bae492014-02-25 16:16:18 -08001375void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1376 // We only want to report this on "update check".
1377 if (ping_only_ || event_ != nullptr)
1378 return;
1379
1380 metrics::CheckResult result = metrics::CheckResult::kUnset;
1381 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1382 metrics::DownloadErrorCode download_error_code =
1383 metrics::DownloadErrorCode::kUnset;
1384
1385 // Regular update attempt.
1386 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001387 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001388 // OK, we parsed the response successfully but that does
1389 // necessarily mean that an update is available.
1390 if (HasOutputPipe()) {
1391 const OmahaResponse& response = GetOutputObject();
1392 if (response.update_exists) {
1393 result = metrics::CheckResult::kUpdateAvailable;
1394 reaction = metrics::CheckReaction::kUpdating;
1395 } else {
1396 result = metrics::CheckResult::kNoUpdateAvailable;
1397 }
1398 } else {
1399 result = metrics::CheckResult::kNoUpdateAvailable;
1400 }
1401 break;
1402
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001403 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001404 result = metrics::CheckResult::kUpdateAvailable;
1405 reaction = metrics::CheckReaction::kIgnored;
1406 break;
1407
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001408 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001409 result = metrics::CheckResult::kUpdateAvailable;
1410 reaction = metrics::CheckReaction::kDeferring;
1411 break;
1412
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001413 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001414 result = metrics::CheckResult::kUpdateAvailable;
1415 reaction = metrics::CheckReaction::kBackingOff;
1416 break;
1417
1418 default:
1419 // We report two flavors of errors, "Download errors" and "Parsing
1420 // error". Try to convert to the former and if that doesn't work
1421 // we know it's the latter.
Alex Deymo38429cf2015-11-11 18:27:22 -08001422 metrics::DownloadErrorCode tmp_error =
1423 metrics_utils::GetDownloadErrorCode(code);
David Zeuthen33bae492014-02-25 16:16:18 -08001424 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1425 result = metrics::CheckResult::kDownloadError;
1426 download_error_code = tmp_error;
1427 } else {
1428 result = metrics::CheckResult::kParsingError;
1429 }
1430 break;
1431 }
1432
1433 metrics::ReportUpdateCheckMetrics(system_state_,
1434 result, reaction, download_error_code);
1435}
1436
Chris Sosa77f79e82014-06-02 18:16:24 -07001437bool OmahaRequestAction::ShouldIgnoreUpdate(
1438 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001439 // Note: policy decision to not update to a version we rolled back from.
1440 string rollback_version =
1441 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001442 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001443 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001444 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001445 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1446 return true;
1447 }
1448 }
1449
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001450 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001451 LOG(INFO) << "Update is not allowed over current connection.";
1452 return true;
1453 }
1454
1455 // Note: We could technically delete the UpdateFirstSeenAt state when we
1456 // return true. If we do, it'll mean a device has to restart the
1457 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1458 // turned on again. On the other hand, it also increases the chance of update
1459 // starvation if an admin turns AU on/off more frequently. We choose to err on
1460 // the side of preventing starvation at the cost of not applying scattering in
1461 // those cases.
1462 return false;
1463}
1464
1465bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
1466 NetworkConnectionType type;
1467 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001468 ConnectionManagerInterface* connection_manager =
1469 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001470 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001471 LOG(INFO) << "We could not determine our connection type. "
1472 << "Defaulting to allow updates.";
1473 return true;
1474 }
1475 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1476 LOG(INFO) << "We are connected via "
Alex Deymof6ee0162015-07-31 12:35:22 -07001477 << ConnectionManager::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001478 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1479 return is_allowed;
1480}
1481
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001482} // namespace chromeos_update_engine