blob: 8967762738349c88d674fd0667ccaa7fc7bcc922 [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
35#include "update_engine/action_pipe.h"
Alex Deymof6ee0162015-07-31 12:35:22 -070036#include "update_engine/connection_manager.h"
Jay Srinivasand29695d2013-04-08 15:08:05 -070037#include "update_engine/constants.h"
J. Richard Barnette056b0ab2013-10-29 15:24:56 -070038#include "update_engine/hardware_interface.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070039#include "update_engine/omaha_hash_calculator.h"
Darin Petkova4a8a8c2010-07-15 22:21:12 -070040#include "update_engine/omaha_request_params.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070041#include "update_engine/p2p_manager.h"
Jay Srinivasan55f50c22013-01-10 19:24:35 -080042#include "update_engine/payload_state_interface.h"
Alex Deymoac41a822015-09-15 20:52:53 -070043#include "update_engine/platform_constants.h"
Darin Petkov1cbd78f2010-07-29 12:38:34 -070044#include "update_engine/prefs_interface.h"
adlr@google.comc98a7ed2009-12-04 18:54:03 +000045#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000046
Darin Petkov1cbd78f2010-07-29 12:38:34 -070047using base::Time;
48using base::TimeDelta;
David Zeuthene8ed8632014-07-24 13:38:10 -040049using std::map;
rspangler@google.com49fdf182009-10-10 00:57:34 +000050using std::string;
David Zeuthene8ed8632014-07-24 13:38:10 -040051using std::vector;
rspangler@google.com49fdf182009-10-10 00:57:34 +000052
53namespace chromeos_update_engine {
54
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080055// List of custom pair tags that we interpret in the Omaha Response:
56static const char* kTagDeadline = "deadline";
Jay Srinivasan08262882012-12-28 19:29:43 -080057static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff";
Chris Sosa3b748432013-06-20 16:42:59 -070058static const char* kTagVersion = "version";
Jay Srinivasand671e972013-01-11 17:17:19 -080059// Deprecated: "IsDelta"
60static const char* kTagIsDeltaPayload = "IsDeltaPayload";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080061static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl";
62static const char* kTagMaxDaysToScatter = "MaxDaysToScatter";
63// Deprecated: "ManifestSignatureRsa"
64// Deprecated: "ManifestSize"
65static const char* kTagMetadataSignatureRsa = "MetadataSignatureRsa";
66static const char* kTagMetadataSize = "MetadataSize";
67static const char* kTagMoreInfo = "MoreInfo";
Don Garrett42bd3aa2013-04-10 18:14:56 -070068// Deprecated: "NeedsAdmin"
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080069static const char* kTagPrompt = "Prompt";
70static const char* kTagSha256 = "sha256";
David Zeuthen8f191b22013-08-06 12:27:50 -070071static const char* kTagDisableP2PForDownloading = "DisableP2PForDownloading";
72static const char* kTagDisableP2PForSharing = "DisableP2PForSharing";
David Zeuthene7f89172013-10-31 10:21:04 -070073static const char* kTagPublicKeyRsa = "PublicKeyRsa";
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -080074
Alex Deymoac41a822015-09-15 20:52:53 -070075static const char* kOmahaUpdaterVersion = "0.1.0.0";
rspangler@google.com49fdf182009-10-10 00:57:34 +000076
Alex Deymoac41a822015-09-15 20:52:53 -070077namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +000078
Darin Petkov1cbd78f2010-07-29 12:38:34 -070079// Returns an XML ping element attribute assignment with attribute
80// |name| and value |ping_days| if |ping_days| has a value that needs
81// to be sent, or an empty string otherwise.
82string GetPingAttribute(const string& name, int ping_days) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -070083 if (ping_days > 0 || ping_days == OmahaRequestAction::kNeverPinged)
Alex Vakulenko75039d72014-03-25 12:36:28 -070084 return base::StringPrintf(" %s=\"%d\"", name.c_str(), ping_days);
Darin Petkov1cbd78f2010-07-29 12:38:34 -070085 return "";
86}
87
88// Returns an XML ping element if any of the elapsed days need to be
89// sent, or an empty string otherwise.
Jay Srinivasanae4697c2013-03-18 17:08:08 -070090string GetPingXml(int ping_active_days, int ping_roll_call_days) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -070091 string ping_active = GetPingAttribute("a", ping_active_days);
92 string ping_roll_call = GetPingAttribute("r", ping_roll_call_days);
93 if (!ping_active.empty() || !ping_roll_call.empty()) {
Alex Vakulenko75039d72014-03-25 12:36:28 -070094 return base::StringPrintf(" <ping active=\"1\"%s%s></ping>\n",
Alex Deymoebbe7ef2014-10-30 13:02:49 -070095 ping_active.c_str(),
96 ping_roll_call.c_str());
Darin Petkov1cbd78f2010-07-29 12:38:34 -070097 }
98 return "";
99}
100
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700101// Returns an XML that goes into the body of the <app> element of the Omaha
102// request based on the given parameters.
103string GetAppBody(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700104 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700105 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700106 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700107 int ping_active_days,
108 int ping_roll_call_days,
109 PrefsInterface* prefs) {
110 string app_body;
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700111 if (event == nullptr) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700112 if (include_ping)
113 app_body = GetPingXml(ping_active_days, ping_roll_call_days);
Darin Petkov265f2902011-05-09 15:17:40 -0700114 if (!ping_only) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700115 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700116 " <updatecheck targetversionprefix=\"%s\""
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700117 "></updatecheck>\n",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700118 XmlEncodeWithDefault(params->target_version_prefix(), "").c_str());
Jay Srinivasan0a708742012-03-20 11:26:12 -0700119
Darin Petkov265f2902011-05-09 15:17:40 -0700120 // If this is the first update check after a reboot following a previous
121 // update, generate an event containing the previous version number. If
122 // the previous version preference file doesn't exist the event is still
123 // generated with a previous version of 0.0.0.0 -- this is relevant for
124 // older clients or new installs. The previous version event is not sent
125 // for ping-only requests because they come before the client has
126 // rebooted.
127 string prev_version;
128 if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) {
129 prev_version = "0.0.0.0";
130 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700131
Alex Vakulenko75039d72014-03-25 12:36:28 -0700132 app_body += base::StringPrintf(
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700133 " <event eventtype=\"%d\" eventresult=\"%d\" "
134 "previousversion=\"%s\"></event>\n",
135 OmahaEvent::kTypeUpdateComplete,
136 OmahaEvent::kResultSuccessReboot,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700137 XmlEncodeWithDefault(prev_version, "0.0.0.0").c_str());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700138 LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, ""))
139 << "Unable to reset the previous version.";
Darin Petkov95508da2011-01-05 12:42:29 -0800140 }
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700141 } else {
Darin Petkovc91dd6b2011-01-10 12:31:34 -0800142 // The error code is an optional attribute so append it only if the result
143 // is not success.
Darin Petkove17f86b2010-07-20 09:12:01 -0700144 string error_code;
145 if (event->result != OmahaEvent::kResultSuccess) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700146 error_code = base::StringPrintf(" errorcode=\"%d\"",
147 static_cast<int>(event->error_code));
Darin Petkove17f86b2010-07-20 09:12:01 -0700148 }
Alex Vakulenko75039d72014-03-25 12:36:28 -0700149 app_body = base::StringPrintf(
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700150 " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n",
Darin Petkove17f86b2010-07-20 09:12:01 -0700151 event->type, event->result, error_code.c_str());
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700152 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700153
154 return app_body;
155}
156
Alex Deymo8e18f932015-03-27 16:16:59 -0700157// Returns the cohort* argument to include in the <app> tag for the passed
158// |arg_name| and |prefs_key|, if any. The return value is suitable to
159// concatenate to the list of arguments and includes a space at the end.
160string GetCohortArgXml(PrefsInterface* prefs,
Alex Deymob0d74eb2015-03-30 17:59:17 -0700161 const string arg_name,
162 const string prefs_key) {
Alex Deymo8e18f932015-03-27 16:16:59 -0700163 // There's nothing wrong with not having a given cohort setting, so we check
164 // existance first to avoid the warning log message.
165 if (!prefs->Exists(prefs_key))
166 return "";
167 string cohort_value;
168 if (!prefs->GetString(prefs_key, &cohort_value) || cohort_value.empty())
169 return "";
170 // This is a sanity check to avoid sending a huge XML file back to Ohama due
171 // to a compromised stateful partition making the update check fail in low
172 // network environments envent after a reboot.
173 if (cohort_value.size() > 1024) {
174 LOG(WARNING) << "The omaha cohort setting " << arg_name
175 << " has a too big value, which must be an error or an "
176 "attacker trying to inhibit updates.";
177 return "";
178 }
179
Alex Deymob0d74eb2015-03-30 17:59:17 -0700180 string escaped_xml_value;
181 if (!XmlEncode(cohort_value, &escaped_xml_value)) {
182 LOG(WARNING) << "The omaha cohort setting " << arg_name
183 << " is ASCII-7 invalid, ignoring it.";
184 return "";
185 }
186
Alex Deymo8e18f932015-03-27 16:16:59 -0700187 return base::StringPrintf("%s=\"%s\" ",
Alex Deymob0d74eb2015-03-30 17:59:17 -0700188 arg_name.c_str(), escaped_xml_value.c_str());
Alex Deymo8e18f932015-03-27 16:16:59 -0700189}
190
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700191// Returns an XML that corresponds to the entire <app> node of the Omaha
192// request based on the given parameters.
193string GetAppXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700194 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700195 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700196 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700197 int ping_active_days,
198 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800199 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700200 SystemState* system_state) {
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700201 string app_body = GetAppBody(event, params, ping_only, include_ping,
202 ping_active_days, ping_roll_call_days,
203 system_state->prefs());
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700204 string app_versions;
205
206 // If we are upgrading to a more stable channel and we are allowed to do
207 // powerwash, then pass 0.0.0.0 as the version. This is needed to get the
208 // highest-versioned payload on the destination channel.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700209 if (params->to_more_stable_channel() && params->is_powerwash_allowed()) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700210 LOG(INFO) << "Passing OS version as 0.0.0.0 as we are set to powerwash "
211 << "on downgrading to the version in the more stable channel";
212 app_versions = "version=\"0.0.0.0\" from_version=\"" +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700213 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700214 } else {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700215 app_versions = "version=\"" +
216 XmlEncodeWithDefault(params->app_version(), "0.0.0.0") + "\" ";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700217 }
218
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700219 string download_channel = params->download_channel();
Alex Deymob0d74eb2015-03-30 17:59:17 -0700220 string app_channels =
221 "track=\"" + XmlEncodeWithDefault(download_channel, "") + "\" ";
222 if (params->current_channel() != download_channel) {
223 app_channels += "from_track=\"" + XmlEncodeWithDefault(
224 params->current_channel(), "") + "\" ";
225 }
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700226
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700227 string delta_okay_str = params->delta_okay() ? "true" : "false";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700228
David Zeuthen639aa362014-02-03 16:23:44 -0800229 // If install_date_days is not set (e.g. its value is -1 ), don't
230 // include the attribute.
231 string install_date_in_days_str = "";
232 if (install_date_in_days >= 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700233 install_date_in_days_str = base::StringPrintf("installdate=\"%d\" ",
234 install_date_in_days);
David Zeuthen639aa362014-02-03 16:23:44 -0800235 }
236
Alex Deymo8e18f932015-03-27 16:16:59 -0700237 string app_cohort_args;
238 app_cohort_args += GetCohortArgXml(system_state->prefs(),
239 "cohort", kPrefsOmahaCohort);
240 app_cohort_args += GetCohortArgXml(system_state->prefs(),
241 "cohorthint", kPrefsOmahaCohortHint);
242 app_cohort_args += GetCohortArgXml(system_state->prefs(),
243 "cohortname", kPrefsOmahaCohortName);
244
Alex Deymob0d74eb2015-03-30 17:59:17 -0700245 string app_xml = " <app "
246 "appid=\"" + XmlEncodeWithDefault(params->GetAppId(), "") + "\" " +
247 app_cohort_args +
248 app_versions +
249 app_channels +
250 "lang=\"" + XmlEncodeWithDefault(params->app_lang(), "en-US") + "\" " +
251 "board=\"" + XmlEncodeWithDefault(params->os_board(), "") + "\" " +
252 "hardware_class=\"" + XmlEncodeWithDefault(params->hwid(), "") + "\" " +
253 "delta_okay=\"" + delta_okay_str + "\" "
254 "fw_version=\"" + XmlEncodeWithDefault(params->fw_version(), "") + "\" " +
255 "ec_version=\"" + XmlEncodeWithDefault(params->ec_version(), "") + "\" " +
256 install_date_in_days_str +
257 ">\n" +
258 app_body +
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700259 " </app>\n";
260
261 return app_xml;
262}
263
264// Returns an XML that corresponds to the entire <os> node of the Omaha
265// request based on the given parameters.
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700266string GetOsXml(OmahaRequestParams* params) {
Alex Deymob0d74eb2015-03-30 17:59:17 -0700267 string os_xml =" <os "
268 "version=\"" + XmlEncodeWithDefault(params->os_version(), "") + "\" " +
269 "platform=\"" + XmlEncodeWithDefault(params->os_platform(), "") + "\" " +
270 "sp=\"" + XmlEncodeWithDefault(params->os_sp(), "") + "\">"
271 "</os>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700272 return os_xml;
273}
274
275// Returns an XML that corresponds to the entire Omaha request based on the
276// given parameters.
277string GetRequestXml(const OmahaEvent* event,
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700278 OmahaRequestParams* params,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700279 bool ping_only,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700280 bool include_ping,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700281 int ping_active_days,
282 int ping_roll_call_days,
David Zeuthen639aa362014-02-03 16:23:44 -0800283 int install_date_in_days,
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700284 SystemState* system_state) {
285 string os_xml = GetOsXml(params);
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700286 string app_xml = GetAppXml(event, params, ping_only, include_ping,
287 ping_active_days, ping_roll_call_days,
288 install_date_in_days, system_state);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700289
Alex Vakulenko75039d72014-03-25 12:36:28 -0700290 string install_source = base::StringPrintf("installsource=\"%s\" ",
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700291 (params->interactive() ? "ondemandupdate" : "scheduler"));
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700292
Alex Deymoac41a822015-09-15 20:52:53 -0700293 string updater_version = XmlEncodeWithDefault(
294 base::StringPrintf("%s-%s",
295 constants::kOmahaUpdaterID,
296 kOmahaUpdaterVersion), "");
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700297 string request_xml =
298 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
Alex Deymob0d74eb2015-03-30 17:59:17 -0700299 "<request protocol=\"3.0\" " + (
Alex Deymoac41a822015-09-15 20:52:53 -0700300 "version=\"" + updater_version + "\" "
301 "updaterversion=\"" + updater_version + "\" " +
Alex Deymob0d74eb2015-03-30 17:59:17 -0700302 install_source +
303 "ismachine=\"1\">\n") +
304 os_xml +
305 app_xml +
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700306 "</request>\n";
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700307
308 return request_xml;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000309}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700310
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700311} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000312
David Zeuthene8ed8632014-07-24 13:38:10 -0400313// Struct used for holding data obtained when parsing the XML.
314struct OmahaParserData {
David Zeuthenf3e28012014-08-26 18:23:52 -0400315 explicit OmahaParserData(XML_Parser _xml_parser) : xml_parser(_xml_parser) {}
316
317 // Pointer to the expat XML_Parser object.
318 XML_Parser xml_parser;
319
David Zeuthene8ed8632014-07-24 13:38:10 -0400320 // This is the state of the parser as it's processing the XML.
321 bool failed = false;
David Zeuthenf3e28012014-08-26 18:23:52 -0400322 bool entity_decl = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400323 string current_path;
324
325 // These are the values extracted from the XML.
Alex Deymo8e18f932015-03-27 16:16:59 -0700326 string app_cohort;
327 string app_cohorthint;
328 string app_cohortname;
329 bool app_cohort_set = false;
330 bool app_cohorthint_set = false;
331 bool app_cohortname_set = false;
David Zeuthene8ed8632014-07-24 13:38:10 -0400332 string updatecheck_status;
333 string updatecheck_poll_interval;
334 string daystart_elapsed_days;
335 string daystart_elapsed_seconds;
336 vector<string> url_codebase;
337 string package_name;
338 string package_size;
339 string manifest_version;
340 map<string, string> action_postinstall_attrs;
341};
342
343namespace {
344
345// Callback function invoked by expat.
346void ParserHandlerStart(void* user_data, const XML_Char* element,
347 const XML_Char** attr) {
348 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
349
350 if (data->failed)
351 return;
352
353 data->current_path += string("/") + element;
354
355 map<string, string> attrs;
356 if (attr != nullptr) {
357 for (int n = 0; attr[n] != nullptr && attr[n+1] != nullptr; n += 2) {
358 string key = attr[n];
359 string value = attr[n + 1];
360 attrs[key] = value;
361 }
362 }
363
Alex Deymo8e18f932015-03-27 16:16:59 -0700364 if (data->current_path == "/response/app") {
365 if (attrs.find("cohort") != attrs.end()) {
366 data->app_cohort_set = true;
367 data->app_cohort = attrs["cohort"];
368 }
369 if (attrs.find("cohorthint") != attrs.end()) {
370 data->app_cohorthint_set = true;
371 data->app_cohorthint = attrs["cohorthint"];
372 }
373 if (attrs.find("cohortname") != attrs.end()) {
374 data->app_cohortname_set = true;
375 data->app_cohortname = attrs["cohortname"];
376 }
377 } else if (data->current_path == "/response/app/updatecheck") {
David Zeuthene8ed8632014-07-24 13:38:10 -0400378 // There is only supposed to be a single <updatecheck> element.
379 data->updatecheck_status = attrs["status"];
380 data->updatecheck_poll_interval = attrs["PollInterval"];
381 } else if (data->current_path == "/response/daystart") {
382 // Get the install-date.
383 data->daystart_elapsed_days = attrs["elapsed_days"];
384 data->daystart_elapsed_seconds = attrs["elapsed_seconds"];
385 } else if (data->current_path == "/response/app/updatecheck/urls/url") {
386 // Look at all <url> elements.
387 data->url_codebase.push_back(attrs["codebase"]);
388 } else if (data->package_name.empty() && data->current_path ==
389 "/response/app/updatecheck/manifest/packages/package") {
390 // Only look at the first <package>.
391 data->package_name = attrs["name"];
392 data->package_size = attrs["size"];
393 } else if (data->current_path == "/response/app/updatecheck/manifest") {
394 // Get the version.
395 data->manifest_version = attrs[kTagVersion];
396 } else if (data->current_path ==
397 "/response/app/updatecheck/manifest/actions/action") {
398 // We only care about the postinstall action.
399 if (attrs["event"] == "postinstall") {
400 data->action_postinstall_attrs = attrs;
401 }
402 }
403}
404
405// Callback function invoked by expat.
406void ParserHandlerEnd(void* user_data, const XML_Char* element) {
407 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
408 if (data->failed)
409 return;
410
411 const string path_suffix = string("/") + element;
412
Alex Vakulenko6a9d3492015-06-15 12:53:22 -0700413 if (!base::EndsWith(data->current_path, path_suffix, true)) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400414 LOG(ERROR) << "Unexpected end element '" << element
415 << "' with current_path='" << data->current_path << "'";
416 data->failed = true;
417 return;
418 }
419 data->current_path.resize(data->current_path.size() - path_suffix.size());
420}
421
David Zeuthenf3e28012014-08-26 18:23:52 -0400422// Callback function invoked by expat.
423//
424// This is called for entity declarations. Since Omaha is guaranteed
425// to never return any XML with entities our course of action is to
426// just stop parsing. This avoids potential resource exhaustion
427// problems AKA the "billion laughs". CVE-2013-0340.
428void ParserHandlerEntityDecl(void *user_data,
429 const XML_Char *entity_name,
430 int is_parameter_entity,
431 const XML_Char *value,
432 int value_length,
433 const XML_Char *base,
434 const XML_Char *system_id,
435 const XML_Char *public_id,
436 const XML_Char *notation_name) {
437 OmahaParserData* data = reinterpret_cast<OmahaParserData*>(user_data);
438
439 LOG(ERROR) << "XML entities are not supported. Aborting parsing.";
440 data->failed = true;
441 data->entity_decl = true;
442 XML_StopParser(data->xml_parser, false);
443}
444
David Zeuthene8ed8632014-07-24 13:38:10 -0400445} // namespace
446
Alex Deymob0d74eb2015-03-30 17:59:17 -0700447bool XmlEncode(const string& input, string* output) {
448 if (std::find_if(input.begin(), input.end(),
449 [](const char c){return c & 0x80;}) != input.end()) {
450 LOG(WARNING) << "Invalid ASCII-7 string passed to the XML encoder:";
451 utils::HexDumpString(input);
452 return false;
453 }
Alex Deymocc457852015-06-18 18:35:50 -0700454 output->clear();
455 // We need at least input.size() space in the output, but the code below will
456 // handle it if we need more.
457 output->reserve(input.size());
458 for (char c : input) {
459 switch (c) {
460 case '\"':
461 output->append("&quot;");
462 break;
463 case '\'':
464 output->append("&apos;");
465 break;
466 case '&':
467 output->append("&amp;");
468 break;
469 case '<':
470 output->append("&lt;");
471 break;
472 case '>':
473 output->append("&gt;");
474 break;
475 default:
476 output->push_back(c);
477 }
478 }
Alex Deymob0d74eb2015-03-30 17:59:17 -0700479 return true;
480}
481
482string XmlEncodeWithDefault(const string& input, const string& default_value) {
483 string output;
484 if (XmlEncode(input, &output))
485 return output;
486 return default_value;
rspangler@google.com49fdf182009-10-10 00:57:34 +0000487}
488
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800489OmahaRequestAction::OmahaRequestAction(SystemState* system_state,
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700490 OmahaEvent* event,
Thieu Le116fda32011-04-19 11:01:54 -0700491 HttpFetcher* http_fetcher,
492 bool ping_only)
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800493 : system_state_(system_state),
Darin Petkova4a8a8c2010-07-15 22:21:12 -0700494 event_(event),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700495 http_fetcher_(http_fetcher),
Thieu Le116fda32011-04-19 11:01:54 -0700496 ping_only_(ping_only),
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700497 ping_active_days_(0),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700498 ping_roll_call_days_(0) {
499 params_ = system_state->request_params();
500}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000501
Darin Petkov6a5b3222010-07-13 14:55:28 -0700502OmahaRequestAction::~OmahaRequestAction() {}
rspangler@google.com49fdf182009-10-10 00:57:34 +0000503
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700504// Calculates the value to use for the ping days parameter.
505int OmahaRequestAction::CalculatePingDays(const string& key) {
506 int days = kNeverPinged;
507 int64_t last_ping = 0;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800508 if (system_state_->prefs()->GetInt64(key, &last_ping) && last_ping >= 0) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700509 days = (Time::Now() - Time::FromInternalValue(last_ping)).InDays();
510 if (days < 0) {
511 // If |days| is negative, then the system clock must have jumped
512 // back in time since the ping was sent. Mark the value so that
513 // it doesn't get sent to the server but we still update the
514 // last ping daystart preference. This way the next ping time
515 // will be correct, hopefully.
516 days = kPingTimeJump;
517 LOG(WARNING) <<
518 "System clock jumped back in time. Resetting ping daystarts.";
519 }
520 }
521 return days;
522}
523
524void OmahaRequestAction::InitPingDays() {
525 // We send pings only along with update checks, not with events.
526 if (IsEvent()) {
527 return;
528 }
529 // TODO(petkov): Figure a way to distinguish active use pings
530 // vs. roll call pings. Currently, the two pings are identical. A
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700531 // fix needs to change this code as well as UpdateLastPingDays and ShouldPing.
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700532 ping_active_days_ = CalculatePingDays(kPrefsLastActivePingDay);
533 ping_roll_call_days_ = CalculatePingDays(kPrefsLastRollCallPingDay);
534}
535
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700536bool OmahaRequestAction::ShouldPing() const {
537 if (ping_active_days_ == OmahaRequestAction::kNeverPinged &&
538 ping_roll_call_days_ == OmahaRequestAction::kNeverPinged) {
539 int powerwash_count = system_state_->hardware()->GetPowerwashCount();
540 if (powerwash_count > 0) {
541 LOG(INFO) << "Not sending ping with a=-1 r=-1 to omaha because "
542 << "powerwash_count is " << powerwash_count;
543 return false;
544 }
545 return true;
546 }
547 return ping_active_days_ > 0 || ping_roll_call_days_ > 0;
548}
549
David Zeuthen639aa362014-02-03 16:23:44 -0800550// static
551int OmahaRequestAction::GetInstallDate(SystemState* system_state) {
552 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700553 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -0800554 return -1;
555
556 // If we have the value stored on disk, just return it.
557 int64_t stored_value;
558 if (prefs->GetInt64(kPrefsInstallDateDays, &stored_value)) {
559 // Convert and sanity-check.
560 int install_date_days = static_cast<int>(stored_value);
561 if (install_date_days >= 0)
562 return install_date_days;
563 LOG(ERROR) << "Dropping stored Omaha InstallData since its value num_days="
564 << install_date_days << " looks suspicious.";
565 prefs->Delete(kPrefsInstallDateDays);
566 }
567
568 // Otherwise, if OOBE is not complete then do nothing and wait for
569 // ParseResponse() to call ParseInstallDate() and then
570 // PersistInstallDate() to set the kPrefsInstallDateDays state
571 // variable. Once that is done, we'll then report back in future
572 // Omaha requests. This works exactly because OOBE triggers an
573 // update check.
574 //
575 // However, if OOBE is complete and the kPrefsInstallDateDays state
576 // variable is not set, there are two possibilities
577 //
578 // 1. The update check in OOBE failed so we never got a response
579 // from Omaha (no network etc.); or
580 //
581 // 2. OOBE was done on an older version that didn't write to the
582 // kPrefsInstallDateDays state variable.
583 //
584 // In both cases, we approximate the install date by simply
585 // inspecting the timestamp of when OOBE happened.
586
587 Time time_of_oobe;
Alex Deymobccbc382014-04-03 13:38:55 -0700588 if (!system_state->hardware()->IsOOBEComplete(&time_of_oobe)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800589 LOG(INFO) << "Not generating Omaha InstallData as we have "
590 << "no prefs file and OOBE is not complete.";
591 return -1;
592 }
593
594 int num_days;
595 if (!utils::ConvertToOmahaInstallDate(time_of_oobe, &num_days)) {
596 LOG(ERROR) << "Not generating Omaha InstallData from time of OOBE "
597 << "as its value '" << utils::ToString(time_of_oobe)
598 << "' looks suspicious.";
599 return -1;
600 }
601
602 // Persist this to disk, for future use.
603 if (!OmahaRequestAction::PersistInstallDate(system_state,
604 num_days,
605 kProvisionedFromOOBEMarker))
606 return -1;
607
608 LOG(INFO) << "Set the Omaha InstallDate from OOBE time-stamp to "
609 << num_days << " days";
610
611 return num_days;
612}
613
Darin Petkov6a5b3222010-07-13 14:55:28 -0700614void OmahaRequestAction::PerformAction() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000615 http_fetcher_->set_delegate(this);
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700616 InitPingDays();
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700617 if (ping_only_ && !ShouldPing()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700618 processor_->ActionComplete(this, ErrorCode::kSuccess);
Thieu Leb44e9e82011-06-06 14:34:04 -0700619 return;
620 }
David Zeuthen639aa362014-02-03 16:23:44 -0800621
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700622 string request_post(GetRequestXml(event_.get(),
Jay Srinivasan1c0fe792013-03-28 16:45:25 -0700623 params_,
Thieu Le116fda32011-04-19 11:01:54 -0700624 ping_only_,
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700625 ShouldPing(), // include_ping
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700626 ping_active_days_,
Darin Petkov95508da2011-01-05 12:42:29 -0800627 ping_roll_call_days_,
David Zeuthen639aa362014-02-03 16:23:44 -0800628 GetInstallDate(system_state_),
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700629 system_state_));
Jay Srinivasan0a708742012-03-20 11:26:12 -0700630
Gilad Arnold9dd1e7c2012-02-16 12:13:36 -0800631 http_fetcher_->SetPostData(request_post.data(), request_post.size(),
632 kHttpContentTypeTextXml);
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700633 LOG(INFO) << "Posting an Omaha request to " << params_->update_url();
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700634 LOG(INFO) << "Request: " << request_post;
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700635 http_fetcher_->BeginTransfer(params_->update_url());
rspangler@google.com49fdf182009-10-10 00:57:34 +0000636}
637
Darin Petkov6a5b3222010-07-13 14:55:28 -0700638void OmahaRequestAction::TerminateProcessing() {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000639 http_fetcher_->TerminateTransfer();
640}
641
642// We just store the response in the buffer. Once we've received all bytes,
643// we'll look in the buffer and decide what to do.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700644void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher,
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800645 const void* bytes,
646 size_t length) {
647 const uint8_t* byte_ptr = reinterpret_cast<const uint8_t*>(bytes);
648 response_buffer_.insert(response_buffer_.end(), byte_ptr, byte_ptr + length);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000649}
650
651namespace {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000652
653// Parses a 64 bit base-10 int from a string and returns it. Returns 0
654// on error. If the string contains "0", that's indistinguishable from
655// error.
656off_t ParseInt(const string& str) {
657 off_t ret = 0;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700658 int rc = sscanf(str.c_str(), "%" PRIi64, &ret); // NOLINT(runtime/printf)
rspangler@google.com49fdf182009-10-10 00:57:34 +0000659 if (rc < 1) {
660 // failure
661 return 0;
662 }
663 return ret;
664}
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700665
David Zeuthene8ed8632014-07-24 13:38:10 -0400666// Parses |str| and returns |true| if, and only if, its value is "true".
667bool ParseBool(const string& str) {
668 return str == "true";
669}
670
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700671// Update the last ping day preferences based on the server daystart
672// response. Returns true on success, false otherwise.
David Zeuthene8ed8632014-07-24 13:38:10 -0400673bool UpdateLastPingDays(OmahaParserData *parser_data, PrefsInterface* prefs) {
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700674 int64_t elapsed_seconds = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -0400675 TEST_AND_RETURN_FALSE(
676 base::StringToInt64(parser_data->daystart_elapsed_seconds,
677 &elapsed_seconds));
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700678 TEST_AND_RETURN_FALSE(elapsed_seconds >= 0);
679
680 // Remember the local time that matches the server's last midnight
681 // time.
682 Time daystart = Time::Now() - TimeDelta::FromSeconds(elapsed_seconds);
683 prefs->SetInt64(kPrefsLastActivePingDay, daystart.ToInternalValue());
684 prefs->SetInt64(kPrefsLastRollCallPingDay, daystart.ToInternalValue());
685 return true;
686}
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700687} // namespace
rspangler@google.com49fdf182009-10-10 00:57:34 +0000688
David Zeuthene8ed8632014-07-24 13:38:10 -0400689bool OmahaRequestAction::ParseResponse(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700690 OmahaResponse* output_object,
691 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400692 if (parser_data->updatecheck_status.empty()) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700693 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700694 return false;
695 }
696
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800697 // chromium-os:37289: The PollInterval is not supported by Omaha server
698 // currently. But still keeping this existing code in case we ever decide to
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700699 // slow down the request rate from the server-side. Note that the PollInterval
700 // is not persisted, so it has to be sent by the server on every response to
701 // guarantee that the scheduler uses this value (otherwise, if the device got
702 // rebooted after the last server-indicated value, it'll revert to the default
703 // value). Also kDefaultMaxUpdateChecks value for the scattering logic is
704 // based on the assumption that we perform an update check every hour so that
705 // the max value of 8 will roughly be equivalent to one work day. If we decide
706 // to use PollInterval permanently, we should update the
707 // max_update_checks_allowed to take PollInterval into account. Note: The
708 // parsing for PollInterval happens even before parsing of the status because
709 // we may want to specify the PollInterval even when there's no update.
David Zeuthene8ed8632014-07-24 13:38:10 -0400710 base::StringToInt(parser_data->updatecheck_poll_interval,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700711 &output_object->poll_interval);
712
David Zeuthen639aa362014-02-03 16:23:44 -0800713 // Check for the "elapsed_days" attribute in the "daystart"
714 // element. This is the number of days since Jan 1 2007, 0:00
715 // PST. If we don't have a persisted value of the Omaha InstallDate,
716 // we'll use it to calculate it and then persist it.
David Zeuthene8ed8632014-07-24 13:38:10 -0400717 if (ParseInstallDate(parser_data, output_object) &&
718 !HasInstallDate(system_state_)) {
David Zeuthen639aa362014-02-03 16:23:44 -0800719 // Since output_object->install_date_days is never negative, the
720 // elapsed_days -> install-date calculation is reduced to simply
721 // rounding down to the nearest number divisible by 7.
722 int remainder = output_object->install_date_days % 7;
723 int install_date_days_rounded =
724 output_object->install_date_days - remainder;
725 if (PersistInstallDate(system_state_,
726 install_date_days_rounded,
727 kProvisionedFromOmahaResponse)) {
728 LOG(INFO) << "Set the Omaha InstallDate from Omaha Response to "
729 << install_date_days_rounded << " days";
730 }
731 }
732
Alex Deymo00d79ac2015-06-29 15:41:49 -0700733 // We persist the cohorts sent by omaha even if the status is "noupdate".
734 if (parser_data->app_cohort_set)
735 PersistCohortData(kPrefsOmahaCohort, parser_data->app_cohort);
736 if (parser_data->app_cohorthint_set)
737 PersistCohortData(kPrefsOmahaCohortHint, parser_data->app_cohorthint);
738 if (parser_data->app_cohortname_set)
739 PersistCohortData(kPrefsOmahaCohortName, parser_data->app_cohortname);
740
David Zeuthene8ed8632014-07-24 13:38:10 -0400741 if (!ParseStatus(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700742 return false;
743
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800744 // Note: ParseUrls MUST be called before ParsePackage as ParsePackage
745 // appends the package name to the URLs populated in this method.
David Zeuthene8ed8632014-07-24 13:38:10 -0400746 if (!ParseUrls(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700747 return false;
748
David Zeuthene8ed8632014-07-24 13:38:10 -0400749 if (!ParsePackage(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700750 return false;
751
David Zeuthene8ed8632014-07-24 13:38:10 -0400752 if (!ParseParams(parser_data, output_object, completer))
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700753 return false;
754
755 return true;
756}
757
David Zeuthene8ed8632014-07-24 13:38:10 -0400758bool OmahaRequestAction::ParseStatus(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700759 OmahaResponse* output_object,
760 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400761 const string& status = parser_data->updatecheck_status;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700762 if (status == "noupdate") {
763 LOG(INFO) << "No update.";
764 output_object->update_exists = false;
765 SetOutputObject(*output_object);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700766 completer->set_code(ErrorCode::kSuccess);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700767 return false;
768 }
769
770 if (status != "ok") {
771 LOG(ERROR) << "Unknown Omaha response status: " << status;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700772 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700773 return false;
774 }
775
776 return true;
777}
778
David Zeuthene8ed8632014-07-24 13:38:10 -0400779bool OmahaRequestAction::ParseUrls(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700780 OmahaResponse* output_object,
781 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400782 if (parser_data->url_codebase.empty()) {
783 LOG(ERROR) << "No Omaha Response URLs";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700784 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700785 return false;
786 }
787
David Zeuthene8ed8632014-07-24 13:38:10 -0400788 LOG(INFO) << "Found " << parser_data->url_codebase.size() << " url(s)";
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800789 output_object->payload_urls.clear();
David Zeuthene8ed8632014-07-24 13:38:10 -0400790 for (const auto& codebase : parser_data->url_codebase) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800791 if (codebase.empty()) {
792 LOG(ERROR) << "Omaha Response URL has empty codebase";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700793 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800794 return false;
795 }
796 output_object->payload_urls.push_back(codebase);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700797 }
798
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700799 return true;
800}
801
David Zeuthene8ed8632014-07-24 13:38:10 -0400802bool OmahaRequestAction::ParsePackage(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->package_name.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700806 LOG(ERROR) << "Omaha Response has empty package name";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700807 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700808 return false;
809 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800810
811 // Append the package name to each URL in our list so that we don't
812 // propagate the urlBase vs packageName distinctions beyond this point.
813 // From now on, we only need to use payload_urls.
David Zeuthene8ed8632014-07-24 13:38:10 -0400814 for (auto& payload_url : output_object->payload_urls)
815 payload_url += parser_data->package_name;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700816
817 // Parse the payload size.
David Zeuthene8ed8632014-07-24 13:38:10 -0400818 off_t size = ParseInt(parser_data->package_size);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700819 if (size <= 0) {
820 LOG(ERROR) << "Omaha Response has invalid payload size: " << size;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700821 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700822 return false;
823 }
824 output_object->size = size;
825
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800826 LOG(INFO) << "Payload size = " << output_object->size << " bytes";
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700827
828 return true;
829}
830
David Zeuthene8ed8632014-07-24 13:38:10 -0400831bool OmahaRequestAction::ParseParams(OmahaParserData* parser_data,
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700832 OmahaResponse* output_object,
833 ScopedActionCompleter* completer) {
David Zeuthene8ed8632014-07-24 13:38:10 -0400834 output_object->version = parser_data->manifest_version;
Chris Sosa3b748432013-06-20 16:42:59 -0700835 if (output_object->version.empty()) {
Chris Sosaaa18e162013-06-20 13:20:30 -0700836 LOG(ERROR) << "Omaha Response does not have version in manifest!";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700837 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Chris Sosa3b748432013-06-20 16:42:59 -0700838 return false;
839 }
840
841 LOG(INFO) << "Received omaha response to update to version "
842 << output_object->version;
843
David Zeuthene8ed8632014-07-24 13:38:10 -0400844 map<string, string> attrs = parser_data->action_postinstall_attrs;
845 if (attrs.empty()) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700846 LOG(ERROR) << "Omaha Response has no postinstall event action";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700847 completer->set_code(ErrorCode::kOmahaResponseInvalid);
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700848 return false;
849 }
850
David Zeuthene8ed8632014-07-24 13:38:10 -0400851 output_object->hash = attrs[kTagSha256];
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700852 if (output_object->hash.empty()) {
853 LOG(ERROR) << "Omaha Response has empty sha256 value";
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
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800858 // Get the optional properties one by one.
David Zeuthene8ed8632014-07-24 13:38:10 -0400859 output_object->more_info_url = attrs[kTagMoreInfo];
860 output_object->metadata_size = ParseInt(attrs[kTagMetadataSize]);
861 output_object->metadata_signature = attrs[kTagMetadataSignatureRsa];
862 output_object->prompt = ParseBool(attrs[kTagPrompt]);
863 output_object->deadline = attrs[kTagDeadline];
864 output_object->max_days_to_scatter = ParseInt(attrs[kTagMaxDaysToScatter]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700865 output_object->disable_p2p_for_downloading =
David Zeuthene8ed8632014-07-24 13:38:10 -0400866 ParseBool(attrs[kTagDisableP2PForDownloading]);
David Zeuthen8f191b22013-08-06 12:27:50 -0700867 output_object->disable_p2p_for_sharing =
David Zeuthene8ed8632014-07-24 13:38:10 -0400868 ParseBool(attrs[kTagDisableP2PForSharing]);
869 output_object->public_key_rsa = attrs[kTagPublicKeyRsa];
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800870
David Zeuthene8ed8632014-07-24 13:38:10 -0400871 string max = attrs[kTagMaxFailureCountPerUrl];
Jay Srinivasan08262882012-12-28 19:29:43 -0800872 if (!base::StringToUint(max, &output_object->max_failure_count_per_url))
Jay Srinivasan2b5a0f02012-12-19 17:25:56 -0800873 output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl;
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700874
David Zeuthene8ed8632014-07-24 13:38:10 -0400875 output_object->is_delta_payload = ParseBool(attrs[kTagIsDeltaPayload]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800876
877 output_object->disable_payload_backoff =
David Zeuthene8ed8632014-07-24 13:38:10 -0400878 ParseBool(attrs[kTagDisablePayloadBackoff]);
Jay Srinivasan08262882012-12-28 19:29:43 -0800879
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700880 return true;
881}
882
David Zeuthene8ed8632014-07-24 13:38:10 -0400883// If the transfer was successful, this uses expat to parse the response
rspangler@google.com49fdf182009-10-10 00:57:34 +0000884// and fill in the appropriate fields of the output object. Also, notifies
885// the processor that we're done.
Darin Petkov6a5b3222010-07-13 14:55:28 -0700886void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher,
887 bool successful) {
rspangler@google.com49fdf182009-10-10 00:57:34 +0000888 ScopedActionCompleter completer(processor_, this);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800889 string current_response(response_buffer_.begin(), response_buffer_.end());
890 LOG(INFO) << "Omaha request response: " << current_response;
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700891
Gilad Arnold74b5f552014-10-07 08:17:16 -0700892 PayloadStateInterface* const payload_state = system_state_->payload_state();
893
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700894 // Events are best effort transactions -- assume they always succeed.
895 if (IsEvent()) {
896 CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests.";
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800897 if (event_->result == OmahaEvent::kResultError && successful &&
J. Richard Barnette056b0ab2013-10-29 15:24:56 -0700898 system_state_->hardware()->IsOfficialBuild()) {
Andrew de los Reyes2008e4c2011-01-12 10:17:52 -0800899 LOG(INFO) << "Signalling Crash Reporter.";
900 utils::ScheduleCrashReporterUpload();
901 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700902 completer.set_code(ErrorCode::kSuccess);
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700903 return;
904 }
905
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700906 if (!successful) {
Darin Petkov0dc8e9a2010-07-14 14:51:57 -0700907 LOG(ERROR) << "Omaha request network transfer failed.";
Darin Petkovedc522e2010-11-05 09:35:17 -0700908 int code = GetHTTPResponseCode();
909 // Makes sure we send sane error values.
910 if (code < 0 || code >= 1000) {
911 code = 999;
912 }
David Zeuthena99981f2013-04-29 13:42:47 -0700913 completer.set_code(static_cast<ErrorCode>(
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700914 static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + code));
rspangler@google.com49fdf182009-10-10 00:57:34 +0000915 return;
Andrew de los Reyesf98bff82010-05-06 13:33:25 -0700916 }
rspangler@google.com49fdf182009-10-10 00:57:34 +0000917
David Zeuthene8ed8632014-07-24 13:38:10 -0400918 XML_Parser parser = XML_ParserCreate(nullptr);
David Zeuthenf3e28012014-08-26 18:23:52 -0400919 OmahaParserData parser_data(parser);
David Zeuthene8ed8632014-07-24 13:38:10 -0400920 XML_SetUserData(parser, &parser_data);
921 XML_SetElementHandler(parser, ParserHandlerStart, ParserHandlerEnd);
David Zeuthenf3e28012014-08-26 18:23:52 -0400922 XML_SetEntityDeclHandler(parser, ParserHandlerEntityDecl);
Alex Vakulenkof68bbbc2015-02-09 12:53:18 -0800923 XML_Status res = XML_Parse(
924 parser,
925 reinterpret_cast<const char*>(response_buffer_.data()),
926 response_buffer_.size(),
927 XML_TRUE);
David Zeuthene8ed8632014-07-24 13:38:10 -0400928 XML_ParserFree(parser);
929
930 if (res != XML_STATUS_OK || parser_data.failed) {
Alex Deymoa9bb7dc2015-06-19 09:50:23 -0700931 LOG(ERROR) << "Omaha response not valid XML: "
932 << XML_ErrorString(XML_GetErrorCode(parser))
933 << " at line " << XML_GetCurrentLineNumber(parser)
934 << " col " << XML_GetCurrentColumnNumber(parser);
David Zeuthenf3e28012014-08-26 18:23:52 -0400935 ErrorCode error_code = ErrorCode::kOmahaRequestXMLParseError;
936 if (response_buffer_.empty()) {
937 error_code = ErrorCode::kOmahaRequestEmptyResponseError;
938 } else if (parser_data.entity_decl) {
939 error_code = ErrorCode::kOmahaRequestXMLHasEntityDecl;
940 }
941 completer.set_code(error_code);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000942 return;
943 }
944
Alex Deymoebbe7ef2014-10-30 13:02:49 -0700945 // Update the last ping day preferences based on the server daystart response
946 // even if we didn't send a ping. Omaha always includes the daystart in the
947 // response, but log the error if it didn't.
948 LOG_IF(ERROR, !UpdateLastPingDays(&parser_data, system_state_->prefs()))
949 << "Failed to update the last ping day preferences!";
Darin Petkov1cbd78f2010-07-29 12:38:34 -0700950
Thieu Le116fda32011-04-19 11:01:54 -0700951 if (!HasOutputPipe()) {
952 // Just set success to whether or not the http transfer succeeded,
953 // which must be true at this point in the code.
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700954 completer.set_code(ErrorCode::kSuccess);
Thieu Le116fda32011-04-19 11:01:54 -0700955 return;
956 }
957
Darin Petkov6a5b3222010-07-13 14:55:28 -0700958 OmahaResponse output_object;
David Zeuthene8ed8632014-07-24 13:38:10 -0400959 if (!ParseResponse(&parser_data, &output_object, &completer))
rspangler@google.com49fdf182009-10-10 00:57:34 +0000960 return;
David Zeuthen8f191b22013-08-06 12:27:50 -0700961 output_object.update_exists = true;
962 SetOutputObject(output_object);
rspangler@google.com49fdf182009-10-10 00:57:34 +0000963
Chris Sosa77f79e82014-06-02 18:16:24 -0700964 if (ShouldIgnoreUpdate(output_object)) {
Jay Srinivasan23b92a52012-10-27 02:00:21 -0700965 output_object.update_exists = false;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700966 completer.set_code(ErrorCode::kOmahaUpdateIgnoredPerPolicy);
Jay Srinivasan0a708742012-03-20 11:26:12 -0700967 return;
968 }
969
David Zeuthen8f191b22013-08-06 12:27:50 -0700970 // If Omaha says to disable p2p, respect that
971 if (output_object.disable_p2p_for_downloading) {
972 LOG(INFO) << "Forcibly disabling use of p2p for downloading as "
973 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700974 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700975 }
976 if (output_object.disable_p2p_for_sharing) {
977 LOG(INFO) << "Forcibly disabling use of p2p for sharing as "
978 << "requested by Omaha.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700979 payload_state->SetUsingP2PForSharing(false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700980 }
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800981
982 // Update the payload state with the current response. The payload state
983 // will automatically reset all stale state if this response is different
Jay Srinivasan08262882012-12-28 19:29:43 -0800984 // from what's stored already. We are updating the payload state as late
985 // as possible in this method so that if a new release gets pushed and then
986 // got pulled back due to some issues, we don't want to clear our internal
987 // state unnecessarily.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800988 payload_state->SetResponse(output_object);
Jay Srinivasan08262882012-12-28 19:29:43 -0800989
David Zeuthen8f191b22013-08-06 12:27:50 -0700990 // It could be we've already exceeded the deadline for when p2p is
991 // allowed or that we've tried too many times with p2p. Check that.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700992 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -0700993 payload_state->P2PNewAttempt();
994 if (!payload_state->P2PAttemptAllowed()) {
995 LOG(INFO) << "Forcibly disabling use of p2p for downloading because "
996 << "of previous failures when using p2p.";
Gilad Arnold74b5f552014-10-07 08:17:16 -0700997 payload_state->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -0700998 }
999 }
1000
1001 // From here on, we'll complete stuff in CompleteProcessing() so
1002 // disable |completer| since we'll create a new one in that
1003 // function.
1004 completer.set_should_complete(false);
1005
1006 // If we're allowed to use p2p for downloading we do not pay
1007 // attention to wall-clock-based waiting if the URL is indeed
1008 // available via p2p. Therefore, check if the file is available via
1009 // p2p before deferring...
Gilad Arnold74b5f552014-10-07 08:17:16 -07001010 if (payload_state->GetUsingP2PForDownloading()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001011 LookupPayloadViaP2P(output_object);
1012 } else {
1013 CompleteProcessing();
1014 }
1015}
1016
1017void OmahaRequestAction::CompleteProcessing() {
1018 ScopedActionCompleter completer(processor_, this);
1019 OmahaResponse& output_object = const_cast<OmahaResponse&>(GetOutputObject());
1020 PayloadStateInterface* payload_state = system_state_->payload_state();
1021
1022 if (ShouldDeferDownload(&output_object)) {
Jay Srinivasan08262882012-12-28 19:29:43 -08001023 output_object.update_exists = false;
David Zeuthen8f191b22013-08-06 12:27:50 -07001024 LOG(INFO) << "Ignoring Omaha updates as updates are deferred by policy.";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001025 completer.set_code(ErrorCode::kOmahaUpdateDeferredPerPolicy);
Jay Srinivasan08262882012-12-28 19:29:43 -08001026 return;
1027 }
David Zeuthen8f191b22013-08-06 12:27:50 -07001028
Chris Sosa20f005c2013-09-05 13:53:08 -07001029 if (payload_state->ShouldBackoffDownload()) {
1030 output_object.update_exists = false;
1031 LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry "
1032 << "attempts";
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001033 completer.set_code(ErrorCode::kOmahaUpdateDeferredForBackoff);
Chris Sosa20f005c2013-09-05 13:53:08 -07001034 return;
David Zeuthen8f191b22013-08-06 12:27:50 -07001035 }
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001036 completer.set_code(ErrorCode::kSuccess);
David Zeuthen8f191b22013-08-06 12:27:50 -07001037}
1038
1039void OmahaRequestAction::OnLookupPayloadViaP2PCompleted(const string& url) {
1040 LOG(INFO) << "Lookup complete, p2p-client returned URL '" << url << "'";
1041 if (!url.empty()) {
Gilad Arnold74b5f552014-10-07 08:17:16 -07001042 system_state_->payload_state()->SetP2PUrl(url);
David Zeuthen8f191b22013-08-06 12:27:50 -07001043 } else {
1044 LOG(INFO) << "Forcibly disabling use of p2p for downloading "
1045 << "because no suitable peer could be found.";
Gilad Arnold74b5f552014-10-07 08:17:16 -07001046 system_state_->payload_state()->SetUsingP2PForDownloading(false);
David Zeuthen8f191b22013-08-06 12:27:50 -07001047 }
1048 CompleteProcessing();
1049}
1050
1051void OmahaRequestAction::LookupPayloadViaP2P(const OmahaResponse& response) {
David Zeuthen41996ad2013-09-24 15:43:24 -07001052 // If the device is in the middle of an update, the state variables
1053 // kPrefsUpdateStateNextDataOffset, kPrefsUpdateStateNextDataLength
1054 // tracks the offset and length of the operation currently in
1055 // progress. The offset is based from the end of the manifest which
1056 // is kPrefsManifestMetadataSize bytes long.
1057 //
1058 // To make forward progress and avoid deadlocks, we need to find a
1059 // peer that has at least the entire operation we're currently
1060 // working on. Otherwise we may end up in a situation where two
1061 // devices bounce back and forth downloading from each other,
1062 // neither making any forward progress until one of them decides to
1063 // stop using p2p (via kMaxP2PAttempts and kMaxP2PAttemptTimeSeconds
1064 // safe-guards). See http://crbug.com/297170 for an example)
David Zeuthen8f191b22013-08-06 12:27:50 -07001065 size_t minimum_size = 0;
David Zeuthen41996ad2013-09-24 15:43:24 -07001066 int64_t manifest_metadata_size = 0;
1067 int64_t next_data_offset = 0;
1068 int64_t next_data_length = 0;
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001069 if (system_state_ &&
David Zeuthen41996ad2013-09-24 15:43:24 -07001070 system_state_->prefs()->GetInt64(kPrefsManifestMetadataSize,
1071 &manifest_metadata_size) &&
1072 manifest_metadata_size != -1 &&
David Zeuthen8f191b22013-08-06 12:27:50 -07001073 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataOffset,
David Zeuthen41996ad2013-09-24 15:43:24 -07001074 &next_data_offset) &&
1075 next_data_offset != -1 &&
1076 system_state_->prefs()->GetInt64(kPrefsUpdateStateNextDataLength,
1077 &next_data_length)) {
1078 minimum_size = manifest_metadata_size + next_data_offset + next_data_length;
David Zeuthen8f191b22013-08-06 12:27:50 -07001079 }
1080
1081 string file_id = utils::CalculateP2PFileId(response.hash, response.size);
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001082 if (system_state_->p2p_manager()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001083 LOG(INFO) << "Checking if payload is available via p2p, file_id="
1084 << file_id << " minimum_size=" << minimum_size;
1085 system_state_->p2p_manager()->LookupUrlForFile(
1086 file_id,
1087 minimum_size,
David Zeuthen4cc5ed22014-01-15 12:35:03 -08001088 TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds),
David Zeuthen8f191b22013-08-06 12:27:50 -07001089 base::Bind(&OmahaRequestAction::OnLookupPayloadViaP2PCompleted,
1090 base::Unretained(this)));
1091 }
rspangler@google.com49fdf182009-10-10 00:57:34 +00001092}
1093
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001094bool OmahaRequestAction::ShouldDeferDownload(OmahaResponse* output_object) {
Chris Sosa968d0572013-08-23 14:46:02 -07001095 if (params_->interactive()) {
1096 LOG(INFO) << "Not deferring download because update is interactive.";
1097 return false;
1098 }
1099
David Zeuthen8f191b22013-08-06 12:27:50 -07001100 // If we're using p2p to download _and_ we have a p2p URL, we never
1101 // defer the download. This is because the download will always
1102 // happen from a peer on the LAN and we've been waiting in line for
1103 // our turn.
Gilad Arnold74b5f552014-10-07 08:17:16 -07001104 const PayloadStateInterface* payload_state = system_state_->payload_state();
1105 if (payload_state->GetUsingP2PForDownloading() &&
1106 !payload_state->GetP2PUrl().empty()) {
David Zeuthen8f191b22013-08-06 12:27:50 -07001107 LOG(INFO) << "Download not deferred because download "
1108 << "will happen from a local peer (via p2p).";
1109 return false;
1110 }
1111
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001112 // We should defer the downloads only if we've first satisfied the
1113 // wall-clock-based-waiting period and then the update-check-based waiting
1114 // period, if required.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001115 if (!params_->wall_clock_based_wait_enabled()) {
Chris Sosa968d0572013-08-23 14:46:02 -07001116 LOG(INFO) << "Wall-clock-based waiting period is not enabled,"
1117 << " so no deferring needed.";
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001118 return false;
1119 }
1120
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001121 switch (IsWallClockBasedWaitingSatisfied(output_object)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001122 case kWallClockWaitNotSatisfied:
1123 // We haven't even satisfied the first condition, passing the
1124 // wall-clock-based waiting period, so we should defer the downloads
1125 // until that happens.
1126 LOG(INFO) << "wall-clock-based-wait not satisfied.";
1127 return true;
1128
1129 case kWallClockWaitDoneButUpdateCheckWaitRequired:
1130 LOG(INFO) << "wall-clock-based-wait satisfied and "
1131 << "update-check-based-wait required.";
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001132 return !IsUpdateCheckCountBasedWaitingSatisfied();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001133
1134 case kWallClockWaitDoneAndUpdateCheckWaitNotRequired:
1135 // Wall-clock-based waiting period is satisfied, and it's determined
1136 // that we do not need the update-check-based wait. so no need to
1137 // defer downloads.
1138 LOG(INFO) << "wall-clock-based-wait satisfied and "
1139 << "update-check-based-wait is not required.";
1140 return false;
1141
1142 default:
1143 // Returning false for this default case so we err on the
1144 // side of downloading updates than deferring in case of any bugs.
1145 NOTREACHED();
1146 return false;
1147 }
1148}
1149
1150OmahaRequestAction::WallClockWaitResult
1151OmahaRequestAction::IsWallClockBasedWaitingSatisfied(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001152 OmahaResponse* output_object) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001153 Time update_first_seen_at;
Ben Chan9abb7632014-08-07 00:10:53 -07001154 int64_t update_first_seen_at_int;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001155
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001156 if (system_state_->prefs()->Exists(kPrefsUpdateFirstSeenAt)) {
1157 if (system_state_->prefs()->GetInt64(kPrefsUpdateFirstSeenAt,
1158 &update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001159 // Note: This timestamp could be that of ANY update we saw in the past
1160 // (not necessarily this particular update we're considering to apply)
1161 // but never got to apply because of some reason (e.g. stop AU policy,
1162 // updates being pulled out from Omaha, changes in target version prefix,
1163 // new update being rolled out, etc.). But for the purposes of scattering
1164 // it doesn't matter which update the timestamp corresponds to. i.e.
1165 // the clock starts ticking the first time we see an update and we're
1166 // ready to apply when the random wait period is satisfied relative to
1167 // that first seen timestamp.
1168 update_first_seen_at = Time::FromInternalValue(update_first_seen_at_int);
1169 LOG(INFO) << "Using persisted value of UpdateFirstSeenAt: "
1170 << utils::ToString(update_first_seen_at);
1171 } else {
1172 // This seems like an unexpected error where the persisted value exists
1173 // but it's not readable for some reason. Just skip scattering in this
1174 // case to be safe.
1175 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value cannot be read";
1176 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1177 }
1178 } else {
1179 update_first_seen_at = Time::Now();
1180 update_first_seen_at_int = update_first_seen_at.ToInternalValue();
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001181 if (system_state_->prefs()->SetInt64(kPrefsUpdateFirstSeenAt,
1182 update_first_seen_at_int)) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001183 LOG(INFO) << "Persisted the new value for UpdateFirstSeenAt: "
1184 << utils::ToString(update_first_seen_at);
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001185 } else {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001186 // This seems like an unexpected error where the value cannot be
1187 // persisted for some reason. Just skip scattering in this
1188 // case to be safe.
1189 LOG(INFO) << "Not scattering as UpdateFirstSeenAt value "
1190 << utils::ToString(update_first_seen_at)
1191 << " cannot be persisted";
1192 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1193 }
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001194 }
1195
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001196 TimeDelta elapsed_time = Time::Now() - update_first_seen_at;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001197 TimeDelta max_scatter_period = TimeDelta::FromDays(
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001198 output_object->max_days_to_scatter);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001199
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001200 LOG(INFO) << "Waiting Period = "
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001201 << utils::FormatSecs(params_->waiting_period().InSeconds())
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001202 << ", Time Elapsed = "
1203 << utils::FormatSecs(elapsed_time.InSeconds())
1204 << ", MaxDaysToScatter = "
1205 << max_scatter_period.InDays();
1206
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001207 if (!output_object->deadline.empty()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001208 // The deadline is set for all rules which serve a delta update from a
1209 // previous FSI, which means this update will be applied mostly in OOBE
1210 // cases. For these cases, we shouldn't scatter so as to finish the OOBE
1211 // quickly.
1212 LOG(INFO) << "Not scattering as deadline flag is set";
1213 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1214 }
1215
1216 if (max_scatter_period.InDays() == 0) {
1217 // This means the Omaha rule creator decides that this rule
1218 // should not be scattered irrespective of the policy.
1219 LOG(INFO) << "Not scattering as MaxDaysToScatter in rule is 0.";
1220 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1221 }
1222
1223 if (elapsed_time > max_scatter_period) {
Jay Srinivasan34b5d862012-07-23 11:43:22 -07001224 // This means we've waited more than the upperbound wait in the rule
1225 // from the time we first saw a valid update available to us.
1226 // This will prevent update starvation.
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001227 LOG(INFO) << "Not scattering as we're past the MaxDaysToScatter limit.";
1228 return kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1229 }
1230
1231 // This means we are required to participate in scattering.
1232 // See if our turn has arrived now.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001233 TimeDelta remaining_wait_time = params_->waiting_period() - elapsed_time;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001234 if (remaining_wait_time.InSeconds() <= 0) {
1235 // Yes, it's our turn now.
1236 LOG(INFO) << "Successfully passed the wall-clock-based-wait.";
1237
1238 // But we can't download until the update-check-count-based wait is also
1239 // satisfied, so mark it as required now if update checks are enabled.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001240 return params_->update_check_count_wait_enabled() ?
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001241 kWallClockWaitDoneButUpdateCheckWaitRequired :
1242 kWallClockWaitDoneAndUpdateCheckWaitNotRequired;
1243 }
1244
1245 // Not our turn yet, so we have to wait until our turn to
1246 // help scatter the downloads across all clients of the enterprise.
1247 LOG(INFO) << "Update deferred for another "
1248 << utils::FormatSecs(remaining_wait_time.InSeconds())
1249 << " per policy.";
1250 return kWallClockWaitNotSatisfied;
1251}
1252
Jay Srinivasan23b92a52012-10-27 02:00:21 -07001253bool OmahaRequestAction::IsUpdateCheckCountBasedWaitingSatisfied() {
Ben Chan9abb7632014-08-07 00:10:53 -07001254 int64_t update_check_count_value;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001255
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001256 if (system_state_->prefs()->Exists(kPrefsUpdateCheckCount)) {
1257 if (!system_state_->prefs()->GetInt64(kPrefsUpdateCheckCount,
1258 &update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001259 // We are unable to read the update check count from file for some reason.
1260 // So let's proceed anyway so as to not stall the update.
1261 LOG(ERROR) << "Unable to read update check count. "
1262 << "Skipping update-check-count-based-wait.";
1263 return true;
1264 }
1265 } else {
1266 // This file does not exist. This means we haven't started our update
1267 // check count down yet, so this is the right time to start the count down.
1268 update_check_count_value = base::RandInt(
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001269 params_->min_update_checks_needed(),
1270 params_->max_update_checks_allowed());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001271
1272 LOG(INFO) << "Randomly picked update check count value = "
1273 << update_check_count_value;
1274
1275 // Write out the initial value of update_check_count_value.
Jay Srinivasan6f6ea002012-12-14 11:26:28 -08001276 if (!system_state_->prefs()->SetInt64(kPrefsUpdateCheckCount,
1277 update_check_count_value)) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001278 // We weren't able to write the update check count file for some reason.
1279 // So let's proceed anyway so as to not stall the update.
1280 LOG(ERROR) << "Unable to write update check count. "
1281 << "Skipping update-check-count-based-wait.";
1282 return true;
1283 }
1284 }
1285
1286 if (update_check_count_value == 0) {
1287 LOG(INFO) << "Successfully passed the update-check-based-wait.";
1288 return true;
1289 }
1290
1291 if (update_check_count_value < 0 ||
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001292 update_check_count_value > params_->max_update_checks_allowed()) {
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001293 // We err on the side of skipping scattering logic instead of stalling
1294 // a machine from receiving any updates in case of any unexpected state.
1295 LOG(ERROR) << "Invalid value for update check count detected. "
1296 << "Skipping update-check-count-based-wait.";
1297 return true;
1298 }
1299
1300 // Legal value, we need to wait for more update checks to happen
1301 // until this becomes 0.
1302 LOG(INFO) << "Deferring Omaha updates for another "
1303 << update_check_count_value
1304 << " update checks per policy";
1305 return false;
1306}
1307
David Zeuthen639aa362014-02-03 16:23:44 -08001308// static
David Zeuthene8ed8632014-07-24 13:38:10 -04001309bool OmahaRequestAction::ParseInstallDate(OmahaParserData* parser_data,
David Zeuthen639aa362014-02-03 16:23:44 -08001310 OmahaResponse* output_object) {
David Zeuthen639aa362014-02-03 16:23:44 -08001311 int64_t elapsed_days = 0;
David Zeuthene8ed8632014-07-24 13:38:10 -04001312 if (!base::StringToInt64(parser_data->daystart_elapsed_days,
David Zeuthen639aa362014-02-03 16:23:44 -08001313 &elapsed_days))
1314 return false;
1315
1316 if (elapsed_days < 0)
1317 return false;
1318
1319 output_object->install_date_days = elapsed_days;
1320 return true;
1321}
1322
1323// static
1324bool OmahaRequestAction::HasInstallDate(SystemState *system_state) {
1325 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001326 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001327 return false;
1328
1329 return prefs->Exists(kPrefsInstallDateDays);
1330}
1331
1332// static
1333bool OmahaRequestAction::PersistInstallDate(
1334 SystemState *system_state,
1335 int install_date_days,
1336 InstallDateProvisioningSource source) {
1337 TEST_AND_RETURN_FALSE(install_date_days >= 0);
1338
1339 PrefsInterface* prefs = system_state->prefs();
Alex Vakulenko88b591f2014-08-28 16:48:57 -07001340 if (prefs == nullptr)
David Zeuthen639aa362014-02-03 16:23:44 -08001341 return false;
1342
1343 if (!prefs->SetInt64(kPrefsInstallDateDays, install_date_days))
1344 return false;
1345
Alex Deymoaf9a8632015-09-23 18:51:48 -07001346 string metric_name = metrics::kMetricInstallDateProvisioningSource;
David Zeuthen33bae492014-02-25 16:16:18 -08001347 system_state->metrics_lib()->SendEnumToUMA(
1348 metric_name,
1349 static_cast<int>(source), // Sample.
1350 kProvisionedMax); // Maximum.
David Zeuthen639aa362014-02-03 16:23:44 -08001351
1352 return true;
1353}
1354
Alex Deymo8e18f932015-03-27 16:16:59 -07001355bool OmahaRequestAction::PersistCohortData(
1356 const string& prefs_key,
1357 const string& new_value) {
1358 if (new_value.empty() && system_state_->prefs()->Exists(prefs_key)) {
1359 LOG(INFO) << "Removing stored " << prefs_key << " value.";
1360 return system_state_->prefs()->Delete(prefs_key);
1361 } else if (!new_value.empty()) {
1362 LOG(INFO) << "Storing new setting " << prefs_key << " as " << new_value;
1363 return system_state_->prefs()->SetString(prefs_key, new_value);
1364 }
1365 return true;
1366}
1367
David Zeuthen33bae492014-02-25 16:16:18 -08001368void OmahaRequestAction::ActionCompleted(ErrorCode code) {
1369 // We only want to report this on "update check".
1370 if (ping_only_ || event_ != nullptr)
1371 return;
1372
1373 metrics::CheckResult result = metrics::CheckResult::kUnset;
1374 metrics::CheckReaction reaction = metrics::CheckReaction::kUnset;
1375 metrics::DownloadErrorCode download_error_code =
1376 metrics::DownloadErrorCode::kUnset;
1377
1378 // Regular update attempt.
1379 switch (code) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001380 case ErrorCode::kSuccess:
David Zeuthen33bae492014-02-25 16:16:18 -08001381 // OK, we parsed the response successfully but that does
1382 // necessarily mean that an update is available.
1383 if (HasOutputPipe()) {
1384 const OmahaResponse& response = GetOutputObject();
1385 if (response.update_exists) {
1386 result = metrics::CheckResult::kUpdateAvailable;
1387 reaction = metrics::CheckReaction::kUpdating;
1388 } else {
1389 result = metrics::CheckResult::kNoUpdateAvailable;
1390 }
1391 } else {
1392 result = metrics::CheckResult::kNoUpdateAvailable;
1393 }
1394 break;
1395
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001396 case ErrorCode::kOmahaUpdateIgnoredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001397 result = metrics::CheckResult::kUpdateAvailable;
1398 reaction = metrics::CheckReaction::kIgnored;
1399 break;
1400
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001401 case ErrorCode::kOmahaUpdateDeferredPerPolicy:
David Zeuthen33bae492014-02-25 16:16:18 -08001402 result = metrics::CheckResult::kUpdateAvailable;
1403 reaction = metrics::CheckReaction::kDeferring;
1404 break;
1405
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -07001406 case ErrorCode::kOmahaUpdateDeferredForBackoff:
David Zeuthen33bae492014-02-25 16:16:18 -08001407 result = metrics::CheckResult::kUpdateAvailable;
1408 reaction = metrics::CheckReaction::kBackingOff;
1409 break;
1410
1411 default:
1412 // We report two flavors of errors, "Download errors" and "Parsing
1413 // error". Try to convert to the former and if that doesn't work
1414 // we know it's the latter.
1415 metrics::DownloadErrorCode tmp_error = utils::GetDownloadErrorCode(code);
1416 if (tmp_error != metrics::DownloadErrorCode::kInputMalformed) {
1417 result = metrics::CheckResult::kDownloadError;
1418 download_error_code = tmp_error;
1419 } else {
1420 result = metrics::CheckResult::kParsingError;
1421 }
1422 break;
1423 }
1424
1425 metrics::ReportUpdateCheckMetrics(system_state_,
1426 result, reaction, download_error_code);
1427}
1428
Chris Sosa77f79e82014-06-02 18:16:24 -07001429bool OmahaRequestAction::ShouldIgnoreUpdate(
1430 const OmahaResponse& response) const {
Chris Sosa77f79e82014-06-02 18:16:24 -07001431 // Note: policy decision to not update to a version we rolled back from.
1432 string rollback_version =
1433 system_state_->payload_state()->GetRollbackVersion();
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001434 if (!rollback_version.empty()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001435 LOG(INFO) << "Detected previous rollback from version " << rollback_version;
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001436 if (rollback_version == response.version) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001437 LOG(INFO) << "Received version that we rolled back from. Ignoring.";
1438 return true;
1439 }
1440 }
1441
Alex Vakulenkod2779df2014-06-16 13:19:00 -07001442 if (!IsUpdateAllowedOverCurrentConnection()) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001443 LOG(INFO) << "Update is not allowed over current connection.";
1444 return true;
1445 }
1446
1447 // Note: We could technically delete the UpdateFirstSeenAt state when we
1448 // return true. If we do, it'll mean a device has to restart the
1449 // UpdateFirstSeenAt and thus help scattering take effect when the AU is
1450 // turned on again. On the other hand, it also increases the chance of update
1451 // starvation if an admin turns AU on/off more frequently. We choose to err on
1452 // the side of preventing starvation at the cost of not applying scattering in
1453 // those cases.
1454 return false;
1455}
1456
1457bool OmahaRequestAction::IsUpdateAllowedOverCurrentConnection() const {
1458 NetworkConnectionType type;
1459 NetworkTethering tethering;
Alex Deymof6ee0162015-07-31 12:35:22 -07001460 ConnectionManagerInterface* connection_manager =
1461 system_state_->connection_manager();
Alex Deymo30534502015-07-20 15:06:33 -07001462 if (!connection_manager->GetConnectionProperties(&type, &tethering)) {
Chris Sosa77f79e82014-06-02 18:16:24 -07001463 LOG(INFO) << "We could not determine our connection type. "
1464 << "Defaulting to allow updates.";
1465 return true;
1466 }
1467 bool is_allowed = connection_manager->IsUpdateAllowedOver(type, tethering);
1468 LOG(INFO) << "We are connected via "
Alex Deymof6ee0162015-07-31 12:35:22 -07001469 << ConnectionManager::StringForConnectionType(type)
Chris Sosa77f79e82014-06-02 18:16:24 -07001470 << ", Updates allowed: " << (is_allowed ? "Yes" : "No");
1471 return is_allowed;
1472}
1473
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001474} // namespace chromeos_update_engine